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

...
Автор SHA1 Повідомлення Дата
Deng Liu 569cd5b6e5 test(macos): cover non-main-thread WKWebViewConfiguration creation
Extract build_macos_webview_configuration_with and add macos_webview_configuration_handles_non_main_thread to verify off-thread calls never panic on scheduling failure or missing MainThreadMarker and dispatch cleanly to the main thread when available.
2026-11-26 14:58:12 -08:00
Deng Liu 2df2e48c38 fix(macos): construct WKWebViewConfiguration on main thread when off-thread
Secondary project windows (spawn_window) and auxiliary windows (open_auxiliary_window) build off the main thread. Dispatch WKWebViewConfiguration creation to the AppKit main thread via AppHandle::run_on_main_thread with a timeout, falling back to the unmodified builder if scheduling fails or times out instead of panicking on MainThreadMarker::new().expect().
2026-11-26 14:52:31 -08:00
Deng Liu 3be9e04bfc fix(macos): disable Apple Intelligence Writing Tools in WKWebView
Selecting text in Markdown previews, Quick Documentation, or other selectable views on macOS 15+ shows Apple's floating Writing Tools badge, overlapping bullets and margins.

Set WKWebViewConfiguration.writingToolsBehavior to NSWritingToolsBehaviorNone (guarded by respondsToSelector: for macOS < 15) when building project and auxiliary windows, while preserving the debug-only OPENIDEA_DEV_DISALLOW_USER_FONTS override on the same configuration.
2026-11-26 14:43:26 -08:00
Deng Liuтаdengliu 4b5745c1b6 feat(agents): sign in to coding agents in an IDE terminal (#6263)
Agents can be signed in from the IDE: Sign In... in Settings > Agents > Agent
Setup and on a sign-in error in the chat opens a dialog running the agent's own
login flow (copilot login, codex login, claude, an ACP terminal-auth method) in
an IDE-managed PTY with the real program and arguments, no shell quoting. The
Settings window's boot provides the embedded terminal, so the dialog works there
without importing the terminal feature. Sign-in clears a failed model-catalog
cooldown and refreshes the agent's models. Copilot's login runs with ambient
GitHub token variables cleared, and copied login hints quote paths with spaces.
A test pins that every built-in login hint yields the arguments Sign In runs.

Co-authored-by: dengliu <[email protected]>
2026-11-27 06:36:26 +08:00
Mansur Akhmadiтаmansur-akhmadi 4667c81e6b feat(project-view): Show Scratches and Consoles option (#6273)
Adds the Project view's Show Scratches and Consoles option (Options >
Appearance, and a Find Action toggle), on by default. Off, the Project / Unity /
Unreal panes leave out the Scratches and Consoles root and scratch paths outside
the project; the Scratches and Consoles pane and the path-based panes are
unchanged. Select In > Project View then switches to the Scratches and Consoles
pane for a scratch the Project pane hides.

Closes #6272

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 06:29:14 +08:00
Deng Liuтаdengliu cea9d863f9 feat(github): install the GitHub CLI as a managed tool (#6271)
Registers the GitHub CLI as a managed tool (cli/cli release archives for
macOS / Linux / Windows on arm64 and x64, verified against the release's
checksums file), and offers Install GitHub CLI next to Download manually in
Pull Requests and Clone Repository > GitHub when gh is missing. An existing gh
(OPENIDEA_GH, PATH, Homebrew, Program Files, Snap) counts as installed, so no
duplicate is offered. gh is now looked up on each use instead of once per
process, so a copy installed while the IDE runs is picked up without a restart;
ide-github drops its `which` dependency for the shared tool_path lookup.

Co-authored-by: dengliu <[email protected]>
2026-11-27 06:21:21 +08:00
Vladislav Kuzmin 5fa953eddd fix(ci): scope Unix-only integration test declarations for Windows Clippy (#6259)
Windows Clippy (-D warnings) built two integration-test declarations whose only
users are Unix-only tests: tsc_errors in language_smoke.rs (used by the
TypeScript project-errors test) and the file-level Duration import in
plugin_workbench.rs (used by the PTY run-output test). Scope tsc_errors to unix
and move the import into the Unix-only test.

Fixes #6258

Co-authored-by: principalwater <[email protected]>
2026-11-27 06:06:41 +08:00
Mansur Akhmadiтаmansur-akhmadi 031f1acd07 feat(editor): Move Up / Down and Scroll actions (#6268)
Adds Move Up / Down and Scroll and their with-Selection variants as Editor
Actions (IDEA's EditorMoveUpAndScroll family, reachable from Find Action,
imported keymaps and IdeaVim :action). The carets move one line from the head,
dropping a selection unless extending, and the view scrolls by the distance the
primary caret moved (text line top below block widgets, or the visual row with
soft wrap), so the caret keeps its place on screen. Unbound by default, as in
IDEA's keymaps.

Closes #6267

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 06:04:03 +08:00
l0ng-ai add23fe97f feat(viewers): open SVG files as source with a live image preview (#6266)
SVG files open in the text editor with the image viewer beside it and the
Editor Only / Editor and Preview / Preview Only switch Markdown has. The preview
is redrawn from the source as it is typed, reports invalid SVG and recovers once
it is valid; it is drawn as an image, so scripts never run. The SVG layout is
remembered apart from Markdown's, raster images keep the image viewer, and text
editor wrappers gain `fallback` so a plugin's editor for a more specific SVG
pattern still wins.

Fixes #6234
2026-11-27 05:32:32 +08:00
l0ng-ai 3d2b0946de fix(debugger): don't sync breakpoints to the backend while no project is open (#6215)
Before a project opens (a web page booting, a welcome window) and after one
closes, loadBreakpoints(null) asked the backend to replace this window's
breakpoints; with no project the call failed with "no project is open in this
window" and logged debugReplaceBreakpoints failed on every such load. Without a
project the backend holds no breakpoints for the window, so the sync now waits
until a project root is loaded.
2026-11-27 05:18:36 +08:00
Muuтаmuutot 6c7282b442 feat(editor): choose sibling symbols from a code breadcrumb (#6106)
Clicking a code breadcrumb still navigates to its symbol. Right-clicking a crumb
offers "Choose Symbol..." and Alt+Down on a focused crumb opens the same
chooser: the existing Navigation Bar children popup, anchored on the crumb and
listing the symbol's siblings (children of the enclosing symbol, or of the file
for a top-level symbol).

Co-authored-by: muutot <[email protected]>
2026-11-27 05:17:28 +08:00
Muuтаmuutot 1f79a7f805 feat(editor): File Color submenu in the editor tab context menu (#6105)
The editor tab context menu gains the Project view's File Color submenu for
files inside the project. Its rows are action items (file.<colour>,
file.clearColor, file.editColors, registered by the project view) carrying the
path, so the editor never imports the feature and the colour is written to the
same scope + File Colors entry: the tab, the Project view and Settings > File
Colors always agree, and the choice travels with the project settings.

Co-authored-by: muutot <[email protected]>
2026-11-27 05:15:51 +08:00
Muuтаmuutot 3d1eaf71e4 feat(java): pass the import-on-demand thresholds to jdtls (#6117)
Adds Settings > Code Style > Java > Imports with "Class count to use import
with '*'" and "Names count to use static import with '*'", passed to jdtls as
java.sources.organizeImports.starThreshold / staticStarThreshold.

Organize imports used to collapse imports into wildcards on jdtls's defaults
(99, but jdtls keeps the last value it was sent). The thresholds are now always
sent, defaulting to 5 and 3 when the code style leaves them unset; an explicit
value in the server's own settings still wins.

Fixes #6026

Co-authored-by: muutot <[email protected]>
2026-11-27 05:13:37 +08:00
Muuтаmuutot 138209c627 feat(vcs): show Today / Yesterday in the annotate gutter with pretty dates (#6110)
The annotate gutter now shows Today / Yesterday when the global date format's "Use pretty formatting" is on, as IDEA's annotate does (FileAnnotation.formatDate -> DateFormatUtil.formatPrettyDate); older dates, and all dates with pretty formatting off, keep the short date. New formatPrettyDay next to formatTimestamp.

Co-authored-by: muutot <[email protected]>
2026-11-27 05:09:25 +08:00
Mansur Akhmadiтаmansur-akhmadi b283d352b7 feat(editor): Scroll Up / Scroll Down and Move if Necessary actions (#6256)
Adds IDEA's EditorScrollUpAndMove / EditorScrollDownAndMove: scroll by one line, then move each caret that left the fully visible lines to the first or last of them, keeping its visual column; carets still in view keep their place and selection. Reachable from Find Action, imported keymaps and IdeaVim :action; unbound by default as in IDEA. The column logic of Move Caret to Page Top / Bottom is shared through a small helper.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 05:06:05 +08:00
audichuang f7f9dabe2b fix(documents): don't treat a rewrite of the same bytes as a disk conflict (#6195)
With unsaved edits, a touch, a tool rewriting the file unchanged, or a git stash/pop the watcher missed was reported as a disk change and stopped autosave, because both the watcher and autosave's check compared only the (mtime, length) stamp. When the mtime moved but the length did not, the file's bytes are now compared with what the clean text encodes to (encoding, BOM, line endings); identical bytes adopt the new stamp. Equal text in other bytes still conflicts, and without a clean text a moved stamp still counts.

Co-authored-by: audichuang <[email protected]>
2026-11-27 05:04:18 +08:00
l0ng-ai 787d4fbcfa feat(ssh): apply LocalForward and RemoteForward from the SSH config (#6262)
Fixes #6031

`~/.ssh/config`'s `RemoteForward` and `LocalForward` were ignored by the IDE's own SSH client (remote development, SFTP, tunnels), so a forward that works with `ssh <alias>` did nothing in a remote window.

- `ide-ssh` config parsing reads `RemoteForward` / `LocalForward` as OpenSSH does: `[bind_address:]port host:hostport` or the one-argument colon form, IPv6 in brackets, `*` for every address, `localhost` by default; `ClearAllForwardings yes` drops them. Only the target's forwards apply, not a jump host's. Unix socket and dynamic (SOCKS) forwards are skipped with a debug log.
- The shared session of an SSH configuration starts them when it connects (so a reconnect restores them, and they stop when the session closes): each `RemoteForward` is a `tcpip-forward` request, and the client accepts forwarded connections only for the ports it asked for, connecting each to `host:hostport` here; each `LocalForward` listens here and opens a `direct-tcpip` channel per connection. A port that can't be forwarded (in use, refused by the server) is logged and skipped, as `ssh` warns and continues.

Tests: config parsing (forms, jump hosts, `ClearAllForwardings`), and an end-to-end test against the in-process SSH server where both forwards carry data and the local listener goes away with the session. `cargo test -p ide-ssh --all-features`, clippy on `ide-ssh`, `ide-remote`, `openidea`. Not run against a real remote host.
2026-11-27 05:02:12 +08:00
l0ng-ai 3fbd0e05a5 feat(java): suggest variable names from the declared type (#6261)
Fixes #6002

Typing the name of a Java declaration now lists names derived from its type, the way IntelliJ's code style manager suggests them:

- The type's name and its shorter endings: `IMesCheckStandardService` → `iMesCheckStandardService`, `mesCheckStandardService`, `checkStandardService`, `standardService`, `service`; an `Impl` suffix is dropped and an `Entity` one also offered without it.
- Collections and arrays by their contents (`List<Order>` → `orders`, …, `orderList`, `list`; `Order[]` → `orders`), `Optional<User>` → `user`, `optionalUser`, and generic types by their arguments (`Map<String, Order>` → `stringOrderMap`, `orderMap`, `map`).
- Locals and parameters also get the short names (`String` → `s`, `int` → `i`), and an exception parameter `e`.

At such a name only names fit, so the lookup there shows just these: no live templates (`psf` after `MesProductPlan p`), and not jdtls' own name proposals, which repeat the type (`orderBookOrderBook`). Detection is textual on the line (a type, then the name being typed), skipping `new`, `class`, `extends`, `throws`, `return` and similar contexts, annotations, comments and strings.

Tests: `variableNames.test.ts` (names per type kind, declaration detection and its negatives), `src/editor` vitest, typecheck, `codeCompletionSettingsLayout` e2e. Checked in the app on a Maven project with jdtls: `OrderBook b` lists `book`; `java.util.List<OrderBook> o` lists `orderBooks`, `orderBookList`.
2026-11-27 04:54:15 +08:00
116 змінених файлів з 3589 додано та 338 видалено

No files matched your search

Створено
-1
Переглянути файл
@@ -4440,7 +4440,6 @@ dependencies = [
"serde_json",
"specta",
"tracing",
"which",
]
[[package]]
+14
Переглянути файл
@@ -283,6 +283,20 @@ impl AgentCatalogs {
}
}
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
let key = Self::key(shared, provider);
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key)
&& entry.flight.is_none()
&& entry.error.is_some()
{
entry.completed = None;
entry.retry_at_ms = None;
entry.error = None;
}
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
+46
Переглянути файл
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use provider::LoginLaunch;
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
@@ -53,6 +54,21 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
/// Resolves agent `id`'s interactive sign-in command without an open project.
pub fn login_launch_without_project(
custom_agents_dir: Option<&Path>,
secrets: Option<&dyn EnvSecrets>,
cwd: &Path,
id: &str,
) -> IdeResult<LoginLaunch> {
let spec = provider::load(custom_agents_dir, secrets)
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
spec.login_launch(cwd, None)
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
}
/// Receives the events of one project's tasks.
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
@@ -201,6 +217,8 @@ struct Shared {
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
probes: Mutex<HashMap<String, AgentProbe>>,
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
@@ -706,6 +724,7 @@ impl AgentManager {
known,
providers,
probes: Mutex::new(HashMap::new()),
terminal_auth_args: RwLock::new(HashMap::new()),
copilot_acp_fallback: Mutex::new(HashSet::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
@@ -790,11 +809,14 @@ impl AgentManager {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let in_use: std::collections::HashSet<String> =
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
let terminal_auth = self.shared.terminal_auth_args.read();
let list = specs
.iter()
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
.map(|p| {
let mut info = provider::describe(p);
info.can_sign_in =
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
@@ -802,6 +824,7 @@ impl AgentManager {
info
})
.collect();
drop(terminal_auth);
let mut prev = self.shared.providers.write();
let mut probes = self.shared.probes.lock();
probes.retain(|id, _| {
@@ -815,6 +838,21 @@ impl AgentManager {
list
}
/// Resolves the interactive sign-in command for agent `id`.
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let spec = specs
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
})?;
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
Ok(launch)
}
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
@@ -3509,6 +3547,14 @@ impl Task {
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
})?;
if let Some(args) = init.auth_methods.iter().find_map(|method| {
if method.get("type").and_then(Value::as_str) != Some("terminal") {
return None;
}
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
}) {
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
}
let sign_in_message = spec.sign_in_message(&init.auth_methods);
let can_load = init.load_session();
let (capabilities, embedded) = capabilities_of(&init);
+11
Переглянути файл
@@ -623,6 +623,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
@@ -647,6 +650,14 @@ pub enum AgentCommandReadOnlyReason {
CustomAgent,
}
/// Output and completion of an interactive sign-in PTY started by the IDE.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum AgentLoginEvent {
Output { data: String },
Exited { code: Option<i32> },
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
+115 -1
Переглянути файл
@@ -73,7 +73,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
"GitHub Copilot",
Driver::Copilot,
&["copilot", "--headless", "--no-auto-update", "--stdio"],
"Run `copilot` in a terminal and sign in.",
"Run `copilot login` in a terminal.",
),
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
@@ -176,6 +176,80 @@ impl ProviderSpec {
.into_owned();
self
}
/// Resolves the executable, arguments, and environment to run this agent's interactive
/// sign-in flow directly in an IDE PTY without shell quoting.
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
let search = ide_core::tool_path::search_path();
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
let candidate =
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
if candidate.is_absolute() && is_executable(&candidate) {
return Some(candidate);
}
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
};
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
"claude-acp" => Some(("claude", &[][..])),
"codex-acp" => Some(("codex", &["login"][..])),
"vibe" => Some(("vibe", &[][..])),
_ => None,
} {
let program = resolve_exe(separate_cmd, &self.env)?;
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
});
}
if let Some(builtin) = builtin_spec(&self.id) {
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
.or_else(|| builtin_login_args(&builtin))?;
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
if is_copilot_provider(&self.id) {
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
}
return Some(LoginLaunch { program, args, env });
}
let args = terminal_auth_args?.to_vec();
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
}
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
self.login_launch(cwd, terminal_auth_args).is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoginLaunch {
pub program: PathBuf,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
}
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
let prefix = format!("Run `{}", builtin.command);
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
match rest {
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
let (args, _) = after_space.split_once('`')?;
Some(args.split_whitespace().map(str::to_owned).collect())
}
Some(_) => Some(Vec::new()),
None => None,
}
}
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
@@ -389,6 +463,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
config: vec![],
@@ -901,6 +976,22 @@ mod tests {
assert_eq!(reset.env, custom.env);
}
#[test]
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
for spec in builtins() {
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
continue;
}
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
}
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert!(args("qwen").is_empty());
}
#[test]
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
for spec in builtins() {
@@ -1458,4 +1549,27 @@ mod tests {
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
);
}
#[test]
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
let dir = tempfile::tempdir().unwrap();
let app_support = dir.path().join("Application Support/copilot");
std::fs::create_dir_all(&app_support).unwrap();
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let mut spec = builtin_spec("copilot").unwrap();
spec.command = bin.to_string_lossy().into_owned();
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
let launch = spec.login_launch(dir.path(), None).unwrap();
assert_eq!(launch.program, bin);
assert_eq!(launch.args, ["login"]);
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
}
}
+1 -1
Переглянути файл
@@ -1212,7 +1212,7 @@ esac
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(spec.name, "GitHub Copilot");
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![provider::describe(&spec)];
+10
Переглянути файл
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
+32
Переглянути файл
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
}
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
/// only when installed, then the user's `PATH`), and standard OS install locations.
pub fn find_gh_executable() -> Option<PathBuf> {
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
}
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
return Some(explicit);
}
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
}
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
return Some(explicit.to_path_buf());
}
if let Some(found) = find_command("gh", search, Path::new("")) {
return Some(found);
}
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
}
fn is_executable(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else { return false };
#[cfg(unix)]
-1
Переглянути файл
@@ -12,4 +12,3 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+37 -18
Переглянути файл
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;
/// API calls normally answer within a few seconds.
const QUICK: Duration = Duration::from_secs(60);
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
/// install or remove a managed copy in its tools directory at runtime).
pub fn gh_executable() -> Option<PathBuf> {
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
GH.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("gh") {
return Some(found);
}
let candidates: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
})
.clone()
ide_core::tool_path::find_gh_executable()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -386,3 +371,37 @@ pub fn prepare_diff(
let files = repo.diff_files(&base, head_oid)?;
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
}
#[cfg(test)]
mod tests {
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let search = std::env::join_paths([&dir]).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
std::fs::remove_file(&gh).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
+71 -3
Переглянути файл
@@ -6,9 +6,9 @@ use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
};
@@ -108,6 +108,73 @@ pub fn agent_set_env(
host.project(window)?.agents.set_builtin_env(&id, env)
}
pub(crate) fn spawn_login_pty(
host: &Host,
window: &str,
cwd: std::path::PathBuf,
launch: LoginLaunch,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
crate::ops::term::apply_output_rate(host, window);
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
let options = ide_terminal::TerminalOptions {
cwd: cwd.into(),
shell: Some(launch.program.to_string_lossy().into_owned()),
args: launch.args,
env: launch.env,
cols: if cols == 0 { 80 } else { cols },
rows: if rows == 0 { 20 } else { rows },
shell_integration: false,
};
let exit_channel = on_event.clone();
host.terminals.spawn_program(
options,
format!("agent-login:{window}"),
host.window_sink(window),
Box::new(move |data| {
let _ = on_event.send(AgentLoginEvent::Output { data });
}),
Some(std::sync::Arc::new(move |code| {
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
})),
)
}
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_login_spawn(
host: &Host,
window: &str,
id: String,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let (cwd, launch) = match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
let launch = host.blocking(move || agents.login_launch(&id)).await?;
(root, launch)
}
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
let cwd_for_lookup = cwd.clone();
let launch = host
.blocking(move || {
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
})
.await?;
(cwd, launch)
}
};
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
/// Saves a new custom ACP agent through its agent file.
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
host.require_trust(window)?;
@@ -1472,6 +1539,7 @@ ide_command::domain!(
agent_grouped_changes,
agent_hermes_profiles,
agent_import_session,
agent_login_spawn,
agent_mcp_discover_sources,
agent_mcp_import,
agent_mcp_import_selected,
+7 -3
Переглянути файл
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
&root,
&settings,
));
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
let mut found: std::collections::BTreeMap<_, _> =
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
found.insert("gh".to_owned(), gh);
}
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_downloads(settings.tool_downloads.clone())
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found.into_iter().collect())
.with_found_paths(found)
.with_work_dir(work_dir))
}
+1
Переглянути файл
@@ -697,6 +697,7 @@ async fn typescript() {
}
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
#[cfg(unix)]
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
+1 -1
Переглянути файл
@@ -6,7 +6,6 @@ use ide_host::{Host, HostConfig};
use ide_plugin::TextQuery;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
struct Harness {
host: Arc<Host>,
@@ -510,6 +509,7 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
use ide_plugin::{Invocation, Limits};
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
+53
Переглянути файл
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
Some(settings)
}
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
/// A threshold the server configuration sets explicitly is kept.
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
json!({
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
})
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
@@ -84,6 +98,7 @@ pub fn configure_formatter(
});
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
@@ -300,6 +315,44 @@ mod tests {
}
}
#[test]
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let imports = |cfg: &LanguageServerConfig| {
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
};
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
class_count_to_use_import_with_star: Some(7),
names_count_to_use_static_import_with_star: Some(4),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
let mut cfg = config("jdtls");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
// A threshold set in the server configuration wins.
let mut cfg = config("jdtls");
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
let mut cfg = config("rust-analyzer");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
}
#[test]
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
let dir = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -152,6 +152,8 @@ impl SshManager {
let config = self.config(id)?;
let secret = self.secret(&config);
let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?);
// The shared session carries the config's port forwards, restarted on every reconnect.
session.start_forwards().await;
self.sessions.lock().insert(id.to_owned(), session.clone());
Ok(session)
}
+115 -3
Переглянути файл
@@ -7,7 +7,9 @@
//! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a
//! changed key is refused unless host key checking is off.
use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops};
use crate::target::{
ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops,
};
use ide_core::remote_settings::SshAuth;
use ide_core::{IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
@@ -113,6 +115,18 @@ pub struct Session {
/// Sessions of the `ProxyJump` hosts, kept alive under `handle`.
_jumps: Vec<Handle<Client>>,
label: String,
/// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`].
forwards: Vec<PortForward>,
/// `LocalForward` listeners, stopped with the session.
listeners: Mutex<Vec<tokio::task::AbortHandle>>,
}
impl Drop for Session {
fn drop(&mut self) {
for listener in self.listeners.lock().drain(..) {
listener.abort();
}
}
}
impl Session {
@@ -158,8 +172,50 @@ impl Session {
sessions.push(handle);
}
let handle = sessions.pop().expect("at least one hop");
let label = hops.last().expect("at least one hop").label();
Ok(Session { handle, _jumps: sessions, label })
let last = hops.last().expect("at least one hop");
Ok(Session {
handle,
_jumps: sessions,
label: last.label(),
forwards: last.forwards.clone(),
listeners: Mutex::default(),
})
}
/// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the
/// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each
/// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused
/// by the server) is skipped with a warning, as `ssh` goes on without it.
pub async fn start_forwards(self: &Arc<Self>) {
for f in &self.forwards {
let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port);
match f.direction {
ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await {
Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label),
Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label),
},
ForwardDirection::Local => {
let bind = match f.bind.as_str() {
"localhost" => "127.0.0.1",
"" => "0.0.0.0",
b => b,
};
match tokio::net::TcpListener::bind((bind, f.port)).await {
Ok(listener) => {
let task = tokio::spawn(local_forward(
listener,
Arc::downgrade(self),
f.host.clone(),
f.host_port,
));
self.listeners.lock().push(task.abort_handle());
tracing::info!("{}: LocalForward {what}", self.label);
}
Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label),
}
}
}
}
}
/// `user@host:port` of the target.
@@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError {
IdeError::new(ErrorKind::Io, message)
}
/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to
/// `host:port` from the SSH host, while the session lives.
async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) {
while let Ok((mut socket, _)) = listener.accept().await {
let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return };
let host = host.clone();
tokio::spawn(async move {
match session.direct_tcpip(&host, port).await {
Ok(mut stream) => {
drop(session);
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
}
Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"),
}
});
}
}
/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways.
async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) {
match tokio::net::TcpStream::connect((host.as_str(), port)).await {
Ok(mut socket) => {
reply.accept().await;
let mut stream = channel.into_stream();
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
}
Err(e) => {
tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}");
reply.reject(russh::ChannelOpenFailure::ConnectFailed).await;
}
}
}
// --- connection ----------------------------------------------------------------
#[derive(Debug)]
@@ -418,6 +507,8 @@ pub struct Client {
known_hosts: PathBuf,
host_key_policy: HostKeyPolicy,
issue: Arc<Mutex<Option<HostKeyIssue>>>,
/// The `RemoteForward`s whose connections this client accepts.
remote_forwards: Vec<PortForward>,
}
impl client::Handler for Client {
@@ -442,6 +533,26 @@ impl client::Handler for Client {
*self.issue.lock() = Some(issue);
Ok(false)
}
async fn server_channel_open_forwarded_tcpip(
&mut self,
channel: russh::Channel<Msg>,
_connected_address: &str,
connected_port: u32,
_originator_address: &str,
_originator_port: u32,
reply: client::ChannelOpenHandle,
_session: &mut client::Session,
) -> Result<(), Self::Error> {
// Only a port this client asked the server to forward is accepted.
match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) {
Some(f) => {
tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port));
}
None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await,
}
Ok(())
}
}
impl Client {
@@ -600,6 +711,7 @@ where
known_hosts: effective_known_hosts,
host_key_policy: hop.host_key_policy,
issue: issue.clone(),
remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(),
};
let result = match stream {
None => client::connect(config, (hop.host.as_str(), hop.port), handler).await,
+114 -2
Переглянути файл
@@ -54,6 +54,63 @@ pub(crate) struct Hop {
pub host_key_policy: HostKeyPolicy,
pub known_hosts: Option<PathBuf>,
pub agent: Agent,
/// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing).
pub forwards: Vec<PortForward>,
}
/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortForward {
pub direction: ForwardDirection,
/// Address the listening side binds: empty for every address, `localhost` by default.
pub bind: String,
pub port: u16,
/// Where each connection goes, as the other side sees it.
pub host: String,
pub host_port: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForwardDirection {
/// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host.
Local,
/// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine.
Remote,
}
/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6
/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s
/// dynamic (SOCKS) form.
pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> {
let spec = split_args(value).join(":");
let mut parts: Vec<String> = Vec::new();
let mut cur = String::new();
let mut bracket = false;
for ch in spec.chars() {
match ch {
'[' if cur.is_empty() => bracket = true,
']' if bracket => bracket = false,
':' if !bracket => parts.push(std::mem::take(&mut cur)),
'/' => return None,
_ => cur.push(ch),
}
}
parts.push(cur);
let (bind, port, host, host_port) = match parts.as_slice() {
[port, host, host_port] => (None, port, host, host_port),
[bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port),
_ => return None,
};
let bind = match bind {
None => "localhost".to_owned(),
Some("*") | Some("") => String::new(),
Some(b) => b.to_owned(),
};
let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?);
if host.is_empty() || host_port == 0 {
return None;
}
Some(PortForward { direction, bind, port, host: host.clone(), host_port })
}
/// Where the SSH agent of a hop listens (`IdentityAgent`).
@@ -158,6 +215,8 @@ struct RawConfig {
host_key_policy: Option<HostKeyPolicy>,
user_known_hosts_file: Option<String>,
identity_agent: Option<String>,
forwards: Vec<PortForward>,
clear_forwardings: bool,
}
fn strip_quotes(s: &str) -> &str {
@@ -516,6 +575,23 @@ fn parse_config_file(
out.user_known_hosts_file = Some(first);
}
}
"localforward" | "remoteforward" => {
let direction = if key.eq_ignore_ascii_case("localforward") {
ForwardDirection::Local
} else {
ForwardDirection::Remote
};
match parse_forward(direction, value) {
Some(f) if !out.forwards.contains(&f) => out.forwards.push(f),
Some(_) => {}
None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"),
}
}
"clearallforwardings" => {
if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") {
out.clear_forwardings = true;
}
}
_ => {}
}
}
@@ -559,7 +635,8 @@ fn config_hop(
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
let agent =
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards };
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards };
(hop, proxy_jump)
}
@@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
_ => (rest, None),
};
let (hop, _) = config_hop(config, host, port, user);
hop
Hop { forwards: Vec::new(), ..hop }
}
/// The SSH hosts to go through, the target last.
@@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
host_key_policy: HostKeyPolicy::Ask,
known_hosts: None,
agent: Agent::Default,
forwards: Vec::new(),
},
None,
)
@@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> {
mod tests {
use super::*;
#[test]
fn parses_port_forwards_like_openssh() {
let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port));
let remote = ForwardDirection::Remote;
assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222)));
assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80)));
assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80)));
assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80)));
assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432)));
// Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards.
assert_eq!(f(remote, "1080"), None);
assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None);
assert_eq!(f(remote, "8080 web:http"), None);
}
#[test]
fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() {
let dir = tempfile::tempdir().unwrap();
let config = dir.path().join("config");
std::fs::write(
&config,
"Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\
Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n",
)
.unwrap();
let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
let hops = resolve_hops(&target("box"), Some(&config)).unwrap();
assert_eq!(hops.len(), 2);
assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing");
let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect();
assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]);
assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty());
}
#[test]
fn resolves_aliases_and_proxy_jumps_from_ssh_config() {
let tmp = tempfile::tempdir().unwrap();
+73
Переглянути файл
@@ -98,6 +98,32 @@ impl server::Handler for Sshd {
});
Ok(())
}
/// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client.
async fn tcpip_forward(
&mut self,
address: &str,
port: &mut u32,
session: &mut ServerSession,
) -> Result<bool, Self::Error> {
let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) };
let (handle, address, port) = (session.handle(), address.to_owned(), *port);
tokio::spawn(async move {
while let Ok((mut socket, peer)) = listener.accept().await {
let Ok(channel) = handle
.channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port()))
.await
else {
continue;
};
tokio::spawn(async move {
let mut stream = channel.into_stream();
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await;
});
}
});
Ok(true)
}
}
/// Echo server standing in for a remote service.
@@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() {
let msg = denied(env.connect(&target, None).await);
assert!(msg.contains("has changed"), "{msg}");
}
/// A free local port (bound and released).
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
async fn echoes(port: u16) {
let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens");
s.write_all(b"ping").await.unwrap();
let mut buf = [0u8; 4];
s.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"ping");
}
/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031).
#[tokio::test]
async fn config_port_forwards_follow_the_session() {
let mut env = env().await;
let (remote, local) = (free_port(), free_port());
let config = env._tmp.path().join("ssh_config");
std::fs::write(
&config,
format!(
"Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\
\tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\
\tRemoteForward /tmp/remote.sock /tmp/local.sock\n",
echo = env.echo_port
),
)
.unwrap();
env.files.config = Some(config);
let target = SshTarget {
host: "box".into(),
port: Some(env.ssh_port),
user: "coder".into(),
auth: SshAuth::OpenSsh,
..Default::default()
};
let session = Arc::new(env.connect(&target, None).await.expect("connects"));
session.start_forwards().await;
// The SSH host's port reaches the echo server here; the local port reaches it from the SSH host.
echoes(remote).await;
echoes(local).await;
drop(session);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward");
}
+1 -5
Переглянути файл
@@ -4,7 +4,7 @@
//! without network.
use crate::platform::{Arch, Os, Platform};
use crate::process::{Emit, Http};
use crate::process::Emit;
use crate::sources::Download;
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
use ide_core::error::ErrorKind;
@@ -240,10 +240,6 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
}
impl Tools {
fn http(&self) -> IdeResult<Http> {
Http::new(&self.system_path)
}
/// Java versions `vendor` publishes.
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
vendor_or_err(vendor)?;
+9 -4
Переглянути файл
@@ -557,6 +557,10 @@ impl Tools {
&self.root
}
pub(crate) fn http(&self) -> IdeResult<Http> {
Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path))
}
/// [`Tools::command`] in the project directory.
fn command_in_project(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = self.command(program);
@@ -902,7 +906,7 @@ impl Tools {
_ => (ToolStatus::Missing, None, None),
}
}
_ => match self.which(main) {
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
Some(path) => {
let version = self.query_version(spec, &path);
(ToolStatus::OnPath, Some(path), version)
@@ -1250,7 +1254,8 @@ impl Tools {
dotnet::SDK_DOWNLOAD_URL
)));
};
let pick = Http::new(&self.system_path)
let pick = self
.http()
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
match pick {
Ok(dotnet::ToolPick::Latest) => Ok(None),
@@ -1542,7 +1547,7 @@ impl Tools {
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let http = Http::new(&self.system_path)?;
let http = self.http()?;
let message = match source {
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
_ => "Resolving the latest release…".into(),
@@ -1683,7 +1688,7 @@ impl Tools {
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
match method {
Method::Release { source, assets, .. } => {
let http = Http::new(&self.system_path)?;
let http = self.http()?;
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
}
Method::Npm { packages } => {
+11
Переглянути файл
@@ -441,6 +441,17 @@ impl Http {
self
}
/// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools).
pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self {
self.gh = which::which_in("gh", Some(search_path), ".").ok();
self
}
#[cfg(test)]
pub(crate) fn gh_path(&self) -> Option<&Path> {
self.gh.as_deref()
}
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
pub fn without_github_auth(mut self) -> Self {
self.gh = None;
+74
Переглянути файл
@@ -181,6 +181,28 @@ pub static TOOLS: &[ToolSpec] = &[
needs: NODE,
homepage: "https://github.com/devcontainers/cli",
},
ToolSpec {
name: "gh",
display: "GitHub CLI",
kind: Cli,
commands: &["gh"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "cli/cli" },
assets: &[
rule(Mac, Arm64, "gh_*_macOS_arm64.zip"),
rule(Mac, X64, "gh_*_macOS_amd64.zip"),
rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"),
rule(Linux, X64, "gh_*_linux_amd64.tar.gz"),
rule(Windows, Arm64, "gh_*_windows_arm64.zip"),
rule(Windows, X64, "gh_*_windows_amd64.zip"),
],
locate: &["gh"],
},
fallback: None,
version: ver("gh"),
needs: &[],
homepage: "https://cli.github.com",
},
ToolSpec {
name: "oxfmt",
display: "oxfmt",
@@ -1483,4 +1505,56 @@ mod tests {
let win_arm = Platform { os: Windows, arch: Arm64 };
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
}
#[test]
fn gh_release_picks_portable_archive_for_every_supported_platform() {
use crate::platform::{Platform, select_asset};
let names = [
"gh_2.106.0_checksums.txt",
"gh_2.106.0_linux_386.deb",
"gh_2.106.0_linux_386.tar.gz",
"gh_2.106.0_linux_amd64.deb",
"gh_2.106.0_linux_amd64.rpm",
"gh_2.106.0_linux_amd64.tar.gz",
"gh_2.106.0_linux_arm64.deb",
"gh_2.106.0_linux_arm64.tar.gz",
"gh_2.106.0_linux_armv6.tar.gz",
"gh_2.106.0_macOS_amd64.zip",
"gh_2.106.0_macOS_arm64.zip",
"gh_2.106.0_macOS_universal.pkg",
"gh_2.106.0_windows_386.zip",
"gh_2.106.0_windows_amd64.msi",
"gh_2.106.0_windows_amd64.zip",
"gh_2.106.0_windows_arm64.msi",
"gh_2.106.0_windows_arm64.zip",
];
let spec = find("gh").unwrap();
assert_eq!(spec.kind, Cli);
let rules = spec.asset_rules();
for (os, arch, expected) in [
(Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"),
(Mac, X64, "gh_2.106.0_macOS_amd64.zip"),
(Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"),
(Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"),
(Windows, Arm64, "gh_2.106.0_windows_arm64.zip"),
(Windows, X64, "gh_2.106.0_windows_amd64.zip"),
] {
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
}
let Method::Release { locate, .. } = &spec.method else { unreachable!() };
let tmp = tempfile::tempdir().unwrap();
let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh");
std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap();
std::fs::write(&unix_bin, "").unwrap();
let unix_names: Vec<String> = locate.iter().map(|n| (*n).to_owned()).collect();
assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin));
let win_dir = tempfile::tempdir().unwrap();
let win_bin = win_dir.path().join("bin/gh.exe");
std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap();
std::fs::write(&win_bin, "").unwrap();
let win_names: Vec<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
}
}
+27
Переглянути файл
@@ -147,6 +147,11 @@ fn pick_release(
let checksum_url = assets
.iter()
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
.or_else(|| {
assets
.iter()
.find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt"))
})
.map(|c| c.url.clone());
return Ok(Download {
version,
@@ -622,6 +627,28 @@ mod tests {
let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64));
assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64)));
assert_eq!(parse_checksum(&sums, "missing.zip"), None);
let gh = serde_json::json!({
"tag_name": "v2.106.0",
"assets": [
{
"name": "gh_2.106.0_macOS_arm64.zip",
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip"
},
{
"name": "gh_2.106.0_checksums.txt",
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt"
}
]
})
.to_string();
let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap();
assert_eq!(dl.version, "2.106.0");
assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip");
assert_eq!(
dl.checksum_url.as_deref(),
Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt")
);
}
#[test]
+24
Переглянути файл
@@ -1428,3 +1428,27 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() {
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 0");
let app_data = env.root.parent().unwrap();
let gh_bin = env.root.join("gh/bin");
assert!(tools_bin_dirs(app_data).contains(&gh_bin));
let missing = env.tools().info("gh", &[]).unwrap();
assert_eq!(missing.kind, ToolKind::Cli);
assert_eq!(missing.status, ToolStatus::Missing);
assert!(missing.can_install);
env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'");
let installed = env.tools().info("gh", &[]).unwrap();
assert_eq!(installed.status, ToolStatus::Installed);
assert_eq!(installed.version.as_deref(), Some("2.106.0"));
assert!(installed.can_uninstall);
let http = env.tools().http().unwrap();
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
}
+33 -1
Переглянути файл
@@ -191,6 +191,35 @@ impl DocState {
self.disk_conflict = false;
self.clean_text = (!self.large).then(|| self.doc.clone());
}
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
let text = doc.text_for_save();
Ok(if self.native_to_ascii {
ide_vfs::encode_properties_ascii(&text).into_bytes()
} else {
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
})
}
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
/// only when the mtime moved but the length did not; without a clean text to compare (large
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
let mtime = ide_vfs::mtime_ms(meta);
if mtime == self.disk_mtime && meta.len() == self.disk_len {
return false;
}
let same_bytes = meta.len() == self.disk_len
&& self.clean_text.as_ref().is_some_and(|clean| {
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
});
if same_bytes {
self.disk_mtime = mtime;
}
!same_bytes
}
}
fn keys_for(path: &Path) -> Vec<PathBuf> {
@@ -924,7 +953,7 @@ impl Documents {
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
&& st.changed_on_disk(&meta)
{
st.disk_mtime = ide_vfs::mtime_ms(&meta);
st.disk_len = meta.len();
@@ -1411,6 +1440,9 @@ impl Documents {
return Ok(());
}
if st.dirty {
if !st.changed_on_disk(&meta) {
return Ok(());
}
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
+1 -6
Переглянути файл
@@ -314,12 +314,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
/// The bytes saving `state` would write.
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
let text = state.doc.text_for_save();
Ok(if state.native_to_ascii {
ide_vfs::encode_properties_ascii(&text).into_bytes()
} else {
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
})
state.bytes_for_save(&state.doc)
}
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
+55
Переглянути файл
@@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
);
}
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
fn rewrite_later(path: &Path, bytes: &[u8]) {
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
fs::write(path, bytes).unwrap();
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
}
#[test]
fn rewriting_the_same_bytes_is_no_disk_conflict() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
rewrite_later(&path, b"alpha\nbeta\n");
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
}
#[test]
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
rewrite_later(&path, b"alpha\nbeta\n");
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
}
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
let f = fixture();
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
rewrite_later(&path, external);
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
assert_eq!(fs::read(&path).unwrap(), external);
}
#[test]
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
// Same length: only the byte comparison tells them apart.
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
+6 -5
Переглянути файл
@@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
let info = docs.open(&first).unwrap();
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
.unwrap();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(&first, "old\n").unwrap();
// An external write under the unsaved buffer, warned about before the refactoring.
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
std::fs::write(&first, "ext\n").unwrap();
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
docs.on_disk_changed(std::slice::from_ref(&first));
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
docs.undo_workspace_edit(undo_id(&events)).unwrap();
let snap = docs.snapshot(info.id).unwrap();
assert_eq!(snap.text, "own\n");
assert!(snap.dirty);
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
}
#[test]
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
| Claude Code | `claude` | `claude` |
| Codex | `codex app-server` | `codex login` |
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
| GitHub Copilot | `copilot --acp` | `copilot` |
| GitHub Copilot | `copilot --acp` | `copilot login` |
| Cursor | `cursor-agent acp` | `cursor-agent login` |
| OpenCode | `opencode acp` | `opencode auth login` |
| Qwen Code | `qwen --experimental-acp` | `qwen` |
+16 -10
Переглянути файл
@@ -114,6 +114,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
## Tabs
@@ -145,17 +147,21 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
## View options
| Action | macOS | Windows / Linux |
| ---------------------- | ----- | --------------- |
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
| **Scroll Up** | — | `Ctrl+Up` |
| **Scroll Down** | — | `Ctrl+Down` |
| **Scroll to Top** | — | — |
| **Scroll to Bottom** | — | — |
| Action | macOS | Windows / Linux |
| ------------------------------------- | ----- | --------------- |
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
| **Scroll Up** | — | `Ctrl+Up` |
| **Scroll Down** | — | `Ctrl+Down` |
| **Scroll Up and Move if Necessary** | — | — |
| **Scroll Down and Move if Necessary** | — | — |
| **Move Up and Scroll** | — | — |
| **Move Down and Scroll** | — | — |
| **Scroll to Top** | — | — |
| **Scroll to Bottom** | — | — |
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
+5 -3
Переглянути файл
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
<Steps>
<Step title="Install gh">
Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in
`/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe`
(Windows).
Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window,
**Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks ›
Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`
(including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux)
or `C:\Program Files\GitHub CLI\gh.exe` (Windows).
</Step>
<Step title="Sign in">
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
+1 -1
Переглянути файл
@@ -31,7 +31,7 @@ Scratch files are saved in a `scratches` folder in OpenIDEA's application data d
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files.
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files. To hide that node, turn off **Show Scratches and Consoles** in the Project view's **Options › Appearance** menu; the **Scratches and Consoles** view still lists them.
Because a scratch file is outside every project, some language servers give it only syntax checks; completion and navigation may be limited. A banner at the top of the editor says so when the server reports it.
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted.
| `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). |
| `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. |
| `dateFormat.use24Hour` | `true` | 24-hour time. |
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". |
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). |
### `[appearance]`
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
| Claude Code | `claude` | `claude` |
| Codex | `codex app-server` | `codex login` |
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
| GitHub Copilot | `copilot --acp` | `copilot` |
| GitHub Copilot | `copilot --acp` | `copilot login` |
| Cursor | `cursor-agent acp` | `cursor-agent login` |
| OpenCode | `opencode acp` | `opencode auth login` |
| Qwen Code | `qwen --experimental-acp` | `qwen` |
+14 -10
Переглянути файл
@@ -145,17 +145,21 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
## 显示选项
| 操作 | macOS | Windows / Linux |
| -------------- | ----- | --------------- |
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
| **滚动到中央** | `⌃L` | `Ctrl+M` |
| **向上滚动** | — | `Ctrl+Up` |
| **向下滚动** | — | `Ctrl+Down` |
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
| 操作 | macOS | Windows / Linux |
| ------------------------------ | ----- | --------------- |
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
| **滚动到中央** | `⌃L` | `Ctrl+M` |
| **向上滚动** | — | `Ctrl+Up` |
| **向下滚动** | — | `Ctrl+Down` |
| **向上滚动并在必要时移动光标** | — | — |
| **向下滚动并在必要时移动光标** | — | — |
| **向上移动并滚动** | — | — |
| **向下移动并滚动** | — | — |
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
+4 -3
Переглянути файл
@@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
<Steps>
<Step title="安装 gh">
安装 GitHub CLI。OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`,以及
`/opt/homebrew/bin`、`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub
CLI\gh.exe`(Windows)中查找。
安装 GitHub CLI:可以直接点击 OpenIDEA 里的 **安装 GitHub CLI** 按钮(位于 **拉取请求** 工具窗口、**克隆仓库 ›
GitHub**、**设置 › 智能体 › GitHub Copilot** 或 **设置 › 语言与框架 › 语言服务器 › 其他工具**),也可以手动安装。
OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`(包含 IDE 管理的工具目录),以及 `/opt/homebrew/bin`、
`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub CLI\gh.exe`(Windows)中查找。
</Step>
<Step title="登录">
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
+1 -1
Переглянути файл
@@ -31,7 +31,7 @@ description: "在项目之外保留临时文件,并在 TODO 工具窗口中汇
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。要隐藏这个节点,可在项目视图的 **选项 › 外观** 菜单中关闭 **显示临时文件和控制台**;**临时文件和控制台** 视图仍会列出它们。
临时文件不属于任何项目,所以部分语言服务器只对它做语法检查,补全和导航可能受限;服务器报告这种情况时,编辑器顶部会显示横幅说明。
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 |
| `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 |
| `dateFormat.use24Hour` | `true` | 使用 24 小时制。 |
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 |
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 |
### `[appearance]`
+88
Переглянути файл
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import type { AgentConfigOption, AgentProvider } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openAgents(page: Page) {
const settings = "/src/features/settings/model/staging.ts";
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings);
return page.getByRole("dialog", { name: "Settings", exact: true });
}
test("signs in to an agent in an IDE terminal dialog and refreshes its model catalog", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(() => {
const model: AgentConfigOption = {
id: "model",
name: "Model",
description: null,
category: "model",
current: "claude-sonnet-4.5",
defaultValue: "claude-sonnet-4.5",
via: "option",
values: [
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
{ value: "gpt-5", name: "GPT-5", description: null },
],
};
let signedIn = false;
Object.assign(window.__ipc.handlers, {
settings_get_global: () => ({}),
agent_registry_list: () => ({ agents: [], warning: null }),
agent_providers: () => {
const provider: AgentProvider = {
id: "copilot",
name: "GitHub Copilot",
command: "copilot --headless --no-auto-update --stdio",
program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot",
args: ["--headless", "--no-auto-update", "--stdio"],
defaultProgram: "copilot",
defaultArgs: ["--headless", "--no-auto-update", "--stdio"],
loginHint:
"Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot' login` in a terminal.",
commandOverridden: false,
commandEditable: false,
commandReadOnlyReason: "registry",
installed: true,
canSignIn: true,
canCheckCliUpdate: false,
env: {},
config: signedIn ? [model] : [],
thoughtLevels: {},
commands: [],
source: { kind: "registry", version: "1.0.116", update: null },
};
return [provider];
},
agent_refresh_models: () => ({
provider: "copilot",
config: signedIn ? [model] : [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: signedIn ? Date.now() : null,
retryAtMs: null,
error: null,
}),
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
setTimeout(() => {
window.__ipc.send(onEvent, { type: "output", data: "Opening GitHub in browser...\r\n" });
signedIn = true;
window.__ipc.send(onEvent, { type: "exited", code: 0 });
}, 40);
return { id: 1, pid: 1001, title: "copilot" };
},
term_resize: () => null,
term_write: () => null,
term_kill: () => null,
});
});
const dialog = await openAgents(page);
const signIn = dialog.getByRole("region", { name: "Sign In" });
const newTasks = dialog.getByRole("region", { name: "New Tasks" });
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
await signIn.getByRole("button", { name: "Sign In…" }).click();
await expect(page.getByRole("dialog", { name: "Sign In to GitHub Copilot" })).toHaveCount(0);
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["copilot"]);
});
+34 -8
Переглянути файл
@@ -4,10 +4,11 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await page.setViewportSize({ width: 1080, height: 700 });
await stubDesktop(page);
await page.evaluate(async () => {
const path = "/dev/acme-api/status.svg";
const path = "/dev/acme-api/status.png";
// A black 128 × 96 PNG.
const image =
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
@@ -18,9 +19,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
const dimensions = toolbar.getByText(/128\s*×\s*96/);
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
await expect(dimensions).toBeVisible();
const wideHeight = (await toolbar.boundingBox())!.height;
@@ -31,8 +31,7 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
await expect(dimensions).toHaveCSS("font-size", "13px");
await expect(showText).toHaveCSS("white-space", "nowrap");
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
await expect(item).toBeInViewport({ ratio: 1 });
}
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
@@ -43,6 +42,33 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
await chessboard.click();
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
await showText.click();
});
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
await editorService().openFile("/dev/acme-api/status.svg");
});
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
// Not an SVG yet: the preview says so, and draws the source once it is typed.
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
await page.locator(".cm-content").click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.insertText(
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
);
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
await expect(page.locator(".cm-content")).toBeHidden();
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
await expect(toolbar).toHaveCount(0);
await expect(page.locator(".cm-content")).toBeVisible();
});
+1 -2
Переглянути файл
@@ -78,9 +78,8 @@ block2 = "0.6"
# Plugin secrets in the login keychain.
security-framework = "3.7"
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTextCheckingClient", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSLocale", "NSNotification", "NSOperation", "NSString"] }
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
[target.'cfg(target_os = "linux")'.dependencies]
+166 -23
Переглянути файл
@@ -1069,7 +1069,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
(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(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
.and_then(|b| {
macos_webview_configuration(app, 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);
@@ -1907,10 +1909,11 @@ 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(webview_profile(app, b)).build()).map_err(|e| {
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
let window =
builder.and_then(|b| macos_webview_configuration(app, webview_profile(app, b)).build()).map_err(|e| {
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -2443,18 +2446,86 @@ fn webview_profile<'a>(
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"))]
fn dev_font_preferences(
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
/// Configure macOS `WKWebViewConfiguration` before `WKWebView` creation:
/// - Disable macOS 15+ Apple Intelligence Writing Tools so its floating selection
/// affordance does not appear over Markdown previews, Quick Documentation, or editors.
/// - In debug builds, optionally reproduce WKWebView's user-font restriction when
/// `OPENIDEA_DEV_DISALLOW_USER_FONTS=1` is set (absent from release builds).
#[cfg(target_os = "macos")]
fn macos_webview_configuration<'a>(
app: &AppHandle,
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
match build_macos_webview_configuration(app) {
Some(config) => builder.with_webview_configuration(config),
None => builder,
}
}
#[cfg(target_os = "macos")]
fn build_macos_webview_configuration(
app: &AppHandle,
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
build_macos_webview_configuration_with(|f| app.run_on_main_thread(f))
}
#[cfg(target_os = "macos")]
fn build_macos_webview_configuration_with(
run_on_main_thread: impl FnOnce(Box<dyn FnOnce() + Send>) -> tauri::Result<()>,
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
const ON_MAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
struct SendConfig(objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>);
// SAFETY: Created and configured exclusively on the main thread, then moved untouched into
// `WebviewWindowBuilder::with_webview_configuration`, which transfers it back to the main
// thread when Wry constructs the WKWebView.
unsafe impl Send for SendConfig {}
let make = |mtm: objc2::MainThreadMarker| {
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
configure_macos_webview_configuration(&config).then_some(SendConfig(config))
};
if let Some(mtm) = objc2::MainThreadMarker::new() {
return make(mtm).map(|c| c.0);
}
// Secondary project windows (`spawn_window`) and auxiliary windows (`open_auxiliary_window`)
// build off the main thread; create the configuration on the AppKit main thread and fall back
// to the default builder if the event loop cannot service it.
let (tx, rx) = std::sync::mpsc::sync_channel(1);
if let Err(err) = run_on_main_thread(Box::new(move || {
let result = objc2::MainThreadMarker::new().and_then(make);
let _ = tx.send(result);
})) {
tracing::warn!("could not schedule macOS WKWebViewConfiguration on main thread: {err}");
return None;
}
match rx.recv_timeout(ON_MAIN_TIMEOUT) {
Ok(Some(config)) => Some(config.0),
Ok(None) => None,
Err(err) => {
tracing::warn!("timed out waiting for macOS WKWebViewConfiguration on main thread: {err}");
None
}
}
}
#[cfg(target_os = "macos")]
fn configure_macos_webview_configuration(config: &objc2_web_kit::WKWebViewConfiguration) -> bool {
use objc2::{msg_send, sel};
use objc2_app_kit::NSWritingToolsBehavior;
use objc2_foundation::NSObjectProtocol;
let mut configured = false;
if config.respondsToSelector(sel!(setWritingToolsBehavior:)) {
unsafe {
let _: () = msg_send![config, setWritingToolsBehavior: NSWritingToolsBehavior::None];
}
configured = true;
}
#[cfg(debug_assertions)]
if std::env::var("OPENIDEA_DEV_DISALLOW_USER_FONTS").as_deref() == Ok("1") {
use objc2::{MainThreadMarker, msg_send, sel};
use objc2_foundation::NSObjectProtocol;
let config = unsafe {
objc2_web_kit::WKWebViewConfiguration::new(MainThreadMarker::new().expect("window creation on main thread"))
};
let preferences = unsafe { config.preferences() };
if preferences.respondsToSelector(sel!(_setShouldAllowUserInstalledFonts:)) {
unsafe {
@@ -2462,17 +2533,19 @@ fn dev_font_preferences(
}
let allowed: bool = unsafe { msg_send![&preferences, _shouldAllowUserInstalledFonts] };
tracing::info!(allowed, "Development user-installed fonts override");
return builder.with_webview_configuration(config);
configured = true;
} else {
tracing::warn!("WKPreferences user-font development selector unavailable");
}
tracing::warn!("WKPreferences user-font development selector unavailable");
}
builder
configured
}
#[cfg(not(all(debug_assertions, target_os = "macos")))]
fn dev_font_preferences(
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
#[cfg(not(target_os = "macos"))]
fn macos_webview_configuration<'a>(
_app: &AppHandle,
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
builder
}
@@ -2561,6 +2634,76 @@ mod tests {
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_webview_configuration_disables_writing_tools() {
use objc2::{MainThreadMarker, msg_send, sel};
use objc2_app_kit::NSWritingToolsBehavior;
use objc2_foundation::NSObjectProtocol;
let Some(mtm) = MainThreadMarker::new() else {
return;
};
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
let configured = configure_macos_webview_configuration(&config);
if config.respondsToSelector(sel!(writingToolsBehavior)) {
assert!(configured);
let behavior: NSWritingToolsBehavior = unsafe { msg_send![&config, writingToolsBehavior] };
assert_eq!(behavior, NSWritingToolsBehavior::None);
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_webview_configuration_handles_non_main_thread() {
use objc2::{MainThreadMarker, sel};
use objc2_foundation::NSObjectProtocol;
// Off-thread scheduling failure falls back to None instead of panicking.
let result = std::thread::spawn(|| {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(|_| Err(tauri::Error::FailedToReceiveMessage)).is_none()
})
.join()
.expect("worker thread must not panic");
assert!(result);
// Off-thread callback without a main-thread marker falls back to None instead of panicking.
let result = std::thread::spawn(|| {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(|f| {
f();
Ok(())
})
.is_none()
})
.join()
.expect("worker thread must not panic");
assert!(result);
// When a main thread is available (e.g. nextest or --test-threads=1), dispatching from a
// worker thread constructs and configures WKWebViewConfiguration on the main thread.
if let Some(mtm) = MainThreadMarker::new() {
let probe = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
let expects_config = probe.respondsToSelector(sel!(setWritingToolsBehavior:));
let (work_tx, work_rx) = std::sync::mpsc::sync_channel::<Box<dyn FnOnce() + Send>>(1);
let worker = std::thread::spawn(move || {
assert!(MainThreadMarker::new().is_none());
build_macos_webview_configuration_with(move |f| {
work_tx.send(f).map_err(|_| tauri::Error::FailedToReceiveMessage)
})
.is_some()
});
let work = work_rx.recv().expect("worker should schedule onto main thread");
work();
let got_config = worker.join().expect("worker thread must not panic");
if expects_config {
assert!(got_config);
}
}
}
#[test]
fn frame_colours_from_the_ui_parse_as_hex() {
for (hex, expected) in [
+1
Переглянути файл
@@ -22,6 +22,7 @@ agent_fork_session trusted project_host bin
agent_grouped_changes trusted project_host bindings async
agent_hermes_profiles trusted project_host bindings async
agent_import_session trusted project_host bindings async
agent_login_spawn outside_restricted project_host bindings async
agent_mcp_discover_sources always project_host bindings async
agent_mcp_import always project_host bindings sync
agent_mcp_import_selected always project_host bindings async
+33
Переглянути файл
@@ -75,6 +75,8 @@ export const commands = {
agentHermesProfiles: () => typedError<HermesProfile[], IdeError>(__TAURI_INVOKE("agent_hermes_profiles")),
/** Imports an external session as a task: its first turn loads and replays it. */
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
/** Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code. */
agentLoginSpawn: (id: string, cols: number, rows: number, onEvent: Channel<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("agent_login_spawn", { id, cols, rows, onEvent })),
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
@@ -2899,6 +2901,9 @@ export type AgentLimit = {
resetsMs: number | null,
};
/** Output and completion of an interactive sign-in PTY started by the IDE. */
export type AgentLoginEvent = { type: "output"; data: string } | { type: "exited"; code: number | null };
/** An MCP server passed to coding agents in `session/new`, `session/load` and `session/fork`. */
export type AgentMcpServer = AgentMcpServer_Serialize | AgentMcpServer_Deserialize;
@@ -3013,6 +3018,8 @@ export type AgentProvider_Deserialize = {
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
/** Whether the command was found (on `PATH`). */
installed: boolean,
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
canSignIn?: boolean,
/** The built-in command can be owned by a global npm package. */
canCheckCliUpdate?: boolean,
/** Environment variables it starts with (from its agent file). */
@@ -3044,6 +3051,8 @@ export type AgentProvider_Serialize = {
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
/** Whether the command was found (on `PATH`). */
installed: boolean,
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
canSignIn: boolean,
/** The built-in command can be owned by a global npm package. */
canCheckCliUpdate: boolean,
/** Environment variables it starts with (from its agent file). */
@@ -9162,6 +9171,18 @@ export type LanguageCodeStyle_Deserialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
@@ -9192,6 +9213,18 @@ export type LanguageCodeStyle_Serialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
+32 -1
Переглянути файл
@@ -81,10 +81,12 @@ import {
cursorParagraphBackward,
cursorParagraphForward,
scrollDown,
scrollDownAndMove,
scrollToBottom,
scrollToCenter,
scrollToTop,
scrollUp,
scrollUpAndMove,
selectCodeBlockEnd,
selectCodeBlockStart,
selectPageBottom,
@@ -95,7 +97,14 @@ import {
} from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
import {
cloneCaretAbove,
cloneCaretBelow,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
} from "./cm/verticalMotion";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
import { copyReferenceToClipboard, declaredName, qualifiedReference, referenceOffset } from "./copyReference";
@@ -1059,6 +1068,28 @@ export function registerEditorActions(): () => void {
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
caret("editor.scrollUpAndMove", "Scroll Up and Move if Necessary", (v) => scrollUpAndMove(v), {
category: "Editor Actions",
}),
caret("editor.scrollDownAndMove", "Scroll Down and Move if Necessary", (v) => scrollDownAndMove(v), {
category: "Editor Actions",
}),
caret("editor.moveUpAndScroll", "Move Up and Scroll", (v) => moveUpAndScroll(v), { category: "Editor Actions" }),
caret("editor.moveDownAndScroll", "Move Down and Scroll", (v) => moveDownAndScroll(v), {
category: "Editor Actions",
}),
caret(
"editor.moveUpAndScrollWithSelection",
"Move Up and Scroll with Selection",
(v) => moveUpAndScrollWithSelection(v),
{ category: "Editor Actions" },
),
caret(
"editor.moveDownAndScrollWithSelection",
"Move Down and Scroll with Selection",
(v) => moveDownAndScrollWithSelection(v),
{ category: "Editor Actions" },
),
caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }),
caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }),
caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }),
+101 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { afterEach, beforeAll, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { indentService, type LanguageSupport } from "@codemirror/language";
import { codeFolding, foldEffect, indentService, type LanguageSupport } from "@codemirror/language";
import { languages } from "@codemirror/language-data";
import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
import {
@@ -14,9 +14,11 @@ import {
nextParagraphBoundary,
previousParagraphBoundary,
scrollDown,
scrollDownAndMove,
scrollToBottom,
scrollToTop,
scrollUp,
scrollUpAndMove,
selectPageBottom,
selectPageTop,
selectParagraphForward,
@@ -251,6 +253,104 @@ describe("Move Caret to Page Top / Bottom", () => {
});
});
describe("Scroll Up / Down and Move if Necessary", () => {
/** jsdom has no layout: a scroller `height` line heights tall, scrolled to `top` line heights. */
function scroller(view: EditorView, top: number, height: number) {
const line = view.lineBlockAt(0).height;
let px = top * line;
Object.defineProperty(view.scrollDOM, "scrollTop", {
configurable: true,
get: () => px,
set: (v: number) => (px = Math.max(0, v)),
});
Object.defineProperty(view, "documentTop", { configurable: true, get: () => -px });
Object.defineProperty(view.scrollDOM, "clientHeight", { configurable: true, get: () => height * line });
return () => px / line;
}
const lines = (marked: Record<number, string>) =>
Array.from({ length: 10 }, (_, i) => marked[i] ?? `line ${i} text`).join("\n");
const lineOf = (view: EditorView) => view.state.selection.ranges.map((r) => view.state.doc.lineAt(r.head).number - 1);
const columnOf = (view: EditorView) =>
view.state.selection.ranges.map((r) => r.head - view.state.doc.lineAt(r.head).from);
it("scrolls one line and keeps a caret that stays in view where it is", () => {
const view = make(lines({ 4: "line 4 te|xt" }));
const top = scroller(view, 2, 4);
const before = view.state.selection;
expect(scrollDownAndMove(view)).toBe(true);
expect(top()).toBe(3);
expect(view.state.selection.eq(before)).toBe(true);
expect(scrollUpAndMove(view)).toBe(true);
expect(top()).toBe(2);
expect(view.state.selection.eq(before)).toBe(true);
});
it("brings a caret that scrolls off the top down to the first line, keeping its column", () => {
const view = make(lines({ 2: "line 2 te|xt" }));
scroller(view, 2, 4);
scrollDownAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[3], [9]]);
});
it("brings a caret that scrolls off the bottom up to the last line, keeping its column", () => {
const view = make(lines({ 5: "li|ne 5 text" }));
scroller(view, 2, 4);
scrollUpAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[4], [2]]);
});
it("moves a caret already out of view to the nearest edge", () => {
const view = make(lines({ 9: "line 9 |text" }));
scroller(view, 0, 4);
scrollDownAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[4], [7]]);
});
it("drops the selection of a caret it moves and keeps the others", () => {
const view = make(lines({ 0: "|line 0 text" }));
const at = (line: number, col: number) => view.state.doc.line(line + 1).from + col;
view.dispatch({
selection: EditorSelection.create(
[EditorSelection.range(at(2, 0), at(2, 4)), EditorSelection.range(at(4, 0), at(4, 4))],
1,
),
});
scroller(view, 2, 4);
scrollDownAndMove(view);
expect(view.state.selection.ranges.map((r) => [r.anchor, r.head])).toEqual([
[at(3, 4), at(3, 4)],
[at(4, 0), at(4, 4)],
]);
expect(view.state.selection.mainIndex).toBe(1);
});
it("keeps a caret at the end of a folded block the view shows", () => {
const view = make(lines({ 7: "line 7 text|" }));
const { doc } = view.state;
view.dispatch({
effects: [
StateEffect.appendConfig.of(codeFolding()),
foldEffect.of({ from: doc.line(6).to, to: doc.line(8).to }),
],
});
expect(view.lineBlockAt(doc.line(8).to).from).toBe(doc.line(6).from);
const before = view.state.selection;
scroller(view, 1, 4);
scrollDownAndMove(view);
expect(view.state.selection.eq(before)).toBe(true);
});
it("only scrolls at the top of the file when the caret stays in view", () => {
const view = make(lines({ 1: "|line 1 text" }));
const top = scroller(view, 0, 4);
const before = view.state.selection;
scrollUpAndMove(view);
expect(top()).toBe(0);
expect(view.state.selection.eq(before)).toBe(true);
expect(view.state.doc.toString()).toBe(lines({}));
});
});
describe("code block navigation", () => {
let js: LanguageSupport;
beforeAll(async () => {
+40 -5
Переглянути файл
@@ -1,4 +1,4 @@
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Scroll Up / Down and Move if Necessary, Page Top / Bottom, code block, brace and paragraph navigation. */
import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state";
import { EditorView, type Command } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
@@ -66,15 +66,21 @@ function pageEdgeLine(view: EditorView, edge: "top" | "bottom"): number {
return block.top >= bottom || (block.bottom > bottom && previous.top >= top) ? previous.from : block.from;
}
/** `head` moved to the line starting at `lineStart`, keeping its visual column. */
function sameColumnOn(state: EditorState, head: number, lineStart: number): number {
const line = state.doc.lineAt(head);
const target = state.doc.lineAt(lineStart);
const column = countColumn(line.text, state.tabSize, head - line.from);
return target.from + findColumn(target.text, column, state.tabSize);
}
/** Move Caret to Page Top / Bottom (with Selection): every caret to that line, keeping its column. */
function moveToPageEdge(edge: "top" | "bottom", extend = false): Command {
return (view) => {
const { state } = view;
const target = state.doc.lineAt(pageEdgeLine(view, edge));
const target = pageEdgeLine(view, edge);
const ranges = state.selection.ranges.map((r) => {
const line = state.doc.lineAt(r.head);
const column = countColumn(line.text, state.tabSize, r.head - line.from);
const head = target.from + findColumn(target.text, column, state.tabSize);
const head = sameColumnOn(state, r.head, target);
return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head);
});
view.dispatch({
@@ -90,6 +96,35 @@ export const cursorPageBottom = moveToPageEdge("bottom");
export const selectPageTop = moveToPageEdge("top", true);
export const selectPageBottom = moveToPageEdge("bottom", true);
/**
* Scroll Up / Down and Move if Necessary: move the viewport by one line, then bring
* a caret outside the lines the view shows whole to the first or last of them,
* keeping its column. Carets in view keep their place and selection.
*/
const scrollByLineAndMove =
(lines: number): Command =>
(view) => {
scrollByLine(lines)(view);
const { state } = view;
const first = pageEdgeLine(view, "top");
const last = view.lineBlockAt(pageEdgeLine(view, "bottom"));
let moved = false;
const ranges = state.selection.ranges.map((r) => {
if (r.head >= first && r.head <= last.to) return r;
moved = true;
return EditorSelection.cursor(sameColumnOn(state, r.head, r.head < first ? first : last.from));
});
if (moved) {
view.dispatch({
selection: EditorSelection.create(ranges, state.selection.mainIndex),
userEvent: "select.navigate",
});
}
return true;
};
export const scrollUpAndMove = scrollByLineAndMove(-1);
export const scrollDownAndMove = scrollByLineAndMove(1);
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
+125 -2
Переглянути файл
@@ -1,12 +1,16 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import {
cloneCaretAbove,
cloneCaretBelow,
cursorLineDown,
cursorLineUp,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
selectLineDown,
visibleGoalColumns,
} from "./verticalMotion";
@@ -106,3 +110,122 @@ describe("Clone Caret Above / Below in visible columns", () => {
expect(cloneCaretAbove(v)).toBe(false);
});
});
describe("Move Up / Down and Scroll", () => {
/** jsdom has no layout: record what the command asks the scroller for, and whether it scrolled to the caret. */
function track(v: EditorView, start: number) {
let top = start;
Object.defineProperty(v.scrollDOM, "scrollTop", {
configurable: true,
get: () => top,
set: (x: number) => (top = x),
});
const scrolledToCaret: boolean[] = [];
v.dispatch({
effects: StateEffect.appendConfig.of(
EditorView.updateListener.of((u) => u.transactions.forEach((tr) => scrolledToCaret.push(tr.scrollIntoView))),
),
});
scrolledToCaret.length = 0;
return { top: () => top, scrolledToCaret };
}
const rowGap = (v: EditorView, from: number, to: number) =>
v.lineBlockAt(v.state.doc.line(to).from).top - v.lineBlockAt(v.state.doc.line(from).from).top;
it("moves the caret one line and scrolls the view by the same amount", () => {
const v = make("abcdef\nabcdef\nabcdef\nabcdef", 7 + 3);
const t = track(v, 100);
const gap = rowGap(v, 2, 3);
expect(gap).toBeGreaterThan(0);
expect(moveDownAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([14 + 3]);
expect(t.top()).toBe(100 + gap);
expect(moveUpAndScroll(v)).toBe(true);
expect(moveUpAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([3]);
expect(t.top()).toBe(100 - rowGap(v, 1, 2));
expect(v.state.selection.main.empty).toBe(true);
});
it("keeps the goal column across a short line", () => {
const v = make("abcdefgh\n张\nabcdefgh", 6);
track(v, 0);
moveDownAndScroll(v);
moveDownAndScroll(v);
expect(heads(v)).toEqual([11 + 6]);
});
it("with Selection extends from the anchor", () => {
const v = make("abcd\nabcd\nabcd", 5 + 2);
const t = track(v, 40);
moveDownAndScrollWithSelection(v);
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 12]);
moveUpAndScrollWithSelection(v);
moveUpAndScrollWithSelection(v);
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 2]);
expect(t.top()).toBe(40 - rowGap(v, 1, 2));
});
it("moves every caret and scrolls with the primary one", () => {
const v = make("ab\nab\nab\nab", 0);
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(7)], 1) });
const t = track(v, 0);
moveDownAndScroll(v);
expect(heads(v)).toEqual([4, 10]);
expect(v.state.selection.mainIndex).toBe(1);
expect(t.top()).toBe(rowGap(v, 3, 4));
});
it("leaves scrolling to itself: never scrolls a caret out of view back into it", () => {
const v = make("ab\nab\nab", 1);
const t = track(v, 500);
moveDownAndScroll(v);
expect(t.scrolledToCaret).toEqual([false]);
expect(t.top()).toBe(500 + rowGap(v, 1, 2));
});
it("drops a selection and moves one line from its caret", () => {
const v = make("abcd\nabcd\nabcd\nabcd", 0);
v.dispatch({ selection: { anchor: 15 + 2, head: 2 } });
const t = track(v, 0);
moveDownAndScroll(v);
expect(v.state.selection.main.empty).toBe(true);
expect(heads(v)).toEqual([5 + 2]);
expect(t.top()).toBe(rowGap(v, 1, 2));
});
it("measures to the text of a line below a block widget (code lens)", () => {
class Lens extends WidgetType {
toDOM() {
return document.createElement("div");
}
get estimatedHeight() {
return 40;
}
}
const v = make("ab\nab\nab", 1);
const lens = Decoration.widget({ widget: new Lens(), block: true, side: -1 }).range(3);
v.dispatch({ effects: StateEffect.appendConfig.of(EditorView.decorations.of(Decoration.set([lens]))) });
const t = track(v, 0);
const line = v.lineBlockAt(0).height;
expect(v.lineBlockAt(3).height).toBeGreaterThan(line);
moveDownAndScroll(v);
expect(heads(v)).toEqual([4]);
expect(t.top()).toBe(v.lineBlockAt(3).bottom - line);
moveUpAndScroll(v);
expect(t.top()).toBe(0);
});
it("does not scroll at the document edge", () => {
const v = make("ab\ncd", 1);
const t = track(v, 0);
expect(moveUpAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([0]);
expect(moveUpAndScroll(v)).toBe(false);
v.dispatch({ selection: { anchor: 4 } });
expect(moveDownAndScroll(v)).toBe(true);
expect(moveDownAndScroll(v)).toBe(false);
expect(heads(v)).toEqual([5]);
expect(t.top()).toBe(0);
});
});
+41 -4
Переглянути файл
@@ -6,7 +6,7 @@
* CodeMirror's pixel motion between their visual rows.
*/
import { EditorSelection, StateEffect, StateField, type EditorState, type SelectionRange } from "@codemirror/state";
import type { Command, EditorView } from "@codemirror/view";
import { BlockType, type BlockInfo, type Command, type EditorView } from "@codemirror/view";
import { offsetAtVisibleColumn, visibleColumn } from "./visibleColumn";
/** Goal visible column per caret head, kept while only these commands move the carets. */
@@ -52,11 +52,12 @@ export function verticalHead(view: EditorView, head: number, forward: boolean, g
return moved === head ? null : moved;
}
function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolean {
/** `fromHead`: drop a selection and move its caret on from the head, as IDEA's caret-relative moves do. */
function moveCarets(view: EditorView, forward: boolean, extend: boolean, fromHead = false): boolean {
const { state } = view;
const goals = new Map<number, number>();
const ranges = state.selection.ranges.map((r): SelectionRange => {
if (!extend && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
if (!extend && !fromHead && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
const goal = goalOf(state, r.head);
let head = verticalHead(view, r.head, forward, goal);
if (head === null) head = forward ? state.doc.lineAt(r.head).to : state.doc.lineAt(r.head).from;
@@ -65,7 +66,8 @@ function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolea
});
const selection = EditorSelection.create(ranges, state.selection.mainIndex);
if (selection.eq(state.selection)) return false;
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: true, userEvent: "select" });
// The caret-relative moves scroll the view themselves and may leave the caret out of view.
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: !fromHead, userEvent: "select" });
return true;
}
@@ -74,6 +76,41 @@ export const cursorLineDown: Command = (view) => moveCarets(view, true, false);
export const selectLineUp: Command = (view) => moveCarets(view, false, true);
export const selectLineDown: Command = (view) => moveCarets(view, true, true);
/** Top of the text of the line at `pos`, in document coordinates: below any block widgets (code lens, inline diff) joined to its line block. */
function lineTextTop(view: EditorView, pos: number): number {
const block = view.lineBlockAt(pos);
if (!Array.isArray(block.type)) return block.top;
const parts = block.type as readonly BlockInfo[];
return (parts.find((b) => b.type === BlockType.Text && b.from <= pos && pos <= b.to) ?? block).top;
}
/** Screen top of the caret's visual row when soft wrap splits lines into rows and the caret is drawn; otherwise null. */
function caretRowTop(view: EditorView): number | null {
if (!view.lineWrapping) return null;
const { head, assoc } = view.state.selection.main;
return view.coordsAtPos(head, assoc || 1)?.top ?? null;
}
/**
* Move Up / Down and Scroll (with Selection), as IDEA: the carets move one line and
* the view scrolls by as much, so the primary caret keeps its place on screen.
*/
function moveAndScroll(view: EditorView, forward: boolean, extend: boolean): boolean {
const before = { row: caretRowTop(view), line: lineTextTop(view, view.state.selection.main.head) };
if (!moveCarets(view, forward, extend, true)) return false;
const row = before.row === null ? null : caretRowTop(view);
view.scrollDOM.scrollTop +=
row !== null && before.row !== null
? row - before.row
: lineTextTop(view, view.state.selection.main.head) - before.line;
return true;
}
export const moveUpAndScroll: Command = (view) => moveAndScroll(view, false, false);
export const moveDownAndScroll: Command = (view) => moveAndScroll(view, true, false);
export const moveUpAndScrollWithSelection: Command = (view) => moveAndScroll(view, false, true);
export const moveDownAndScrollWithSelection: Command = (view) => moveAndScroll(view, true, true);
/** Clone Caret Above / Below: a caret on the next line at each caret's goal column. */
function cloneCaret(view: EditorView, forward: boolean): boolean {
const { state } = view;
+56
Переглянути файл
@@ -24,6 +24,22 @@ import { installKeyboardDispatcher } from "@/platform/keymap";
import { TEXT_WHEN } from "./actions";
import { EDITOR_WHEN } from "@/editor/lsp/actions";
import { setShownLine } from "@/editor/api";
import { registerProjectActions } from "@/features/project-tree/actions";
/** `isTauri` is a spy (File Color writes need it true); the settings commands stand in for the backend. */
const ipc = vi.hoisted(() => ({
isTauri: vi.fn(() => false),
settingsSet: vi.fn(async () => ({ status: "ok" as const, data: {} })),
settingsGet: vi.fn(async () => ({})),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: ipc.isTauri,
commands: { ...real.commands, settingsSet: ipc.settingsSet, settingsGet: ipc.settingsGet },
};
});
let ctrl: EditorController | null = null;
@@ -422,6 +438,46 @@ describe("EditorController", () => {
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
});
it("offers the project view's File Color submenu through actions", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never,
settings: {} as never,
});
ipc.isTauri.mockReturnValue(true);
const disposeActions = registerProjectActions();
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/elsewhere/c.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!;
const raw = ctrl!.tabMenu(pane().id, pane().tabs[0]!);
const entry = raw.find((i) => "label" in i && i.label === "File Color");
expect(entry).toBeDefined();
const items = resolveMenuItems((entry as { submenu: typeof raw }).submenu);
expect(items.filter((i) => i.kind === "item").map((i) => i.label)).toEqual([
"Blue",
"Green",
"Orange",
"Rose",
"Violet",
"Yellow",
"Gray",
"Edit File Colors…",
]);
items.find((i) => i.label === "Blue")!.run!();
await vi.waitFor(() => expect(ipc.settingsSet).toHaveBeenCalledTimes(2));
expect(ipc.settingsSet).toHaveBeenNthCalledWith(1, "project", "scopes", expect.stringContaining('"file:a.ts"'));
expect(ipc.settingsSet).toHaveBeenNthCalledWith(2, "project", "fileColors", expect.stringContaining("blue"));
// A file outside the project has no File Color, as in the project view.
await ctrl.openFile("/elsewhere/c.ts", { focus: false });
const outside = pane().tabs.find((t) => t.input.path === "/elsewhere/c.ts")!;
expect(ctrl.tabMenu(pane().id, outside).some((i) => "label" in i && i.label === "File Color")).toBe(false);
ipc.isTauri.mockReturnValue(false);
useProject.setState({ project: null, settings: null });
} finally {
disposeActions();
}
});
it("keeps editor tabs and unsaved documents through attach and detach", async () => {
const settings = {};
useProject.setState({
+25 -1
Переглянути файл
@@ -12,7 +12,7 @@ import { create } from "zustand";
import { setContext } from "@/platform/context";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import { isSameOrInside } from "@/platform/paths";
import { basename, dirname, useProject } from "@/platform/project";
import { basename, dirname, relativePath, useProject } from "@/platform/project";
import { editorPrefs } from "@/platform/editorSettings";
import {
_emitEditorEvent,
@@ -60,6 +60,7 @@ import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow, projectLocation } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { FILE_COLOR_NAMES, ownFileColor } from "@/platform/fileColors";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import {
activateTab,
@@ -2550,6 +2551,9 @@ export class EditorController implements SlotHost {
{ kind: "separator" },
...(path
? ([
...(inProject && path !== project!.root
? ([{ label: "File Color", submenu: fileColorMenuItems(path) }, { kind: "separator" }] as MenuItem[])
: []),
{
label: "Copy Path/Reference…",
submenu: [
@@ -2638,6 +2642,26 @@ export class EditorController implements SlotHost {
}
}
/**
* File Color submenu of a file tab: the project view's File Color rows as action items carrying
* the path (features/project-tree owns the model and the titles), so both menus agree.
*/
function fileColorMenuItems(path: string): MenuItem[] {
const { project, settings } = useProject.getState();
const current = project ? ownFileColor(relativePath(project.root, path), false, settings)?.toLowerCase() : null;
return [
...FILE_COLOR_NAMES.map((name): MenuItem => ({
kind: "action",
action: `file.${name}`,
arg: path,
checked: current === name,
})),
{ kind: "separator" },
...(current ? [{ kind: "action" as const, action: "file.clearColor", arg: path }] : []),
{ kind: "action", action: "file.editColors" },
];
}
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem {
return {
+3 -1
Переглянути файл
@@ -307,11 +307,13 @@ export function NavChildrenPopup({
segment,
anchor,
openAbove = true,
label,
onClose,
}: {
segment: NavSegment;
anchor: HTMLElement;
openAbove?: boolean;
label?: string;
onClose: () => void;
}) {
const [stack, setStack] = useState<NavSegment[]>([segment]);
@@ -366,7 +368,7 @@ export function NavChildrenPopup({
anchor={anchor}
placement={openAbove ? "top-start" : "bottom-start"}
onClose={onClose}
aria-label={top.label}
aria-label={label ?? top.label}
className={styles.childPopup}
>
{stack.length > 1 && (
+50 -7
Переглянути файл
@@ -14,6 +14,7 @@ import {
Menu,
Popup,
SelectListbox,
showContextMenu,
badgeKind,
fileIconName,
revealHorizontally,
@@ -33,6 +34,7 @@ import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs }
import { languageInfo } from "../cm/languages";
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
import { symbolChain } from "./outline";
import { siblingSegment } from "./navBar";
import { NavChildrenPopup } from "./NavBarPopup";
import type { NavSegment } from "./navBar";
import styles from "./EditorArea.module.css";
@@ -166,9 +168,15 @@ function updateBreadcrumbEdges(row: HTMLDivElement) {
function BreadcrumbStrip({
trail,
activateOnDown = false,
onActivateAltDown,
children,
...props
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
}: ComponentPropsWithoutRef<"nav"> & {
trail: string;
activateOnDown?: boolean;
/** Alt+Down on a focused crumb opens its chooser (the crumb's element is passed). */
onActivateAltDown?: (crumb: HTMLElement) => void;
}) {
const strip = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const row = strip.current;
@@ -189,10 +197,16 @@ function BreadcrumbStrip({
<nav
{...props}
onKeyDown={(e) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
const index = buttons.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
if (e.altKey && !e.ctrlKey && !e.metaKey && e.key === "ArrowDown" && onActivateAltDown) {
e.preventDefault();
e.stopPropagation();
onActivateAltDown?.(buttons[index]!);
return;
}
if (e.altKey || e.ctrlKey || e.metaKey) return;
let next: number;
if (e.key === "ArrowLeft") next = Math.max(0, index - 1);
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
@@ -354,6 +368,7 @@ export function CodeBreadcrumbs({
const editorSettings = useProject((s) => s.settings?.editor);
const language = useDocMeta((s) => s[path]?.language);
const outline = useOutline((s) => s[path]);
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
let chain = useCaretSymbols(path, outline);
if (!chain) {
// Not the active editor (another split): its own caret, as of this render.
@@ -373,28 +388,56 @@ export function CodeBreadcrumbs({
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const fontSize = editorSettings?.fontSize ?? undefined;
const navigate = (item: OutlineItem) =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
});
// IDEA's breadcrumb chooser lives off the click: right-click or Alt+Down on a
// crumb lists its siblings (Navigation Bar only).
const chooseSiblings = (i: number, anchor: HTMLElement) => {
if (!outline) return;
setPopup({ nav: siblingSegment(path, chain, i), anchor });
};
const crumbMenu = (
i: number,
crumb: HTMLElement,
e: { clientX: number; clientY: number; preventDefault: () => void },
) => {
e.preventDefault();
if (outline)
showContextMenu(e, [{ id: "chooseSymbol", label: "Choose Symbol…", run: () => chooseSiblings(i, crumb) }]);
};
return (
<BreadcrumbStrip
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
style={{ fontFamily, fontSize }}
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
aria-label={tx("Code breadcrumbs")}
onActivateAltDown={(crumb) => chooseSiblings(Number(crumb.dataset.crumbIndex), crumb)}
>
{chain.map((item, i) => (
<BarButton
key={`${item.name}:${item.detail ?? ""}:${item.selection_range.start.line}:${item.selection_range.start.col}`}
data-crumb-index={i}
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
aria-current={i === chain.length - 1 ? "location" : undefined}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
onClick={() => navigate(item)}
onContextMenu={(e) => crumbMenu(i, e.currentTarget, e)}
>
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
))}
{popup && (
<NavChildrenPopup
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
segment={popup.nav}
anchor={popup.anchor}
openAbove={position === "bottom"}
label={tx("Choose a symbol")}
onClose={() => setPopup(null)}
/>
)}
</BreadcrumbStrip>
);
}
+11
Переглянути файл
@@ -67,6 +67,17 @@ export function symbolChildren(path: string, items: readonly OutlineItem[]): Nav
return items.map((item) => ({ kind: "symbol", path, label: item.name, item }));
}
/**
* The segment whose children are the siblings of `chain[index]` (IDEA / PyCharm
* breadcrumb chooser): the file for a top-level symbol, else its enclosing symbol.
*/
export function siblingSegment(path: string, chain: readonly OutlineItem[], index: number): NavSegment {
const parent = index > 0 ? chain[index - 1]! : null;
return parent
? { kind: "symbol", path, label: parent.name, item: parent }
: { kind: "file", path, label: nameOf(path) };
}
export function iconOf(x: NavSegment | NavChild): string {
if (x.kind === "dir") return "root" in x && x.root ? "module" : "folder";
if (x.kind === "file") return fileIconName(x.label);
+81 -3
Переглянути файл
@@ -1,13 +1,15 @@
import { Profiler } from "react";
import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { OutlineItem, Settings } from "@/platform/ipc";
import type { EditorStatus } from "../controller";
const { openFile } = vi.hoisted(() => ({ openFile: vi.fn(async () => {}) }));
vi.mock("../controller", async () => {
const { create } = await import("zustand");
return {
editorController: () => ({ openFile: vi.fn(), slots: new Map() }),
editorController: () => ({ openFile, slots: new Map() }),
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
useGotoLine: create(() => ({ open: false })),
useTabs: create(() => ({ panes: {}, activePane: "" })),
@@ -21,6 +23,7 @@ const { useProject } = await import("@/platform/project");
const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/contributions");
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
const { useContextMenuStore } = await import("@/ui");
const PATH = "/p/Orders.ts";
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
@@ -307,3 +310,78 @@ it("elides the middle of a deep path without a duplicate React key", () => {
view.unmount();
useProject.setState({ project: null, settings: null });
});
describe("code breadcrumb symbol chooser", () => {
beforeEach(() => {
openFile.mockClear();
useProject.setState({
settings: {
editor: { breadcrumbs: { show: true, placement: "bottom", disabledLanguages: [] } },
} as unknown as Settings,
});
useEditorStatus.setState({ status: caret(3, 4) });
});
it("navigates to the crumb's symbol on plain click, as the IDE does", async () => {
// Orders class with place/cancel methods; caret sits inside `place`.
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
// The last crumb is the innermost symbol (place).
const place = crumbs[crumbs.length - 1]!;
expect(place.getAttribute("aria-haspopup")).toBeNull();
fireEvent.click(place);
await waitFor(() => expect(openFile).toHaveBeenCalledWith(PATH, { selection: { line: 2, col: 0 } }));
// No chooser opened with the click: that belongs to the context menu / Alt+Down.
expect(screen.queryByRole("listbox")).toBeNull();
view.unmount();
});
it("opens the sibling chooser from the crumb's context menu", async () => {
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
fireEvent.contextMenu(crumbs[crumbs.length - 1]!);
const menuItem = useContextMenuStore
.getState()
.menu?.items.find((i) => "label" in i && i.label === "Choose Symbol…") as { run?: () => void } | undefined;
expect(menuItem?.run).toBeTruthy();
act(() => menuItem!.run!());
const list = await screen.findByRole("listbox", { name: "Orders" });
expect(list.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);
// Selecting a sibling navigates.
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
await waitFor(() =>
expect(openFile).toHaveBeenCalledWith(PATH, {
selection: { line: 12, col: 0 },
focus: true,
}),
);
view.unmount();
});
it("opens the sibling chooser with Alt+Down while the strip has focus", async () => {
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
const place = crumbs[crumbs.length - 1]!;
place.focus();
fireEvent.keyDown(place, { key: "ArrowDown", altKey: true });
await screen.findByRole("listbox", { name: "Orders" });
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
await waitFor(() =>
expect(openFile).toHaveBeenCalledWith(PATH, {
selection: { line: 12, col: 0 },
focus: true,
}),
);
view.unmount();
});
it("hides the bar when there is no outline chain", () => {
useOutline.setState({ [PATH]: [] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
view.unmount();
});
});
+5
Переглянути файл
@@ -63,6 +63,7 @@ import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
import { featureBackoff } from "./availability";
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
import { javaDeclarationAt, variableNameSource } from "./variableNames";
import { editorPrefs } from "@/platform/editorSettings";
import { tx } from "@/platform/i18n";
import { showHint } from "./hint";
@@ -930,6 +931,9 @@ function gated(source: CompletionSource): CompletionSource {
if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null;
const only = exclusiveSource(ctx);
if (only) return source === contributedSource ? only(ctx) : null;
// At a Java declaration's name only names fit: IDEA lists no live templates there, and
// jdtls' own name proposals repeat the type (`orderBookOrderBook`).
if (source !== variableNameSource && javaDeclarationAt(ctx)) return null;
if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null;
if (!editorPrefs().completion.sortAlphabetically) return source(ctx);
return Promise.resolve(source(ctx)).then(
@@ -1208,6 +1212,7 @@ export function completionExtension() {
gated(contributedSource),
gated(pathFallbackSource),
gated(cssVariableSource),
gated(variableNameSource),
],
icons: false,
addToOptions: [
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { declarationAt, namesForType, pluralize } from "./variableNames";
const names = (before: string) => {
const found = declarationAt(before);
return found ? namesForType(found.type) : null;
};
describe("variable names by type (IDEA)", () => {
it("suggests the type's name and its shorter endings", () => {
expect(names(" private IMesCheckStandardService c")).toEqual([
"iMesCheckStandardService",
"mesCheckStandardService",
"checkStandardService",
"standardService",
"service",
]);
expect(names(" MesProductPlan p")).toEqual(["mesProductPlan", "productPlan", "plan"]);
expect(names(" UserServiceImpl ")).toEqual(["userService", "service"]);
expect(names(" HttpURLConnection c")).toEqual(["httpURLConnection", "urlConnection", "connection"]);
});
it("names collections, arrays, optionals and generic types by their contents", () => {
expect(names("List<MesProductCheck> l")).toEqual([
"mesProductChecks",
"productChecks",
"checks",
"mesProductCheckList",
"productCheckList",
"checkList",
"list",
]);
expect(names("Order[] ")).toEqual(["orders"]);
expect(names("Optional<User> ")).toEqual(["user", "optionalUser", "userOptional", "optional"]);
expect(names("Map<String, Order> ")).toEqual(["stringOrderMap", "orderMap", "map"]);
expect(pluralize("Category")).toBe("Categories");
expect(pluralize("Box")).toBe("Boxes");
});
it("gives locals and parameters IDEA's short names", () => {
expect(names(" String ")).toEqual(["s", "string"]);
expect(names(" private String ")).toEqual(["string"]);
expect(names(" int ")).toEqual(["i"]);
expect(names(" } catch (IOException ")).toEqual(["e", "ioException", "exception"]);
expect(names("void run(Order o")).toEqual(["order"]);
});
it("is quiet where no name is declared", () => {
expect(declarationAt(" return Foo")).toBeNull();
expect(declarationAt(" return value ")).toBeNull();
expect(declarationAt("class Foo ")).toBeNull();
expect(declarationAt(" throw new Error ")).toBeNull();
expect(declarationAt("@Autowired ")).toBeNull();
expect(declarationAt(" private c")).toBeNull();
expect(declarationAt(" var x")).toBeNull();
expect(declarationAt(" foo.bar")).toBeNull();
expect(declarationAt(" Foo f")).toEqual({ type: expect.objectContaining({ name: "Foo" }), typed: "f" });
});
});
+211
Переглянути файл
@@ -0,0 +1,211 @@
/**
* Variable names by type, as IDEA's JavaCodeStyleManager suggests them: typing the name of a
* Java declaration (`private IUserService |`, `List<Order> |`, `catch (IOException |`) lists
* `userService`, `service`, `orders`, `e`… The language server offers nothing there.
*/
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { syntaxTree } from "@codemirror/language";
import { lspDoc } from "./lsp";
/** The declared type at a name being typed: `Map<String, Order>[]` → `Map`, `[String, Order]`, array. */
export interface DeclaredType {
name: string;
args: string[];
array: boolean;
kind: "field" | "parameter" | "local";
}
const PRIMITIVES = new Set(["int", "long", "short", "byte", "char", "boolean", "float", "double"]);
/** Words before a type that make what follows something other than a declaration's name. */
const NOT_A_DECLARATION = new Set([
"new",
"class",
"interface",
"enum",
"record",
"extends",
"implements",
"permits",
"throws",
"import",
"package",
"return",
"throw",
"yield",
"assert",
"goto",
"var",
"this",
"super",
]);
const FIELD_MODIFIERS = /\b(?:private|protected|public|static|volatile|transient)\b/;
const DECLARATION =
/(^|[\s(,;{}])((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*)\s*(<[^;(){}=]*>)?((?:\s*\[\s*\])*)\s+([A-Za-z_$][\w$]*)?$/;
/**
* The type whose variable's name ends `before` (the line up to the caret), with the name typed so
* far; null when the caret isn't at a declared name.
*/
export function declarationAt(before: string): { type: DeclaredType; typed: string } | null {
const m = DECLARATION.exec(before);
if (!m) return null;
const qualified = m[2]!;
const name = qualified.slice(qualified.lastIndexOf(".") + 1);
if (!PRIMITIVES.has(name) && !/^[A-Z]/.test(name)) return null;
const head = before.slice(0, m.index + m[1]!.length);
const previous = /([A-Za-z_@][\w]*)\s*$/.exec(head)?.[1];
if (previous && (NOT_A_DECLARATION.has(previous) || previous.startsWith("@"))) return null;
if (/@\s*$/.test(head)) return null;
const params = /[(,]\s*$/.test(head) || /\(\s*(?:final\s+)?$/.test(head) || /\bcatch\s*\(\s*$/.test(head);
const kind = params ? "parameter" : FIELD_MODIFIERS.test(head) ? "field" : "local";
return {
type: { name, args: typeArguments(m[3] ?? ""), array: !!m[4]?.trim(), kind },
typed: m[5] ?? "",
};
}
/** The top-level type arguments' simple names (`<String, List<Order>>` → `String`, `List`); `?` and bounds skipped. */
function typeArguments(generic: string): string[] {
const inner = generic.slice(1, -1);
const out: string[] = [];
let depth = 0;
let current = "";
for (const ch of inner) {
if (ch === "<") depth++;
if (ch === ">") depth--;
if (ch === "," && depth === 0) {
out.push(current);
current = "";
} else if (depth === 0 && ch !== ">") current += ch;
}
out.push(current);
return out
.map((a) => a.trim())
.filter((a) => /^[A-Za-z_$][\w$.]*$/.test(a))
.map((a) => a.slice(a.lastIndexOf(".") + 1));
}
/** IDEA's NameUtilCore.nameToWordList: `IUserURLService` → `I`, `User`, `URL`, `Service`. */
function words(name: string): string[] {
return name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+|[A-Z]/g) ?? [];
}
/** StringUtil.pluralize for the usual cases. */
export function pluralize(word: string): string {
if (/(?:s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
return `${word}s`;
}
/** `UserService` → `userService`, `service` (longest first); an all-caps first word goes lower case. */
function suffixNames(name: string): string[] {
const ws = words(name);
const out: string[] = [];
for (let i = 0; i < ws.length; i++) {
const first = ws[i]!;
if (!/^[A-Za-z]/.test(first)) continue;
const head = first === first.toUpperCase() ? first.toLowerCase() : first[0]!.toLowerCase() + first.slice(1);
out.push(head + ws.slice(i + 1).join(""));
}
return out;
}
const SHORT_NAMES: Record<string, string> = {
int: "i",
boolean: "b",
byte: "b",
char: "c",
long: "l",
short: "i",
double: "v",
float: "v",
Integer: "i",
Short: "i",
Long: "l",
Boolean: "b",
Byte: "b",
Character: "c",
Double: "v",
Float: "v",
Object: "o",
String: "s",
};
const ITERABLES = new Set([
"Iterable",
"Collection",
"List",
"ArrayList",
"LinkedList",
"Set",
"HashSet",
"LinkedHashSet",
"TreeSet",
"SortedSet",
"NavigableSet",
"Queue",
"Deque",
"ArrayDeque",
"PriorityQueue",
"Stack",
"Vector",
"CopyOnWriteArrayList",
]);
/** `UserServiceImpl` names a `userService`, as in IDEA. */
const normalize = (name: string) => (name.length > 4 && name.endsWith("Impl") ? name.slice(0, -4) : name);
const JAVA_KEYWORDS = new Set(
(
"abstract assert boolean break byte case catch char class const continue default do double else enum extends " +
"final finally float for goto if implements import instanceof int interface long native new package private " +
"protected public return short static strictfp super switch synchronized this throw throws transient try void " +
"volatile while true false null var record yield"
).split(" "),
);
/** The names IDEA suggests for a variable of `type`, best first. */
export function namesForType(type: DeclaredType): string[] {
const base: string[] = [];
const short = type.kind === "field" ? undefined : SHORT_NAMES[type.name];
if (short) base.push(type.array ? pluralize(short) : short);
const name = normalize(type.name);
if (type.args.length === 1 && ITERABLES.has(type.name)) base.push(pluralize(normalize(type.args[0]!)));
if (type.args.length === 1 && type.name === "Optional") {
const content = normalize(type.args[0]!);
base.push(content, `optional${content}`);
}
if (type.args.length) base.push(type.args.map(normalize).join("") + name);
const own = type.array ? pluralize(name) : name;
if (type.kind === "parameter" && type.name.endsWith("Exception")) base.push("e");
base.push(own);
if (own.length > "Entity".length && own.endsWith("Entity")) base.push(own.slice(0, -"Entity".length));
const out: string[] = [];
for (const b of base) {
for (const n of PRIMITIVES.has(b) || b.length === 1 ? [b] : suffixNames(b)) {
if (!out.includes(n) && !JAVA_KEYWORDS.has(n) && /^[A-Za-z_$][\w$]*$/.test(n)) out.push(n);
}
}
return out;
}
/** The declaration under the caret in a Java file (not in a comment or string), or null. */
export function javaDeclarationAt(ctx: CompletionContext): { type: DeclaredType; typed: string } | null {
if (ctx.state.facet(lspDoc)?.language !== "java") return null;
const node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
if (/Comment|String|TextBlock/.test(node.name)) return null;
const line = ctx.state.doc.lineAt(ctx.pos);
return declarationAt(line.text.slice(0, ctx.pos - line.from));
}
/** Completion source: the type's names at a Java declaration's name. */
export function variableNameSource(ctx: CompletionContext): CompletionResult | null {
const found = javaDeclarationAt(ctx);
if (!found) return null;
const names = namesForType(found.type);
const options: Completion[] = names.map((label, i) => ({ label, type: "variable", boost: 50 - i }));
return options.length ? { from: ctx.pos - found.typed.length, options, validFor: /^[\w$]*$/ } : null;
}
+20
Переглянути файл
@@ -237,6 +237,26 @@
.text code {
color: var(--fg-strong);
}
.signInRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
margin: 4px 0;
}
.signInHint {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1);
margin: 0;
color: var(--fg);
overflow-wrap: anywhere;
}
.signInHint code {
font-family: var(--font-mono);
color: var(--fg-strong);
}
/* "Label: control" rows; a hint sits under its control. */
.form {
display: grid;
+66 -5
Переглянути файл
@@ -19,9 +19,23 @@ import { isCancelled, nextRequestId } from "@/platform/ipc";
import { tx, useTxTemplate } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import clsx from "clsx";
import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField, Select, Spinner, T } from "@/ui";
import {
Button,
copyText,
Dialog,
Icon,
IconButton,
Input,
List,
ProgressBar,
SearchField,
Select,
Spinner,
T,
} from "@/ui";
import { useSettingsForm } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { AgentSignInDialog, type SignInTarget } from "./AgentSignInDialog";
import { LocalCliUpdate } from "./LocalCliUpdate";
import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel";
import { providerIcon, slugifyId } from "./model";
@@ -863,6 +877,7 @@ function ProviderSettings({
return formatEnv(launchEnv(parsed));
});
const [error, setError] = useState<string | null>(null);
const [signInTarget, setSignInTarget] = useState<SignInTarget | null>(null);
// An edit can have been staged by a previous page instance. Its Apply callback
// refreshes that instance; the mounted one follows the newly applied value too.
useEffect(() => {
@@ -875,16 +890,39 @@ function ProviderSettings({
? [agent.defaultProgram, ...agent.defaultArgs].join(" ")
: formatArgs([agent.program, ...agent.args]);
const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent";
const canSignInInIde = agent.installed && (agent.canSignIn ?? false);
const commandSpan = agent.loginHint ? (/`([^`]+)`/.exec(agent.loginHint)?.[1] ?? null) : null;
return (
<>
{value.trim() === current && agent.installed && agent.canCheckCliUpdate && (
<LocalCliUpdate key={agent.program} agent={agent} backend={backend} />
)}
{agent.loginHint && (
{(agent.loginHint || canSignInInIde) && (
<Section title="Sign In">
<p className={styles.text}>
<LoginHint text={agent.loginHint} />
</p>
<div className={styles.signInRow}>
{canSignInInIde && (
<Button
size="small"
variant="primary"
onClick={() => setSignInTarget({ kind: "agent", id: agent.id, name: agent.name })}
>
<T>Sign In…</T>
</Button>
)}
{agent.loginHint && (
<p className={styles.signInHint}>
<LoginHint text={agent.loginHint} />
{commandSpan && (
<IconButton
size="small"
icon="copy"
title="Copy command"
onClick={() => void copyText(commandSpan)}
/>
)}
</p>
)}
</div>
</Section>
)}
<Section title="New Tasks">
@@ -1011,6 +1049,29 @@ function ProviderSettings({
</p>
)}
</Section>
{signInTarget && (
<AgentSignInDialog
target={signInTarget}
spawner={backend}
onClose={() => setSignInTarget(null)}
onCompleted={() => {
void refresh().catch((e: unknown) => setError(errorText(e)));
onChanged?.();
if (backend.refreshModels) {
void backend
.refreshModels(agent.id, null, true)
.then((cat) =>
useAgents.setState((s) => {
const modelCatalogs = new Map(s.modelCatalogs);
modelCatalogs.set(agent.id, cat);
return { modelCatalogs };
}),
)
.catch(() => {});
}
}}
/>
)}
</>
);
}
+32
Переглянути файл
@@ -0,0 +1,32 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 12px 16px 8px;
}
.terminal {
width: 100%;
height: 300px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-editor, var(--bg));
overflow: hidden;
padding: 6px 8px;
box-sizing: border-box;
}
.status {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.error {
margin: 0;
color: var(--fg-error, var(--danger, #d93025));
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
+191
Переглянути файл
@@ -0,0 +1,191 @@
/**
* Interactive sign-in dialog for coding agents (`copilot login`, `codex login`, `claude`, …),
* backed by an IDE-managed PTY (`agent_login_spawn`) and a lazily loaded embedded terminal widget.
*/
import { useEffect, useRef, useState } from "react";
import type { AgentLoginEvent, TerminalId } from "@/bindings";
import { tx } from "@/platform/i18n";
import { commands } from "@/platform/ipc";
import { Dialog, Spinner, T } from "@/ui";
import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributions";
import styles from "./AgentSignInDialog.module.css";
import { tauriCommands } from "./registry";
export type SignInTarget = { kind: "agent"; id: string; name: string };
export interface SignInSpawner {
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
}
export function AgentSignInDialog({
target,
spawner,
onClose,
onCompleted,
}: {
target: SignInTarget;
spawner?: SignInSpawner;
onClose: () => void;
onCompleted: () => void;
}) {
const hostRef = useRef<HTMLDivElement>(null);
const ptyIdRef = useRef<TerminalId | null>(null);
const completedRef = useRef(false);
const callbacksRef = useRef({ onClose, onCompleted, spawner });
useEffect(() => {
callbacksRef.current = { onClose, onCompleted, spawner };
});
const [attempt, setAttempt] = useState(0);
const [exitCode, setExitCode] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const agentId = target.id;
useEffect(() => {
const el = hostRef.current;
if (!el) return;
let disposed = false;
let term: EmbeddedTerminal | null = null;
const pendingOutput: string[] = [];
let pendingSize: { cols: number; rows: number } = { cols: 80, rows: 18 };
completedRef.current = false;
setExitCode(null);
setError(null);
const killPty = () => {
const id = ptyIdRef.current;
ptyIdRef.current = null;
if (id !== null) void commands.termKill(id).catch(() => {});
};
void (async () => {
try {
// Provided by the terminal feature (workbench windows) or the Settings window's boot.
const factory = embeddedTerminal();
if (!factory) throw new Error(tx("The terminal is not available in this window."));
const instance = await factory(el, {
onData: (data) => {
const id = ptyIdRef.current;
if (id !== null) void commands.termWrite(id, data).catch(() => {});
},
onResize: (cols, rows) => {
pendingSize = { cols, rows };
const id = ptyIdRef.current;
if (id !== null) void commands.termResize(id, cols, rows).catch(() => {});
},
});
if (disposed) {
instance.dispose();
return;
}
term = instance;
for (const chunk of pendingOutput.splice(0)) {
term.write(chunk);
}
term.focus();
} catch (e) {
if (!disposed) setError(e instanceof Error ? e.message : String(e));
return;
}
const onEvent = (event: AgentLoginEvent) => {
if (disposed) return;
if (event.type === "output") {
if (term) term.write(event.data);
else pendingOutput.push(event.data);
} else {
ptyIdRef.current = null;
const code = event.code ?? -1;
setExitCode(code);
if (code === 0 && !completedRef.current) {
completedRef.current = true;
callbacksRef.current.onCompleted();
callbacksRef.current.onClose();
}
}
};
try {
const custom = callbacksRef.current.spawner;
const ptyId = await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
agentId,
pendingSize.cols,
pendingSize.rows,
onEvent,
);
if (disposed) {
void commands.termKill(ptyId).catch(() => {});
return;
}
ptyIdRef.current = ptyId;
void commands.termResize(ptyId, pendingSize.cols, pendingSize.rows).catch(() => {});
term?.focus();
} catch (e) {
if (!disposed) setError(e instanceof Error ? e.message : String(e));
}
})();
return () => {
disposed = true;
killPty();
term?.dispose();
};
}, [agentId, attempt]);
const running = exitCode === null && !error;
const title = tx`Sign In to ${target.name}`;
const finishAndClose = () => {
const id = ptyIdRef.current;
ptyIdRef.current = null;
if (id !== null) void commands.termKill(id).catch(() => {});
if (!completedRef.current) {
completedRef.current = true;
onCompleted();
}
onClose();
};
const cancelAndClose = () => {
const id = ptyIdRef.current;
ptyIdRef.current = null;
if (id !== null) void commands.termKill(id).catch(() => {});
onClose();
};
return (
<Dialog
open
blockWorkbenchShortcuts
onClose={cancelAndClose}
title={title}
width={640}
footerStart={
running ? (
<span className={styles.status}>
<Spinner size={12} /> <T>Complete sign-in in your browser or the terminal above…</T>
</span>
) : exitCode !== null && exitCode !== 0 ? (
<span className={styles.error}>{tx`Sign-in exited with code ${exitCode}.`}</span>
) : undefined
}
buttons={
running
? [
{ label: "Done", onClick: finishAndClose },
{ label: "Cancel", role: "cancel", onClick: cancelAndClose },
]
: [
{ label: "Retry", role: "default", onClick: () => setAttempt((n) => n + 1) },
{ label: "Close", role: "cancel", onClick: cancelAndClose },
]
}
>
<div className={styles.body}>
<div ref={hostRef} className={styles.terminal} data-autofocus />
{error && <p className={styles.error}>{error}</p>}
</div>
</Dialog>
);
}
+6
Переглянути файл
@@ -1071,6 +1071,12 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.errorContent {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.working {
display: flex;
+66 -1
Переглянути файл
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type {
AcpImportOutcome,
AgentLoginEvent,
AgentProvider,
AgentRegistry,
InstallEvent,
@@ -13,7 +14,7 @@ import { setLocale, tx } from "@/platform/i18n";
import { iconMarkup } from "@/ui/icons";
import { MessagesHost } from "@/workbench/messages";
import { AgentRegistryPage as RegistryPage } from "./AgentRegistryPage";
import { SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
import { provideEmbeddedTerminal, SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
import { useSettingsFormFor } from "@/features/settings/components/context";
import { closeSettings, openSettings, selectPage } from "@/features/settings/model/staging";
import { SettingsDialog } from "@/features/settings/dialog/SettingsDialog";
@@ -419,6 +420,8 @@ class FakeCommands implements CommandsBackend {
list: AgentProvider[] = [];
saved: [string, string | null][] = [];
providers = vi.fn(async () => this.list);
loginSpawn?: CommandsBackend["loginSpawn"];
refreshModels?: CommandsBackend["refreshModels"];
chooseExecutable = vi.fn(async () => "/chosen/agent");
saveCustom = vi.fn(async () => {});
setAdditionalArgs = vi.fn<CommandsBackend["setAdditionalArgs"]>();
@@ -640,6 +643,68 @@ describe("Built-in executable overrides", () => {
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
});
it("runs in-IDE Sign In PTY dialog and refreshes the agent's model catalog on exit", async () => {
const written: string[] = [];
provideEmbeddedTerminal(async () => ({
write: (d) => written.push(d),
clear: vi.fn(),
focus: vi.fn(),
fit: vi.fn(),
dispose: vi.fn(),
}));
let onLoginEvent: ((e: AgentLoginEvent) => void) | null = null;
try {
const commands = new FakeCommands();
commands.loginSpawn = vi.fn(async (_id, _cols, _rows, cb) => {
onLoginEvent = cb;
return 101;
});
const refreshModels = vi.fn().mockResolvedValue({
provider: "copilot",
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
});
commands.refreshModels = refreshModels;
commands.list = [
{
...claudeProvider("copilot"),
id: "copilot",
name: "GitHub Copilot",
command: "copilot --headless --no-auto-update --stdio",
defaultProgram: "copilot",
loginHint: "Run `copilot login` in a terminal.",
installed: true,
canSignIn: true,
commandReadOnlyReason: "registry",
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
fireEvent.click(await screen.findByRole("button", { name: "Sign In…" }));
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeInTheDocument();
await waitFor(() =>
expect(commands.loginSpawn).toHaveBeenCalledWith(
"copilot",
expect.any(Number),
expect.any(Number),
expect.any(Function),
),
);
act(() => {
onLoginEvent?.({ type: "output", data: "Opening browser…\r\n" });
onLoginEvent?.({ type: "exited", code: 0 });
});
expect(written).toContain("Opening browser…\r\n");
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeNull());
expect(refreshModels).toHaveBeenCalledWith("copilot", null, true);
} finally {
provideEmbeddedTerminal(undefined);
}
});
it("Cancel discards command edits without writing", async () => {
const commands = new FakeCommands();
commands.list = [
+6 -1
Переглянути файл
@@ -1,10 +1,15 @@
import { renderHook } from "@testing-library/react";
import { afterEach, expect, it } from "vitest";
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
import { useAgentErrorText } from "./loginHint";
import { isSignInErrorMessage, useAgentErrorText } from "./loginHint";
afterEach(() => _resetI18nForTests());
it("recognizes IDE sign-in guidance messages", () => {
expect(isSignInErrorMessage("GitHub Copilot needs you to sign in. Run `copilot login` in a terminal.")).toBe(true);
expect(isSignInErrorMessage("Agent says: authentication failed")).toBe(false);
});
it.each([
["Run `cursor-agent login` in a terminal.", "在终端中运行 `cursor-agent login`。"],
["Run `'/registry path/cursor-agent' login` in a terminal.", "在终端中运行 `'/registry path/cursor-agent' login`。"],
+5 -1
Переглянути файл
@@ -1,9 +1,13 @@
import { useTx, useTxTemplate } from "@/platform/i18n";
const SIGN_IN_RE = /^(.+?) needs you to sign in\. ([^\n]+)([\s\S]*)$/;
export const isSignInErrorMessage = (message: string): boolean => SIGN_IN_RE.test(message);
/** Translate the IDE's sign-in guidance while preserving the agent's own errors. */
export function useAgentErrorText(message: string): string {
const tx = useTx();
const translate = useTxTemplate();
const auth = /^(.+?) needs you to sign in\. ([^\n]+)([\s\S]*)$/.exec(message);
const auth = SIGN_IN_RE.exec(message);
return auth ? `${tx`${auth[1]} needs you to sign in. ${translate(auth[2]!)}`}${auth[3]}` : message;
}
+11 -2
Переглянути файл
@@ -7,6 +7,7 @@ import type {
AcpImportOutcome,
AgentCliOffer,
AgentCliUpdateResult,
AgentLoginEvent,
AgentModelCatalog,
AgentProvider,
AgentRegistry,
@@ -15,6 +16,7 @@ import type {
RegistryAgent,
RegistryDistribution,
RequestId,
TerminalId,
} from "@/bindings";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
@@ -32,7 +34,8 @@ export interface CommandsBackend {
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
cancel(request: RequestId): void;
providers(): Promise<AgentProvider[]>;
refreshModels?(id: string, model: string | null): Promise<AgentModelCatalog>;
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
refreshModels?(id: string, model: string | null, force?: boolean): Promise<AgentModelCatalog>;
set(id: string, command: string | null): Promise<void>;
setAdditionalArgs(id: string, args: string[]): Promise<void>;
setEnv(id: string, env: Record<string, string>): Promise<void>;
@@ -61,7 +64,13 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
refreshModels: (id, model) => call(commands.agentRefreshModels(id, false, model)),
loginSpawn: async (id, cols, rows, onEvent) => {
const channel = new Channel<AgentLoginEvent>();
channel.onmessage = onEvent;
const info = await call(commands.agentLoginSpawn(id, cols, rows, channel));
return info.id;
},
refreshModels: (id, model, force = false) => call(commands.agentRefreshModels(id, force, model)),
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
+38 -12
Переглянути файл
@@ -1,12 +1,14 @@
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { copyText, fileIconName, Icon, IconButton, T } from "@/ui";
import { Button, copyText, fileIconName, Icon, IconButton, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { AgentSignInDialog } from "../AgentSignInDialog";
import { ImageStrip } from "../ImageStrip";
import { ReferencedText } from "../ReferenceChip";
import styles from "../Session.module.css";
@@ -14,12 +16,12 @@ import { SubmitButton } from "../SubmitButton";
import { useAgentSettings } from "../agentSettings";
import { messageTokens, parseMention } from "../composerModel";
import { formatDuration, formatSentAt, userMessageText } from "../conversation";
import { useAgentErrorText } from "../loginHint";
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
import { isBusy, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import { forkTask, rerunFrom, resendMessage } from "../store";
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { samePropsExcept, type UserEntry } from "./shared";
import { providerName, samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
/** When a message was sent, or when the turn behind a reply finished, and how long it took. */
@@ -219,12 +221,7 @@ function EntryView({
</div>
);
case "error":
return (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<AgentErrorText message={entry.message} />
</div>
);
return <AgentErrorEntry task={task} message={entry.message} />;
}
}
@@ -244,8 +241,37 @@ export const Entry = memo(
}),
);
function AgentErrorText({ message }: { message: string }) {
return <span>{useAgentErrorText(message)}</span>;
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
const [signingIn, setSigningIn] = useState(false);
const text = useAgentErrorText(message);
const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false);
const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message);
const name = providerName(task.provider);
return (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<div className={styles.errorContent}>
<span>{text}</span>
{canSignIn && (
<div>
<Button size="small" onClick={() => setSigningIn(true)}>
<T>Sign In…</T>
</Button>
</div>
)}
</div>
{signingIn && (
<AgentSignInDialog
target={{ kind: "agent", id: task.provider, name }}
onClose={() => setSigningIn(false)}
onCompleted={() => {
void refreshProviders();
void call(commands.agentRefreshModels(task.provider, true, null)).catch(() => {});
}}
/>
)}
</div>
);
}
function UserMessage({
+9
Переглянути файл
@@ -188,6 +188,15 @@ it("hands the window's whole list to the backend before startup, even after a fa
);
});
it("leaves the backend alone while no project is open", async () => {
loadBreakpoints(null);
await vi.advanceTimersByTimeAsync(200);
expect(ipc.debugReplaceBreakpoints).not.toHaveBeenCalled();
loadBreakpoints("/p");
await vi.advanceTimersByTimeAsync(0);
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledOnce();
});
it("flushes persisted breakpoints immediately after project loading", async () => {
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
localStorage.setItem(
+4 -2
Переглянути файл
@@ -138,8 +138,10 @@ async function drainBreakpoints() {
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
async function replaceBreakpoints() {
if (!isTauri() || useProject.getState().project?.trusted === false) return;
const { byFile, muted } = useBreakpoints.getState();
// Without a project (before one opens, after it closes) the backend holds no breakpoints for
// this window and has none to clear.
const { root, byFile, muted } = useBreakpoints.getState();
if (!isTauri() || root === null || useProject.getState().project?.trusted === false) return;
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
await call(commands.debugReplaceBreakpoints(files));
}
+24 -1
Переглянути файл
@@ -2,13 +2,18 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
const ghAccountRepos = vi.fn();
const toolsList = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { ghAccountRepos: () => ghAccountRepos() },
commands: {
ghAccountRepos: () => ghAccountRepos(),
toolsList: () => toolsList(),
},
}));
import type { GhAccountRepo } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { GitHubCloneSource, matchRepos } from "./GitHubCloneSource";
const repo = (nameWithOwner: string, extra: Partial<GhAccountRepo> = {}): GhAccountRepo => ({
@@ -25,6 +30,7 @@ const repos = [repo("me/app", { private: true, description: "The app" }), repo("
afterEach(() => {
cleanup();
ghAccountRepos.mockReset();
toolsList.mockReset();
});
describe("GitHub clone source", () => {
@@ -64,4 +70,21 @@ describe("GitHub clone source", () => {
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
});
it("installs GitHub CLI in-app when missing and reloads repositories", async () => {
const install = vi.fn().mockResolvedValue(undefined);
const dispose = registerAction({ id: "tools.install", title: "Install", run: install });
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "notInstalled" } });
toolsList.mockResolvedValue({ status: "ok", data: [{ name: "gh", status: "installed" }] });
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "ready", login: "me", repos } });
try {
render(<GitHubCloneSource url="" onUrl={() => {}} onClone={() => {}} disabled={false} />);
expect(await screen.findByText("GitHub CLI is not installed")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" }));
await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" })));
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
} finally {
dispose();
}
});
});
+35 -11
Переглянути файл
@@ -1,8 +1,9 @@
/** Clone Repository › GitHub: the repositories of the account gh is signed in to. */
import { useEffect, useMemo, useState, type KeyboardEvent } from "react";
import type { GhAccountRepo, GhAccountRepos } from "@/bindings";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { call, commands, isCancelled } from "@/platform/ipc";
import {
Button,
EmptyState,
@@ -37,6 +38,8 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
const [state, setState] = useState<GhAccountRepos | null>(null);
const [query, setQuery] = useState("");
const [attempt, setAttempt] = useState(0);
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
@@ -50,14 +53,26 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
const rows = useMemo(() => (state?.kind === "ready" ? matchRepos(state.repos, query) : []), [state, query]);
const active = rows.findIndex((r) => r.repo.cloneUrl === url);
const reload = () => {
setInstallError(null);
setState(null);
setAttempt((n) => n + 1);
};
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) reload();
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button
size="small"
onClick={() => {
setState(null);
setAttempt((n) => n + 1);
}}
>
<Button size="small" onClick={reload}>
<T>Retry</T>
</Button>
);
@@ -77,15 +92,24 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
</Button>
{retry}
</>
}
>
<T>GitHub repositories are listed with the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.
<code>gh auth login</code>.{installError && <div className={styles.muted}>{installError}</div>}
</EmptyState>
);
if (state.kind === "notLoggedIn")
+29 -3
Переглянути файл
@@ -7,6 +7,8 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import type { GhAvailability } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { isCancelled } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMenu, type MenuItem } from "@/ui";
import { CreatePanel } from "../create/CreatePanel";
@@ -28,6 +30,21 @@ import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
import styles from "./ToolWindow.module.css";
function Unavailable({ availability }: { availability: GhAvailability }) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) void refreshConnection();
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button size="small" onClick={() => void refreshConnection()}>
<T>Retry</T>
@@ -40,15 +57,24 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
</Button>
{retry}
</>
}
>
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.
<code>gh auth login</code>.{installError && <div className={styles.hint}>{installError}</div>}
</EmptyState>
);
case "notLoggedIn":
+18 -6
Переглянути файл
@@ -1,12 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { getAction } from "@/platform/actions";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { getAction, registerAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import * as ipc from "@/platform/ipc";
import { provideToolWindowService, useContributions, type ToolWindowService } from "@/workbench/contributions";
import { activate } from "../index";
import { setCurrentRepository } from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
import * as repositoryData from "../data/repository";
import { useGhRepository } from "../data/repository";
import { PullRequestsTabs, PullRequestsToolWindow } from "./PullRequestsToolWindow";
import {
@@ -122,10 +123,21 @@ describe("tool window", () => {
expect(show).toHaveBeenCalledWith("pullRequests", true);
});
it("shows gh's state when it is not ready", () => {
useGhRepository.setState({ availability: { kind: "notInstalled" } });
render(<PullRequestsToolWindow />);
expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy();
it("shows gh's state when it is not ready and installs gh on click", async () => {
const install = vi.fn().mockResolvedValue(undefined);
const dispose = registerAction({ id: "tools.install", title: "Install", run: install });
const refresh = vi.spyOn(repositoryData, "refreshConnection").mockResolvedValue(undefined);
try {
useGhRepository.setState({ availability: { kind: "notInstalled" } });
render(<PullRequestsToolWindow />);
expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" }));
await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" })));
await waitFor(() => expect(refresh).toHaveBeenCalledOnce());
} finally {
refresh.mockRestore();
dispose();
}
});
it("offers the repository selector for several GitHub remotes", () => {
+1
Переглянути файл
@@ -71,6 +71,7 @@ const APPEARANCE_OPTIONS: Array<[ToggleOption, string]> = [
["showHidden", "Show Hidden Files"],
["showExcluded", "Show Excluded Files"],
["showMembers", "Show Members"],
["showScratches", "Show Scratches and Consoles"],
["showRootPaths", "Show Root Paths"],
["horizontalScroll", "Horizontal Scrolling"],
["compact", "Compact Middle Packages"],
+29 -2
Переглянути файл
@@ -1,13 +1,15 @@
/** Actions of the project view (Find Action, keymap, other features via `executeAction`). */
import { activeEditor } from "@/editor/api";
import { getAction, registerActions, type Action } from "@/platform/actions";
import { executeAction, getAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { FILE_COLOR_NAMES } from "@/platform/fileColors";
import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
import { LABELS, setFileColor } from "./fileColor";
import { openNewPopup } from "./newPopupModel";
import type { ProjectNode } from "./model";
import {
@@ -111,7 +113,9 @@ function showProjectView(focus: boolean) {
export function selectInProjectView(path?: string | null, focus = true, expand = false) {
const target = path ?? maybeEditorService()?.activePath() ?? null;
if (!target) return false;
if (!modeShows(target)) setViewMode("project");
// Hidden from the Project pane (Show Scratches and Consoles off), a scratch shows in its own pane.
if (!modeShows(target))
setViewMode(modeShows(target, "project") || !modeShows(target, "scratches") ? "project" : "scratches");
showProjectView(focus);
return revealPath(target, focus, true, expand);
}
@@ -587,5 +591,28 @@ export function registerProjectActions(): () => void {
...toggles,
...modes,
...sorts,
// File Color of a single path (the project view's submenu; the editor tab menu references
// these ids with a path argument instead of importing this feature).
...FILE_COLOR_NAMES.map((name): Action => ({
id: `file.${name}`,
title: LABELS[name],
category: "Project View",
hidden: true,
run: ({ arg }) => void setFileColor(String(arg), false, name),
})),
{
id: "file.clearColor",
title: "Clear File Color",
category: "Project View",
hidden: true,
run: ({ arg }) => void setFileColor(String(arg), false, null),
},
{
id: "file.editColors",
title: "Edit File Colors…",
category: "Project View",
hidden: true,
run: () => void executeAction("file.settings", "fileColors"),
},
]);
}
+2 -1
Переглянути файл
@@ -8,7 +8,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { loadSettings, relativePath, useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
/** English title per colour, also the title of its `file.<colour>` action (the editor tab menu). */
export const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
blue: "Blue",
green: "Green",
orange: "Orange",
+24 -7
Переглянути файл
@@ -66,6 +66,8 @@ export interface ViewOptions extends TreeOptions {
showMembers: boolean;
/** Show the location of each project root beside its name. */
showRootPaths: boolean;
/** List Scratches and Consoles below the project in the Project pane. */
showScratches: boolean;
/** Rows wider than the pane scroll sideways; off clips long names (VS Code's horizontal scrolling). */
horizontalScroll: boolean;
}
@@ -78,6 +80,7 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
singleClickExpand: false,
showMembers: false,
showRootPaths: true,
showScratches: true,
horizontalScroll: true,
};
@@ -313,7 +316,14 @@ export function selectModel(s: ProjectTreeState): TreeModel {
files,
s.options.foldersFirst,
);
else model = withExtraRoots(project(), contributed, s.listings, options, placeholder);
else
model = withExtraRoots(
project(),
s.options.showScratches ? contributed : contributed.filter((r) => r.scope !== "scratches"),
s.listings,
options,
placeholder,
);
if (s.unity && s.mode === "unity" && model.roots[0])
model.roots[0].detail = s.unity.editorVersion ? `Unity ${s.unity.editorVersion}` : "Unity";
if (s.unreal && s.mode === "unreal" && model.roots[0])
@@ -921,23 +931,30 @@ export function extraRootOf(path: string): string | null {
return null;
}
const inScratches = (path: string) =>
projectViewRoots(useProjectViewRoots.getState().roots).some(
(r) => r.scope === "scratches" && r.path !== undefined && isSameOrInside(path, r.path),
);
/** A scratch the Project pane leaves out (Show Scratches and Consoles off); ones inside the project stay. */
const hiddenScratch = (path: string, { options, root }: ProjectTreeState) =>
!options.showScratches && inScratches(path) && memberRootOf(path) === null && !isSameOrInside(path, root!);
/** Whether a pane can show `path`. */
export function modeShows(path: string, mode = get().mode): boolean {
const state = get();
if (!state.root) return false;
switch (mode) {
case "unity":
return !!state.unity && unityPathVisible(path, treeOptions({ ...state, mode }));
return !!state.unity && unityPathVisible(path, treeOptions({ ...state, mode })) && !hiddenScratch(path, state);
case "unreal":
return !!state.unreal && unrealPathVisible(path, treeOptions({ ...state, mode }));
return !!state.unreal && unrealPathVisible(path, treeOptions({ ...state, mode })) && !hiddenScratch(path, state);
case "project":
return true;
return !hiddenScratch(path, state);
case "projectFiles":
return memberRootOf(path) !== null || (!state.members && isSameOrInside(path, state.root));
case "scratches":
return projectViewRoots(useProjectViewRoots.getState().roots).some(
(r) => r.scope === "scratches" && r.path !== undefined && isSameOrInside(path, r.path),
);
return inScratches(path);
default: {
if (mode === state.mode) return currentModel().keyOfPath.has(path);
const pane = { ...state, mode };
+41
Переглянути файл
@@ -186,6 +186,47 @@ describe("project view modes", () => {
expect(localStorage.getItem("openidea.projectTree.mode")).toBe(JSON.stringify("scratches"));
});
it("hides Scratches and Consoles from the Project pane only when the option is off", () => {
store.setViewOption("showScratches", false);
expect(labels()).toEqual(["proj", "External Libraries"]);
expect(modeShows("/data/scratches/s.py")).toBe(false);
expect(modeShows("/data/scratches/s.py", "scratches")).toBe(true);
expect(modeShows("/p/src/App.kt")).toBe(true);
// A scratches folder inside the project stays under the project root.
const inner = registerProjectViewRoot({
id: "inner",
label: "Inner",
icon: "scratches",
path: "/p/tmp",
scope: "scratches",
});
expect(modeShows("/p/tmp/a.txt")).toBe(true);
inner();
// The Scratches and Consoles pane and the Open Files pane still list them.
setViewMode("scratches");
expect(labels()).toEqual(["Scratches"]);
setOpenFiles(["/data/scratches/s.py"]);
setViewMode("openFiles");
expect(labels()).toEqual(["Scratches"]);
setViewMode("project");
store.setViewOption("showScratches", true);
expect(labels()).toEqual(["proj", "External Libraries", "Scratches"]);
expect(modeShows("/data/scratches/s.py")).toBe(true);
});
it("selects a hidden scratch in the Scratches and Consoles pane", async () => {
const { selectInProjectView } = await import("./actions");
store.setViewOption("showScratches", false);
expect(selectInProjectView("/data/scratches/s.py", false)).toBe(true);
expect(useProjectTree.getState().mode).toBe("scratches");
// Project files go back to the Project pane.
expect(selectInProjectView("/p/src/App.kt", false)).toBe(true);
expect(useProjectTree.getState().mode).toBe("project");
store.setViewOption("showScratches", true);
expect(selectInProjectView("/data/scratches/s.py", false)).toBe(true);
expect(useProjectTree.getState().mode).toBe("project");
});
it("keeps each pane's expansion", () => {
store.setExpanded(new Set(["/p", "/p/src"]));
setViewMode("projectFiles");
+66
Переглянути файл
@@ -0,0 +1,66 @@
import { useMemo, type ComponentType } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings, stagedValue, useSettingsDialog } from "../model/staging";
import { codeStyleLanguagePages } from "../pages/editor/codeStyle";
const mocks = vi.hoisted(() => ({ languages: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
languages: mocks.languages,
},
};
});
beforeEach(() => {
mocks.languages.mockResolvedValue([
{ id: "java", name: "Java", indent: { tabSize: 4, insertSpaces: true } },
{ id: "rust", name: "Rust" },
]);
useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null });
openSettings("editor.codeStyle.java");
});
afterEach(cleanup);
function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) {
const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]);
return (
<PageContext.Provider value={value}>
<Page />
</PageContext.Provider>
);
}
async function page(language: string) {
const pages = await codeStyleLanguagePages();
const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!;
render(<CodeStylePage id={spec.id} Page={spec.component!} />);
}
const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages");
describe("Java Imports (IntelliSort)", () => {
it("stages the class-count and static-count options on the Java code style", async () => {
await page("java");
fireEvent.click(screen.getByRole("tab", { name: "Imports" }));
fireEvent.change(screen.getByLabelText("Class count to use import with *"), { target: { value: "7" } });
fireEvent.change(screen.getByLabelText("Names count to use static import with *"), { target: { value: "2" } });
expect(value()).toEqual({
java: { classCountToUseImportWithStar: 7, namesCountToUseStaticImportWithStar: 2 },
});
fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" }));
expect(value()).toEqual({});
});
it("keeps the Imports tab specific to Java", async () => {
await page("rust");
expect(screen.queryByRole("tab", { name: "Imports" })).toBeNull();
});
});
+48 -1
Переглянути файл
@@ -157,6 +157,11 @@ const COMMENTS = {
keywords: ["Line comment at first column", "Add a space at line comment start"],
};
const CASE = { id: "case", label: "Case", keywords: ["Keywords", "Identifiers", "To upper", "To lower"] };
const IMPORTS = {
id: "imports",
label: "Imports",
keywords: ["imports", "static imports", "wildcard", "class count", "import with *"],
};
const SPACES = { id: "spaces", label: "Spaces", keywords: ["Space", "Around binary operators", "Within braces"] };
const PUNCTUATION = { id: "punctuation", label: "Punctuation", keywords: ["Semicolons", "Quotes"] };
@@ -298,6 +303,41 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
),
});
}
if (lang.id === "java") {
tabs.push({
...IMPORTS,
content: (
<FormGroup>
<Row
label="Class count to use import with '*'"
hint="Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports)."
>
<NumberInput
value={own.classCountToUseImportWithStar ?? 5}
onChange={(n) => set({ classCountToUseImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Class count to use import with *"
/>
</Row>
<Row
label="Names count to use static import with '*'"
hint="Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports)."
>
<NumberInput
value={own.namesCountToUseStaticImportWithStar ?? 3}
onChange={(n) => set({ namesCountToUseStaticImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Names count to use static import with *"
/>
</Row>
</FormGroup>
),
});
}
if (TS_STYLE_LANGUAGES.has(lang.id)) {
tabs.push(
{
@@ -501,7 +541,14 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
...keywords,
]),
...(lang.id === "java"
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
? [
"Formatting profile",
"IntelliJ IDEA",
"Custom Eclipse formatter XML",
"Eclipse formatter XML",
IMPORTS.label,
...IMPORTS.keywords,
]
: []),
...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []),
...(lang.id === "sql" ? [CASE.label, ...CASE.keywords, "Do not change"] : []),
+21
Переглянути файл
@@ -276,6 +276,27 @@ describe("annotate Options", () => {
const hidden = (v: EditorView) =>
["date", "author", "revision"].filter((c) => v.dom.classList.contains(`cm-vcs-blame-hide-${c}`));
it("prints Today/Yesterday in the date cell when pretty formatting is on", async () => {
const today = Date.now();
const yesterday = today - 86_400_000;
const recentLines: BlameLine[] = [
{ commit: sha, author: "Aleks Zlateski", timeMs: today, summary: "today" },
{ commit: otherSha, author: "Dan Crankshaw", timeMs: yesterday, summary: "yesterday" },
];
mocks.blame.mockResolvedValue({ status: "ok", data: recentLines });
useProject.setState({ settings: { general: { dateFormat: { pretty: true } } } });
const created = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }),
});
view = created;
await toggleAnnotations(created, "/repo/src/main.py");
const cell = (commit: string) =>
created.dom.querySelector<HTMLElement>(`.cm-vcs-blame [data-commit="${commit}"] .cm-vcs-blame-date`)?.textContent;
expect(cell(sha)).toBe("Today");
expect(cell(otherSha)).toBe("Yesterday");
});
it("shows date and author by default and adds the revision from Options", async () => {
view = await annotated();
expect(
+2 -2
Переглянути файл
@@ -11,7 +11,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS
import { showContextMenu, type MenuItem } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from "./BlamePopup";
import { formatDate } from "./model";
import { formatPrettyDay } from "@/platform/dateFormat";
import { saveVcsSetting } from "./settingsUi";
import { useVcs } from "./store";
@@ -318,7 +318,7 @@ function build(lines: BlameLine[], doc: Text): BlameState {
let label = labels.get(line.commit);
if (!label && !isUncommitted(line)) {
label = {
date: formatDate(line.timeMs),
date: line.timeMs ? formatPrettyDay(line.timeMs) : "",
author: shortAuthorName(line.author, names),
revision: line.commit.slice(0, 8),
};
+51 -26
Переглянути файл
@@ -1,7 +1,8 @@
/**
* Image editor kind (IDEA's image viewer): zoom in / out / fit / actual size,
* ⌘/Ctrl+wheel zoom, transparency chessboard, dimensions and file size.
* Images are read by the backend as `data:` URLs (the CSP allows those).
* Images are read by the backend as `data:` URLs (the CSP allows those). As the preview of an SVG
* file it shows the source as typed instead (`source`), drawn as an image so its scripts never run.
*/
import {
useCallback,
@@ -59,9 +60,19 @@ export function toggleChessboard() {
}
const PADDING = 32;
const NO_FOCUS_TARGET = { current: null };
const INVALID_SVG = "invalid-svg";
export function ImageViewer({ input }: { input: EditorInput }) {
/** An SVG source as an image URL. */
export const svgDataUrl = (source: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`;
/**
* `source`: the SVG text to show instead of the file on disk (the SVG editor's preview); null while
* it isn't known yet.
*/
export function ImageViewer({ input, source }: { input: EditorInput; source?: string | null }) {
const path = input.path!;
const live = source !== undefined;
const [src, setSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [size, setSize] = useState<number | null>(null);
@@ -75,18 +86,27 @@ export function ImageViewer({ input }: { input: EditorInput }) {
const canvasRef = useRef<HTMLDivElement>(null);
useEffect(() => {
let live = true;
if (live) return;
let current = true;
Promise.all([call(commands.fsReadImage(path)), call(commands.fsProbe(path))])
.then(([url, probe]) => {
if (!live) return;
if (!current) return;
setSrc(url);
setSize(probe.size);
})
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
.catch((e: unknown) => current && setError(e instanceof Error ? e.message : String(e)));
return () => {
live = false;
current = false;
};
}, [path, reload]);
}, [path, reload, live]);
// The typed source: each edit is drawn again, so an invalid SVG recovers once it's valid.
const liveSrc = useMemo(() => (source ? svgDataUrl(source) : null), [source]);
const liveSize = useMemo(() => (source ? new TextEncoder().encode(source).length : null), [source]);
const [invalidSrc, setInvalidSrc] = useState<string | null>(null);
const shownSrc = live ? liveSrc : src;
const shownSize = live ? liveSize : size;
const shownError = live ? (invalidSrc !== null && invalidSrc === liveSrc ? INVALID_SVG : null) : error;
const available = useCallback(() => {
const el = canvasRef.current;
@@ -133,7 +153,8 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
}, [handle]);
useForwardFocus(rootRef);
// Beside the source editor, the preview leaves the editor's focus alone.
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
const onLoad = (img: HTMLImageElement) => {
// SVGs without intrinsic size report 0×0; show them at a usable size.
@@ -162,7 +183,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [error, src]);
}, [shownError, shownSrc]);
const onPointerDown = (e: ReactPointerEvent) => {
if (e.button !== 0 && e.button !== 1) return;
@@ -204,15 +225,17 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<div className={styles.imageActions}>
<div className={styles.imageActionGroup}>
<IconButton icon="chessboard" size="small" action="image.toggleChessboard" pressed={chessboard} />
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
{!live && (
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
)}
</div>
<div className={styles.imageActionGroup}>
<IconButton icon="zoom-in" size="small" action="image.zoomIn" />
@@ -221,7 +244,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<IconButton icon="maximize" size="small" action="image.fitToWindow" />
</div>
</div>
{svg && (
{svg && !live && (
<button
type="button"
className={styles.textButton}
@@ -230,16 +253,18 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<T>Open as Text</T>
</button>
)}
{(natural || size !== null || view) && (
{(natural || shownSize !== null || view) && (
<div className={styles.imageInfo}>
{natural && <span>{`${natural.w} × ${natural.h}`}</span>}
{size !== null && <span>{formatSize(size)}</span>}
{shownSize !== null && <span>{formatSize(shownSize)}</span>}
{view && <span>{zoomLabel(z)}</span>}
</div>
)}
</div>
{error ? (
<div className={styles.message}>{tx`Cannot show the image: ${error}`}</div>
{shownError ? (
<div className={styles.message}>
{shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`}
</div>
) : (
<div
data-wheel-scroll
@@ -250,9 +275,9 @@ export function ImageViewer({ input }: { input: EditorInput }) {
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
{src && (
{shownSrc && (
<img
src={src}
src={shownSrc}
alt={path.slice(path.lastIndexOf("/") + 1)}
draggable={false}
className={clsx(styles.image, chessboard && styles.chessboard, z >= 4 && styles.pixelated)}
@@ -266,7 +291,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
: { visibility: "hidden" }
}
onLoad={(e) => onLoad(e.currentTarget)}
onError={() => setError("the file is not a valid image")}
onError={() => (live ? setInvalidSrc(shownSrc) : setError("the file is not a valid image"))}
/>
)}
</div>
+38
Переглянути файл
@@ -0,0 +1,38 @@
import { IconButton } from "@/ui";
import type { LayoutMode } from "./layoutModes";
import styles from "./markdown/Markdown.module.css";
/** Editor Only / Editor and Preview / Preview Only buttons of a text editor with a preview. */
export function LayoutActions({ tabId, mode, label }: { tabId: string; mode: LayoutMode; label: string }) {
return (
<div className={styles.layoutActions} role="toolbar" aria-label={label}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
}
+38 -9
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Non-text editors and the Markdown preview: images open in an image viewer,
* binary and very large files in a read-only hex view (both through file
* editor providers consulted by `openFile`), and Markdown files get IDEA's
* editor providers consulted by `openFile`), and Markdown and SVG files get IDEA's
* Editor / Editor and Preview / Preview layouts around the text editor.
*/
import { registerActions, type Action } from "@/platform/actions";
@@ -29,12 +29,16 @@ import {
imageInput,
isImagePath,
isMarkdownPath,
isSvgPath,
wantsHexView,
} from "./fileKinds";
import { ImageViewer, toggleChessboard, useImageViewers } from "./ImageViewer";
import { HexViewer } from "./HexViewer";
import { registerMarkdownLiveSource } from "./markdown/live";
import { setMarkdownMode, useMarkdownSourceHidden, type MarkdownMode } from "./markdown/modes";
import { setMarkdownMode, useMarkdownModes, useMarkdownSourceHidden } from "./markdown/modes";
import type { LayoutMode } from "./layoutModes";
import { registerSvgLiveSource } from "./svg/live";
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
@@ -65,19 +69,35 @@ function imageActions(): Action[] {
];
}
/**
* The tab whose layout an Editor Only / Editor and Preview / Preview Only action sets: the one its
* tab button passes, else the focused editor's when it's a Markdown or SVG file.
*/
function layoutTarget(arg: unknown): { tabId: string; set: (tabId: string, mode: LayoutMode) => void } | null {
if (typeof arg === "string") {
return { tabId: arg, set: svgModes.useModes.getState().byTab[arg] ? svgModes.set : setMarkdownMode };
}
const editor = activeEditor();
const path = editor?.ctx.path ?? "";
if (!editor?.tabId) return null;
if (isSvgPath(path)) return { tabId: editor.tabId, set: svgModes.set };
if (isMarkdownPath(path) || useMarkdownModes.getState().byTab[editor.tabId])
return { tabId: editor.tabId, set: setMarkdownMode };
return null;
}
function markdownActions(): Action[] {
const mode = (id: string, title: string, m: MarkdownMode, icon: string): Action => ({
const mode = (id: string, title: string, m: LayoutMode, icon: string): Action => ({
id,
title,
category: "Markdown",
icon,
keywords: ["markdown", "preview", "layout"],
when: "textEditorActive && editorLangId == markdown",
keywords: ["markdown", "svg", "preview", "layout"],
when: "textEditorActive",
enabled: ({ arg }) => !!layoutTarget(arg),
run: ({ arg }) => {
// The tab's layout buttons pass their tab; the keyboard acts on the focused editor's.
const editor = activeEditor();
const tabId = typeof arg === "string" ? arg : isMarkdownPath(editor?.ctx.path ?? "") ? editor?.tabId : undefined;
if (tabId) setMarkdownMode(tabId, m);
const target = layoutTarget(arg);
target?.set(target.tabId, m);
},
});
return [
@@ -143,6 +163,15 @@ export function activate(): () => void {
useSourceHidden: useMarkdownSourceHidden,
}),
registerMarkdownLiveSource(),
registerTextEditorWrapper({
id: "viewers.svg",
fallback: true,
matches: isSvgPath,
component: lazyComponent(() => import("./svg/SvgEditor").then((m) => m.SvgEditor)),
tabActions: SvgLayoutActions,
useSourceHidden: svgModes.useSourceHidden,
}),
registerSvgLiveSource(),
registerMenuGroup({
id: EXTRACT_IMAGES,
menus: ["editor"],
+56
Переглянути файл
@@ -0,0 +1,56 @@
/**
* Layout of a text editor with a preview (IDEA's TextEditorWithPreview): Editor Only / Editor and
* Preview / Preview Only, per editor tab. Split panes showing the same file each keep their own;
* tabs opened later take the layout chosen last for that kind of file.
*/
import { create, type StoreApi, type UseBoundStore } from "zustand";
export type LayoutMode = "editor" | "split" | "preview";
const MODES: readonly LayoutMode[] = ["editor", "split", "preview"];
export interface LayoutModesState {
byTab: Record<string, LayoutMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: LayoutMode;
}
export const modeOf = (s: LayoutModesState, tabId: string): LayoutMode => s.byTab[tabId] ?? s.fallback;
export interface LayoutModes {
useModes: UseBoundStore<StoreApi<LayoutModesState>>;
/** Preview Only hides the source editor of `tabId`. */
useSourceHidden: (tabId: string) => boolean;
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
pin: (tabId: string) => void;
set: (tabId: string, mode: LayoutMode) => void;
}
/** The layouts of one kind of file, the last one chosen kept under `storageKey`. */
export function createLayoutModes(storageKey: string): LayoutModes {
const stored = (): LayoutMode => {
try {
const v = localStorage.getItem(storageKey);
return MODES.includes(v as LayoutMode) ? (v as LayoutMode) : "split";
} catch {
return "split";
}
};
const useModes = create<LayoutModesState>(() => ({ byTab: {}, fallback: stored() }));
return {
useModes,
useSourceHidden: (tabId) => useModes((s) => modeOf(s, tabId) === "preview"),
pin: (tabId) => {
if (useModes.getState().byTab[tabId]) return;
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
},
set: (tabId, mode) => {
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(storageKey, mode);
} catch {
// Per-viewer convenience only.
}
},
};
}
+2 -33
Переглянути файл
@@ -1,39 +1,8 @@
import { IconButton } from "@/ui";
import { tx } from "@/platform/i18n";
import { LayoutActions } from "../LayoutActions";
import { modeOf, useMarkdownModes } from "./modes";
import styles from "./Markdown.module.css";
export function MarkdownLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = useMarkdownModes((s) => modeOf(s, tabId));
return (
<div className={styles.layoutActions} role="toolbar" aria-label={tx("Markdown editor layout")}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
return <LayoutActions tabId={tabId} mode={mode} label={tx("Markdown editor layout")} />;
}
+9 -44
Переглянути файл
@@ -1,47 +1,12 @@
/**
* Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. Split
* panes showing the same file each keep their own.
*/
import { create } from "zustand";
/** Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. */
import { createLayoutModes, modeOf, type LayoutMode } from "../layoutModes";
export type MarkdownMode = "editor" | "split" | "preview";
export type MarkdownMode = LayoutMode;
export { modeOf };
const DEFAULT_KEY = "openidea.markdown.defaultMode";
const MODES: readonly MarkdownMode[] = ["editor", "split", "preview"];
const markdown = createLayoutModes("openidea.markdown.defaultMode");
function storedDefault(): MarkdownMode {
try {
const v = localStorage.getItem(DEFAULT_KEY);
return MODES.includes(v as MarkdownMode) ? (v as MarkdownMode) : "split";
} catch {
return "split";
}
}
interface ModesState {
byTab: Record<string, MarkdownMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: MarkdownMode;
}
export const useMarkdownModes = create<ModesState>(() => ({ byTab: {}, fallback: storedDefault() }));
export const modeOf = (s: ModesState, tabId: string): MarkdownMode => s.byTab[tabId] ?? s.fallback;
/** Preview Only hides the source editor of `tabId`. */
export const useMarkdownSourceHidden = (tabId: string) => useMarkdownModes((s) => modeOf(s, tabId) === "preview");
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
export function pinMarkdownMode(tabId: string) {
if (useMarkdownModes.getState().byTab[tabId]) return;
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
}
export function setMarkdownMode(tabId: string, mode: MarkdownMode) {
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(DEFAULT_KEY, mode);
} catch {
// Per-viewer convenience only.
}
}
export const useMarkdownModes = markdown.useModes;
export const useMarkdownSourceHidden = markdown.useSourceHidden;
export const pinMarkdownMode = markdown.pin;
export const setMarkdownMode = markdown.set;
+95
Переглянути файл
@@ -0,0 +1,95 @@
/**
* SVG files as IDEA opens them: the source with the image viewer beside it (Editor Only / Editor and
* Preview / Preview Only), the preview redrawn from the source as it's typed.
*/
import { useEffect, useRef, type ReactNode } from "react";
import clsx from "clsx";
import { editorsFor } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { FloatingToolbar, SplitGroup, SplitHandle, SplitPanel } from "@/ui";
import { imageInput } from "../fileKinds";
import { ImageViewer } from "../ImageViewer";
import { LayoutActions } from "../LayoutActions";
import { createLayoutModes, modeOf } from "../layoutModes";
import { useLiveSvg } from "./live";
import styles from "../markdown/Markdown.module.css";
export const svgModes = createLayoutModes("openidea.svg.defaultMode");
const SPLIT_STORAGE_KEY = "openidea.svg.split";
const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
export function SvgLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
return <LayoutActions tabId={tabId} mode={mode} label={tx("SVG editor layout")} />;
}
function SvgPreview({ path }: { path: string }) {
const source = useLiveSvg((s) => s[path]) ?? null;
return <ImageViewer input={imageInput(path)} source={source} />;
}
export function SvgEditor({
path,
tabId,
children,
actionsInTabs = false,
}: {
path: string;
tabId: string;
children: ReactNode;
actionsInTabs?: boolean;
}) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
useEffect(() => svgModes.pin(tabId), [tabId]);
const ref = useRef<HTMLDivElement>(null);
const editorRef = useRef<HTMLDivElement>(null);
// CodeMirror skips resizes right after a view update; re-measure on drags and mode changes.
useEffect(() => {
const el = editorRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
let width = el.clientWidth;
const ro = new ResizeObserver(() => {
const next = el.clientWidth;
if (next === width) return;
width = next;
if (next <= 0) return;
for (const ed of editorsFor(path)) {
if (!ed.tabId || ed.tabId === tabId) ed.view.requestMeasure();
}
});
ro.observe(el);
return () => ro.disconnect();
}, [path, tabId]);
const splitBounds = mode === "split" ? { minSize: "10%", maxSize: "90%" } : {};
return (
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
<SplitGroup
orientation="horizontal"
className={styles.group}
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
defaultLayout={mode === "split" ? DEFAULT_SPLIT_LAYOUT : undefined}
>
{/* Hidden but mounted in Preview Only, so the document stays open (see MarkdownEditor). */}
<SplitPanel id="editor" style={{ overflow: "hidden" }} disabled={mode === "preview"} {...splitBounds}>
<div ref={editorRef} className={styles.editor}>
{children}
</div>
</SplitPanel>
{mode === "split" && <SplitHandle aria-label={tx("Resize SVG preview")} />}
{mode !== "editor" && (
<SplitPanel id="preview" style={{ overflow: "hidden", display: "flex" }} {...splitBounds}>
<SvgPreview path={path} />
</SplitPanel>
)}
</SplitGroup>
{!actionsInTabs && (
<FloatingToolbar targetRef={ref}>
<SvgLayoutActions path={path} tabId={tabId} />
</FloatingToolbar>
)}
</div>
);
}
+38
Переглянути файл
@@ -0,0 +1,38 @@
/** The SVG source as typed, per file, for the preview beside it (redrawn shortly after typing stops). */
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import { registerEditorContribution } from "@/editor/api";
import { isSvgPath } from "../fileKinds";
export const useLiveSvg = create<Record<string, string | undefined>>(() => ({}));
const TEXT_DELAY = 300;
const publish = (path: string, text: string) =>
useLiveSvg.getState()[path] === text || useLiveSvg.setState({ [path]: text });
function livePlugin(path: string) {
return ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
constructor(view: EditorView) {
publish(path, view.state.doc.toString());
}
update(u: ViewUpdate) {
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => publish(path, u.view.state.doc.toString()), TEXT_DELAY);
}
destroy() {
clearTimeout(this.timer);
}
},
);
}
export function registerSvgLiveSource(): () => void {
return registerEditorContribution({
id: "viewers.svgLive",
extensions: (ctx) => (!ctx.virtual && isSvgPath(ctx.path) ? [livePlugin(ctx.path)] : []),
});
}
+98
Переглянути файл
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useEffect } from "react";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { setMarkdownMode, useMarkdownModes } from "../markdown/modes";
import { activate as activateViewers } from "../index";
import { ImageViewer, svgDataUrl } from "../ImageViewer";
import { imageInput } from "../fileKinds";
import { useLiveSvg } from "./live";
import { SvgEditor, svgModes } from "./SvgEditor";
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
call: vi.fn(() => Promise.reject(new Error("no backend"))),
};
});
const PATH = "/p/icon.svg";
// Hidden until it has loaded (jsdom never loads it), so found by tag rather than role.
const image = () => document.querySelector("img")!;
describe("SVG editor", () => {
beforeEach(() => {
localStorage.clear();
svgModes.useModes.setState({ byTab: {}, fallback: "split" });
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
useLiveSvg.setState({ [PATH]: '<svg xmlns="http://www.w3.org/2000/svg" width="4" height="2"/>' });
});
afterEach(() => {
cleanup();
localStorage.clear();
});
it("shows the source and the image side by side, switching layouts without reopening the editor", () => {
let mounts = 0;
function Source() {
useEffect(() => {
mounts++;
}, []);
return <div data-testid="source" />;
}
render(
<SvgEditor path={PATH} tabId="t">
<Source />
</SvgEditor>,
);
expect(screen.getByRole("separator", { name: "Resize SVG preview" })).toBeInTheDocument();
expect(image().src).toBe(svgDataUrl(useLiveSvg.getState()[PATH]!));
// Beside the source the image viewer can't reload from disk or open the file a second time.
expect(screen.queryByRole("button", { name: "Open as Text" })).toBeNull();
expect(screen.queryByRole("button", { name: "Reload from Disk" })).toBeNull();
act(() => svgModes.set("t", "editor"));
expect(document.querySelector("img")).toBeNull();
act(() => svgModes.set("t", "preview"));
expect(image()).toBeInTheDocument();
expect(screen.getByTestId("source")).toBeInTheDocument();
expect(mounts).toBe(1);
});
it("redraws the image as the source is typed, and recovers from invalid SVG", () => {
const { rerender } = render(<ImageViewer input={imageInput(PATH)} source="<svg" />);
fireEvent.error(image());
expect(screen.getByText("The SVG source is not valid.")).toBeInTheDocument();
const fixed = '<svg xmlns="http://www.w3.org/2000/svg"/>';
rerender(<ImageViewer input={imageInput(PATH)} source={fixed} />);
expect(image().src).toBe(svgDataUrl(fixed));
expect(screen.queryByText("The SVG source is not valid.")).toBeNull();
});
it("keeps the SVG layout apart from Markdown's, and the layout actions set the tab's own", async () => {
const off = activateViewers();
setContext("textEditorActive", true);
try {
render(
<SvgEditor path={PATH} tabId="svg-tab">
<div />
</SvgEditor>,
);
setMarkdownMode("md-tab", "preview");
expect(svgModes.useModes.getState().fallback).toBe("split");
await act(() => executeAction("markdown.editorOnly", "svg-tab"));
expect(svgModes.useModes.getState().byTab["svg-tab"]).toBe("editor");
expect(useMarkdownModes.getState().byTab["md-tab"]).toBe("preview");
expect(useMarkdownModes.getState().byTab["svg-tab"]).toBeUndefined();
// The last layout chosen for an SVG is the one the next SVG opens in.
expect(localStorage.getItem("openidea.svg.defaultMode")).toBe("editor");
} finally {
setContext("textEditorActive", false);
off();
}
});
});
+6 -1
Переглянути файл
@@ -84,8 +84,13 @@ describe("file kinds", () => {
component: () => null,
});
try {
expect((await resolveFileEditor("/p/icon.svg"))?.input.kind).toBe("image");
// SVG files open as text with the image viewer beside it; a plugin's wrapper wins over it.
expect(await resolveFileEditor("/p/icon.svg")).toBeNull();
expect(await resolveFileEditor("/p/logo.png").then((r) => r?.input.kind)).toBe("image");
expect(await resolveFileEditor("/p/arch.diagram.svg")).toBeNull();
const wrappers = useTextEditorWrappers.getState().wrappers;
expect(textEditorWrapperFor(wrappers, "/p/icon.svg")?.id).toBe("viewers.svg");
expect(textEditorWrapperFor(wrappers, "/p/arch.diagram.svg")?.id).toBe("plugin.acme.diagram.canvas");
} finally {
offWrapper();
offViewers();
+14
Переглянути файл
@@ -5,6 +5,7 @@ import {
formatDateTime,
formatDay,
formatPattern,
formatPrettyDay,
formatTimestamp,
} from "./dateFormat";
@@ -33,6 +34,19 @@ describe("dateFormat", () => {
expect(formatTimestamp(d.getTime(), now, custom)).toBe("05.11.2026 09:07");
});
it("shows Today/Yesterday without a clock time for blame, older dates keep the short date", () => {
const now = new Date(2026, 10, 13, 12, 0).getTime();
const pretty = { ...system, pretty: true };
const older = new Date(2026, 10, 5, 9, 7);
const short = { year: "2-digit", month: "2-digit", day: "2-digit" } as const;
expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, pretty)).toBe("Today");
expect(formatPrettyDay(new Date(2026, 10, 12, 23, 30).getTime(), now, pretty)).toBe("Yesterday");
expect(formatPrettyDay(older.getTime(), now, pretty)).toBe(older.toLocaleDateString(undefined, short));
expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, { ...system, pretty: false })).toBe(
new Date(2026, 10, 13, 9, 7).toLocaleDateString(undefined, short),
);
});
it("formats another date with the same cached formatter", () => {
const e = new Date(2025, 0, 31);
formatDay(d, system);
+13
Переглянути файл
@@ -99,3 +99,16 @@ export function formatTimestamp(ms: number, now = Date.now(), o: DateFormatOptio
}
return formatDateTime(d, o);
}
/**
* Day without clock time (blame gutter): "Today" / "Yesterday" when pretty
* formatting is on, as IDEA's annotate shows; older dates keep the short date.
*/
export function formatPrettyDay(ms: number, now = Date.now(), o: DateFormatOptions = dateFormatOptions()): string {
const d = new Date(ms);
if (o.pretty) {
if (d.toDateString() === new Date(now).toDateString()) return tx("Today");
if (d.toDateString() === new Date(now - 86_400_000).toDateString()) return tx("Yesterday");
}
return formatDay(d, o, true);
}
+4
Переглянути файл
@@ -47,6 +47,10 @@ export interface LanguageCodeStyle {
/** SQL › Case: Reformat Code's case for keywords and unquoted identifiers. */
keywordCase?: SqlWordCase;
identifierCase?: SqlWordCase;
/** Java: organize imports switches to a wildcard import once this many classes of one package are used (jdtls passthrough). */
classCountToUseImportWithStar?: number;
/** Java: organize imports switches to a wildcard static import once this many names are used (jdtls passthrough). */
namesCountToUseStaticImportWithStar?: number;
/** JavaScript / TypeScript › Punctuation (unset: tsserver's default, `ignore` / `auto`). */
semicolons?: "ignore" | "insert" | "remove";
quotes?: "auto" | "single" | "double";
+55
Переглянути файл
@@ -0,0 +1,55 @@
/**
* Optional GitHub CLI (`gh`) installer shared by GitHub Pull Requests,
* Clone Repository › GitHub, and Settings › Agents › GitHub Copilot.
* Uses the `tools.install` action when available (workbench window, for
* status-bar progress and notifications) and falls back to `commands.toolsInstall`
* directly in standalone windows such as Settings.
*/
import { Channel } from "@tauri-apps/api/core";
import { executeAction, getAction } from "./actions";
import { call, commands, isTauri, nextRequestId, type InstallEvent, type ToolInfo } from "./ipc";
const GH_TOOL_NAME = "gh";
export const GH_MANUAL_INSTALL_URL = "https://cli.github.com";
interface GhInstallHandle {
promise: Promise<boolean>;
/** Cancels a direct install; null when delegated to the `tools.install` task queue. */
cancel: (() => void) | null;
}
/** Returns the `ide-tools` entry for `gh`, or null outside the desktop app or on lookup error. */
async function getGhToolInfo(): Promise<ToolInfo | null> {
if (!isTauri()) return null;
try {
const tools = await call(commands.toolsList());
return tools.find((tool) => tool.name === GH_TOOL_NAME) ?? null;
} catch {
return null;
}
}
/**
* Installs `gh` into OpenIDEA's managed tools directory. Resolves to `true` when
* `gh` is available afterwards, or `false` if cancelled or not installed.
* Propagates errors when running directly (the `tools.install` action reports
* its own errors via notifications).
*/
export function installGhTool(onEvent?: (event: InstallEvent) => void): GhInstallHandle {
if (getAction("tools.install")) {
const promise = (async () => {
await executeAction("tools.install", GH_TOOL_NAME);
const info = await getGhToolInfo();
return info ? info.status !== "missing" : true;
})();
return { promise, cancel: null };
}
const request = nextRequestId();
const channel = new Channel<InstallEvent>();
channel.onmessage = (event) => onEvent?.(event);
const promise = call(commands.toolsInstall(GH_TOOL_NAME, request, channel)).then((info) => info.status !== "missing");
return {
promise,
cancel: () => void commands.cancelRequest(request).catch(() => {}),
};
}
+6
Переглянути файл
@@ -120,6 +120,12 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
ToggleZenMode: "view.toggleZenMode",
EditorScrollUp: "editor.scrollUp",
EditorScrollDown: "editor.scrollDown",
EditorScrollUpAndMove: "editor.scrollUpAndMove",
EditorScrollDownAndMove: "editor.scrollDownAndMove",
EditorMoveUpAndScroll: "editor.moveUpAndScroll",
EditorMoveDownAndScroll: "editor.moveDownAndScroll",
EditorMoveUpAndScrollWithSelection: "editor.moveUpAndScrollWithSelection",
EditorMoveDownAndScrollWithSelection: "editor.moveDownAndScrollWithSelection",
EditorScrollTop: "editor.scrollToTop",
EditorScrollBottom: "editor.scrollToBottom",
EditorMoveToPageTop: "editor.moveToPageTop",
+20
Переглянути файл
@@ -92,6 +92,26 @@ describe("IntelliJ IDEA keymap import", () => {
expect(k.unknownActions).toEqual([]);
});
it("maps Scroll Up / Scroll Down and Move if Necessary", () => {
const k = parseIdeaKeymap(
`<keymap name="E" parent="$default"><action id="EditorScrollUpAndMove"><keyboard-shortcut first-keystroke="alt UP"/></action><action id="EditorScrollDownAndMove"><keyboard-shortcut first-keystroke="alt DOWN"/></action></keymap>`,
);
expect(k.overrides["editor.scrollUpAndMove"]).toEqual([normalizeBinding("Alt+Up")]);
expect(k.overrides["editor.scrollDownAndMove"]).toEqual([normalizeBinding("Alt+Down")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Move Up / Down and Scroll (with Selection)", () => {
const k = parseIdeaKeymap(
`<keymap name="E" parent="$default"><action id="EditorMoveUpAndScroll"><keyboard-shortcut first-keystroke="ctrl alt UP"/></action><action id="EditorMoveDownAndScroll"><keyboard-shortcut first-keystroke="ctrl alt DOWN"/></action><action id="EditorMoveUpAndScrollWithSelection"><keyboard-shortcut first-keystroke="ctrl alt shift UP"/></action><action id="EditorMoveDownAndScrollWithSelection"><keyboard-shortcut first-keystroke="ctrl alt shift DOWN"/></action></keymap>`,
);
expect(k.overrides["editor.moveUpAndScroll"]).toEqual([normalizeBinding("Ctrl+Alt+Up")]);
expect(k.overrides["editor.moveDownAndScroll"]).toEqual([normalizeBinding("Ctrl+Alt+Down")]);
expect(k.overrides["editor.moveUpAndScrollWithSelection"]).toEqual([normalizeBinding("Ctrl+Alt+Shift+Up")]);
expect(k.overrides["editor.moveDownAndScrollWithSelection"]).toEqual([normalizeBinding("Ctrl+Alt+Shift+Down")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Scroll to Top / Scroll to Bottom", () => {
const k = parseIdeaKeymap(
`<keymap name="X" parent="Mac OS X 10.5+"><action id="EditorScrollTop"><keyboard-shortcut first-keystroke="HOME"/></action><action id="EditorScrollBottom"><keyboard-shortcut first-keystroke="END"/></action></keymap>`,
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more