Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1382735166 | ||
|
|
9d4e778c7b | ||
|
|
c8e3fe9d2e | ||
|
|
4410da60a2 |
No files matched your search
+1
-1
@@ -87,7 +87,7 @@ tree-sitter = "0.25"
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "gzip", "deflate", "brotli"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
|
||||
@@ -46,6 +46,8 @@ const STDERR_LINES: usize = 20;
|
||||
/// Updates of a session's state rather than its conversation.
|
||||
const SESSION_STATE: [&str; 5] =
|
||||
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
|
||||
/// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]).
|
||||
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -264,6 +266,7 @@ impl AgentManager {
|
||||
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
}
|
||||
f.task.retry = None;
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
@@ -389,6 +392,7 @@ impl AgentManager {
|
||||
queue: Vec::new(),
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -577,6 +581,7 @@ impl AgentManager {
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
..s.task.clone()
|
||||
};
|
||||
TaskFile {
|
||||
@@ -830,9 +835,22 @@ impl Task {
|
||||
self.shared.emit(AgentEvent::Task { task });
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
fn set_retry(&self, retry: Option<AgentRetry>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if s.task.retry == retry {
|
||||
return;
|
||||
}
|
||||
s.task.retry = retry;
|
||||
}
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
@@ -1264,6 +1282,12 @@ impl Task {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == RETRY_UPDATE {
|
||||
if !self.replaying.load(Ordering::Acquire) {
|
||||
self.set_retry(retry_of(update, now_ms()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
@@ -1332,6 +1356,8 @@ impl Task {
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
// Output again: the retried request went through.
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
@@ -1556,6 +1582,17 @@ fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// The retry a [`RETRY_UPDATE`] announces, timed from `now`.
|
||||
fn retry_of(update: &Value, now: f64) -> Option<AgentRetry> {
|
||||
let n = |k: &str| update.get(k).and_then(Value::as_u64);
|
||||
Some(AgentRetry {
|
||||
attempt: u32::try_from(n("attempt")?).unwrap_or(u32::MAX),
|
||||
max_retries: n("maxRetries").and_then(|m| u32::try_from(m).ok()),
|
||||
retry_at_ms: now + n("retryDelayMs").unwrap_or(0) as f64,
|
||||
error: update.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
fn model_of(config: &[AgentConfigOption]) -> Option<String> {
|
||||
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
|
||||
}
|
||||
|
||||
@@ -81,6 +81,21 @@ pub struct AgentTask {
|
||||
/// When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said.
|
||||
#[serde(default)]
|
||||
pub resets_ms: Option<f64>,
|
||||
/// The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
/// by its next output or any status change.
|
||||
#[serde(default)]
|
||||
pub retry: Option<AgentRetry>,
|
||||
}
|
||||
|
||||
/// An API request the agent is about to retry.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRetry {
|
||||
pub attempt: u32,
|
||||
pub max_retries: Option<u32>,
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// One value of a select-type session setting.
|
||||
|
||||
@@ -917,6 +917,20 @@ fn pending_starts_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_retries_are_announced() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "api_retry", "attempt": 3, "max_retries": 10,
|
||||
"retry_delay_ms": 4000, "error_status": null, "error": "Connection error."}));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].session, "s");
|
||||
assert_eq!(
|
||||
out[0].update,
|
||||
json!({"sessionUpdate": crate::RETRY_UPDATE, "attempt": 3, "maxRetries": 10, "retryDelayMs": 4000,
|
||||
"error": "Connection error."})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_not_sent_twice() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! Agent tool use that launched them: their messages carry it as `parent_tool_use_id`.
|
||||
|
||||
use super::tools;
|
||||
use crate::RETRY_UPDATE;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
@@ -427,6 +428,23 @@ impl Translator {
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
// Claude Code retries a failed API request on its own; without this the turn looks stuck.
|
||||
Some("api_retry") => {
|
||||
let n = |k: &str| msg.get(k).and_then(Value::as_u64);
|
||||
let error = msg.get("error").and_then(|e| {
|
||||
e.as_str().map(str::to_owned).or_else(|| e.get("message")?.as_str().map(str::to_owned))
|
||||
});
|
||||
vec![Update {
|
||||
session: self.root.clone(),
|
||||
update: json!({
|
||||
"sessionUpdate": RETRY_UPDATE,
|
||||
"attempt": n("attempt").unwrap_or(1),
|
||||
"maxRetries": n("max_retries"),
|
||||
"retryDelayMs": n("retry_delay_ms").unwrap_or(0),
|
||||
"error": error,
|
||||
}),
|
||||
}]
|
||||
}
|
||||
Some("task_notification") if self.children.get(&tool_use).is_some_and(|c| c.background != Some(false)) => {
|
||||
let stop = match msg.get("status").and_then(Value::as_str) {
|
||||
Some("failed") => "error",
|
||||
|
||||
@@ -709,3 +709,14 @@ async fn usage_limits_and_late_settings() {
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_updates_become_a_countdown() {
|
||||
let update =
|
||||
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
|
||||
assert_eq!(
|
||||
retry_of(&update, 1000.0),
|
||||
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
|
||||
);
|
||||
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod ipc_path;
|
||||
pub mod jsonc;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod proxy_settings;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
pub mod task;
|
||||
|
||||
@@ -30,7 +30,8 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
|
||||
/// inherits them loads the image's (older) libraries and plugins next to its own, e.g.
|
||||
/// `curl: symbol lookup error ... nghttp2_...`. The IDE process keeps its environment
|
||||
/// (WebKit and GTK still need it). Then applies the [`set_env_overlay`] variables.
|
||||
/// (WebKit and GTK still need it). Then applies the [`set_env_overlay`] variables and
|
||||
/// those of a manual HTTP proxy ([`crate::proxy_settings::ProxySettings::child_env`]).
|
||||
/// Variables the call site has already set are kept. A no-op outside an AppImage
|
||||
/// without an overlay.
|
||||
pub fn host_env(cmd: &mut Command) -> &mut Command {
|
||||
@@ -89,12 +90,16 @@ fn apply_changes(
|
||||
vars
|
||||
}
|
||||
|
||||
/// The AppImage fixes, then the overlay (which wins for a name both change); one entry per name.
|
||||
/// The AppImage fixes, the overlay, then the manual proxy's (a later one wins); one entry per name.
|
||||
fn child_env_changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut changes = appimage_fixes();
|
||||
let overlay = env_overlay();
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
|
||||
changes.extend(overlay.iter().cloned());
|
||||
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
|
||||
let proxy = crate::proxy_settings::proxy().child_env();
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
|
||||
changes.extend(proxy);
|
||||
changes
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Appearance & Behavior › System Settings › HTTP Proxy, and the proxy the IDE's own
|
||||
//! connections use: [`set_proxy`] makes a configuration current, every outgoing
|
||||
//! request asks [`proxy`] (the HTTP client, `curl` downloads, the updater), and with a
|
||||
//! manual proxy child processes get `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::ffi::OsString;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ProxyMode {
|
||||
/// Every connection goes direct.
|
||||
None,
|
||||
/// The system's proxy: `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` of the environment.
|
||||
#[default]
|
||||
Auto,
|
||||
/// The proxy configured here.
|
||||
Manual,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ProxyKind {
|
||||
#[default]
|
||||
Http,
|
||||
Socks,
|
||||
}
|
||||
|
||||
impl ProxyKind {
|
||||
pub fn default_port(self) -> u16 {
|
||||
match self {
|
||||
ProxyKind::Http => 80,
|
||||
ProxyKind::Socks => 1080,
|
||||
}
|
||||
}
|
||||
|
||||
fn scheme(self) -> &'static str {
|
||||
match self {
|
||||
ProxyKind::Http => "http",
|
||||
// Host names resolve on the proxy.
|
||||
ProxyKind::Socks => "socks5h",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ProxySettings {
|
||||
pub mode: ProxyMode,
|
||||
pub kind: ProxyKind,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
/// Hosts reached directly, comma-separated; `*` matches any characters (`*.example.com`, `192.168.*`).
|
||||
pub no_proxy: String,
|
||||
/// Send `login` / `password` to the proxy.
|
||||
pub authenticate: bool,
|
||||
pub login: String,
|
||||
/// Kept in the saved passwords rather than `settings.toml`; filled in when settings are read.
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
impl Default for ProxySettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: ProxyMode::Auto,
|
||||
kind: ProxyKind::Http,
|
||||
host: String::new(),
|
||||
port: ProxyKind::Http.default_port(),
|
||||
no_proxy: String::new(),
|
||||
authenticate: false,
|
||||
login: String::new(),
|
||||
password: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ProxySettings {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ProxySettings")
|
||||
.field("mode", &self.mode)
|
||||
.field("kind", &self.kind)
|
||||
.field("host", &self.host)
|
||||
.field("port", &self.port)
|
||||
.field("no_proxy", &self.no_proxy)
|
||||
.field("authenticate", &self.authenticate)
|
||||
.field("login", &self.login)
|
||||
.field("password", &if self.password.is_empty() { "" } else { "***" })
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// How a connection to some host is made.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ProxyRoute {
|
||||
Direct,
|
||||
/// Whatever the environment says (the HTTP library's / `curl`'s own proxy lookup).
|
||||
System,
|
||||
/// Through this proxy URL, credentials included (`http://user:pass@proxy:3128`).
|
||||
Via(String),
|
||||
}
|
||||
|
||||
/// Loopback hosts never go through the manual proxy.
|
||||
const LOOPBACK: [&str; 3] = ["localhost", "127.0.0.1", "::1"];
|
||||
|
||||
impl ProxySettings {
|
||||
/// A manual proxy with a host: what [`Self::route`] sends connections through.
|
||||
pub fn manual(&self) -> bool {
|
||||
self.mode == ProxyMode::Manual && !self.host.trim().is_empty()
|
||||
}
|
||||
|
||||
/// What is wrong with the manual configuration, if anything.
|
||||
pub fn problem(&self) -> Option<String> {
|
||||
if self.mode != ProxyMode::Manual {
|
||||
return None;
|
||||
}
|
||||
let host = self.host.trim();
|
||||
if host.is_empty() {
|
||||
return Some("Proxy host is empty".into());
|
||||
}
|
||||
if host.contains(['/', '@', ' ']) {
|
||||
return Some(format!("Invalid proxy host: {host}"));
|
||||
}
|
||||
if self.port == 0 {
|
||||
return Some("Proxy port must be between 1 and 65535".into());
|
||||
}
|
||||
if self.authenticate && self.login.trim().is_empty() {
|
||||
return Some("Proxy login is empty".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `host` is reached directly: loopback, or a "No proxy for" entry.
|
||||
pub fn bypasses(&self, host: &str) -> bool {
|
||||
let host = host.trim().trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase();
|
||||
if LOOPBACK.contains(&host.as_str()) {
|
||||
return true;
|
||||
}
|
||||
self.no_proxy_entries().any(|pattern| glob_match(&pattern, &host))
|
||||
}
|
||||
|
||||
fn no_proxy_entries(&self) -> impl Iterator<Item = String> + '_ {
|
||||
self.no_proxy.split([',', ';', '\n']).map(|e| e.trim().to_ascii_lowercase()).filter(|e| !e.is_empty())
|
||||
}
|
||||
|
||||
/// The manual proxy as a URL, with the credentials when it authenticates.
|
||||
pub fn proxy_url(&self) -> Option<String> {
|
||||
if !self.manual() {
|
||||
return None;
|
||||
}
|
||||
let host = self.host.trim();
|
||||
let host = if host.contains(':') && !host.starts_with('[') { format!("[{host}]") } else { host.to_owned() };
|
||||
let auth = if self.authenticate && !self.login.is_empty() {
|
||||
format!("{}:{}@", encode_userinfo(&self.login), encode_userinfo(&self.password))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
Some(format!("{}://{auth}{host}:{}", self.kind.scheme(), self.port))
|
||||
}
|
||||
|
||||
/// How to connect to `host` (`None`: not known yet, e.g. the request has no URL).
|
||||
pub fn route(&self, host: Option<&str>) -> ProxyRoute {
|
||||
match self.mode {
|
||||
ProxyMode::None => ProxyRoute::Direct,
|
||||
ProxyMode::Auto => ProxyRoute::System,
|
||||
ProxyMode::Manual => match self.proxy_url() {
|
||||
Some(_) if host.is_some_and(|h| self.bypasses(h)) => ProxyRoute::Direct,
|
||||
Some(url) => ProxyRoute::Via(url),
|
||||
None => ProxyRoute::Direct,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::route`] for the host of `url` (`https://user@host:443/path`).
|
||||
pub fn route_for_url(&self, url: &str) -> ProxyRoute {
|
||||
self.route(url_host(url).as_deref())
|
||||
}
|
||||
|
||||
/// Arguments that make a `curl` download of `url` follow this configuration. The
|
||||
/// manual proxy itself comes from the environment (see [`Self::child_env`]), which
|
||||
/// keeps the credentials out of the command line.
|
||||
pub fn curl_args(&self, url: &str) -> Vec<&'static str> {
|
||||
match self.route_for_url(url) {
|
||||
ProxyRoute::Direct => vec!["--noproxy", "*"],
|
||||
ProxyRoute::System => Vec::new(),
|
||||
// Only this configuration decides what bypasses the proxy.
|
||||
ProxyRoute::Via(_) => vec!["--noproxy", ""],
|
||||
}
|
||||
}
|
||||
|
||||
/// Variables child processes get with a manual proxy (`HTTP_PROXY`, `HTTPS_PROXY`,
|
||||
/// `ALL_PROXY`, `NO_PROXY` and their lowercase forms); none otherwise.
|
||||
pub fn child_env(&self) -> Vec<(OsString, Option<OsString>)> {
|
||||
let Some(url) = self.proxy_url() else { return Vec::new() };
|
||||
let mut no_proxy: Vec<String> = LOOPBACK.iter().map(|h| (*h).to_owned()).collect();
|
||||
// `*.example.com` is `.example.com` to curl, Go, Python and Node.
|
||||
no_proxy.extend(self.no_proxy_entries().map(|e| e.strip_prefix('*').map(str::to_owned).unwrap_or(e)));
|
||||
no_proxy.dedup();
|
||||
let no_proxy = no_proxy.join(",");
|
||||
let mut env = Vec::new();
|
||||
for name in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"] {
|
||||
env.push((OsString::from(name), Some(OsString::from(&url))));
|
||||
env.push((OsString::from(name.to_ascii_lowercase()), Some(OsString::from(&url))));
|
||||
}
|
||||
env.push((OsString::from("NO_PROXY"), Some(OsString::from(&no_proxy))));
|
||||
env.push((OsString::from("no_proxy"), Some(OsString::from(no_proxy))));
|
||||
env
|
||||
}
|
||||
}
|
||||
|
||||
/// Case-insensitive host glob (`pattern` is lowercase): `*` matches any run of characters.
|
||||
fn glob_match(pattern: &str, host: &str) -> bool {
|
||||
let (p, h) = (pattern.as_bytes(), host.as_bytes());
|
||||
let (mut pi, mut hi) = (0, 0);
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while hi < h.len() {
|
||||
if pi < p.len() && p[pi] == b'*' {
|
||||
star = Some((pi, hi));
|
||||
pi += 1;
|
||||
} else if pi < p.len() && p[pi] == h[hi] {
|
||||
pi += 1;
|
||||
hi += 1;
|
||||
} else if let Some((sp, sh)) = star {
|
||||
pi = sp + 1;
|
||||
hi = sh + 1;
|
||||
star = Some((sp, sh + 1));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
p[pi..].iter().all(|&c| c == b'*')
|
||||
}
|
||||
|
||||
fn encode_userinfo(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The host of `url`, without brackets, userinfo or port.
|
||||
fn url_host(url: &str) -> Option<String> {
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
let authority = rest.split(['/', '?', '#']).next()?;
|
||||
let authority = authority.rsplit_once('@').map_or(authority, |(_, a)| a);
|
||||
let host =
|
||||
if let Some(v6) = authority.strip_prefix('[') { v6.split(']').next()? } else { authority.split(':').next()? };
|
||||
(!host.is_empty()).then(|| host.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
static CURRENT: RwLock<Option<Arc<ProxySettings>>> = RwLock::new(None);
|
||||
|
||||
/// Makes `settings` (password filled in) the proxy of every later connection and child process.
|
||||
pub fn set_proxy(settings: ProxySettings) {
|
||||
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(settings));
|
||||
}
|
||||
|
||||
/// The current proxy configuration (the default, auto-detect, until [`set_proxy`]).
|
||||
pub fn proxy() -> Arc<ProxySettings> {
|
||||
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn manual(host: &str, port: u16) -> ProxySettings {
|
||||
ProxySettings { mode: ProxyMode::Manual, host: host.into(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_is_the_default_and_defers_to_the_system() {
|
||||
let p = ProxySettings::default();
|
||||
assert_eq!(p.mode, ProxyMode::Auto);
|
||||
assert_eq!(p.route_for_url("https://example.com/"), ProxyRoute::System);
|
||||
assert!(p.curl_args("https://example.com/").is_empty());
|
||||
assert!(p.child_env().is_empty());
|
||||
assert_eq!(p.problem(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_proxy_goes_direct() {
|
||||
let p = ProxySettings { mode: ProxyMode::None, ..manual("proxy", 3128) };
|
||||
assert_eq!(p.route_for_url("https://example.com/"), ProxyRoute::Direct);
|
||||
assert_eq!(p.curl_args("https://example.com/"), ["--noproxy", "*"]);
|
||||
assert!(p.child_env().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_http_and_socks_urls() {
|
||||
let p = manual("proxy.corp", 3128);
|
||||
assert_eq!(p.route_for_url("https://example.com/x"), ProxyRoute::Via("http://proxy.corp:3128".into()));
|
||||
assert_eq!(p.curl_args("https://example.com/x"), ["--noproxy", ""]);
|
||||
let socks = ProxySettings { kind: ProxyKind::Socks, ..manual("10.0.0.1", 1080) };
|
||||
assert_eq!(socks.proxy_url().as_deref(), Some("socks5h://10.0.0.1:1080"));
|
||||
assert_eq!(manual("::1", 8080).proxy_url().as_deref(), Some("http://[::1]:8080"));
|
||||
// Manual without a host connects directly.
|
||||
assert_eq!(manual(" ", 80).route(Some("example.com")), ProxyRoute::Direct);
|
||||
assert!(manual(" ", 80).problem().is_some());
|
||||
assert!(manual("proxy", 0).problem().is_some());
|
||||
assert!(manual("http://proxy", 80).problem().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_are_percent_encoded() {
|
||||
let p = ProxySettings {
|
||||
authenticate: true,
|
||||
login: "dom\\me".into(),
|
||||
password: "p@ss:w/rd".into(),
|
||||
..manual("proxy", 3128)
|
||||
};
|
||||
assert_eq!(p.proxy_url().as_deref(), Some("http://dom%5Cme:p%40ss%3Aw%2Frd@proxy:3128"));
|
||||
// Not sent without "Proxy authentication".
|
||||
let off = ProxySettings { authenticate: false, ..p.clone() };
|
||||
assert_eq!(off.proxy_url().as_deref(), Some("http://proxy:3128"));
|
||||
assert!(ProxySettings { login: " ".into(), ..p.clone() }.problem().is_some());
|
||||
assert!(!format!("{p:?}").contains("p@ss"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_proxy_for_list_matches_globs_and_loopback() {
|
||||
let p = ProxySettings { no_proxy: "*.example.com, 192.168.*,Intranet".into(), ..manual("proxy", 3128) };
|
||||
assert!(p.bypasses("api.example.com"));
|
||||
assert!(p.bypasses("a.b.EXAMPLE.com"));
|
||||
assert!(!p.bypasses("example.com"));
|
||||
assert!(!p.bypasses("example.com.evil.org"));
|
||||
assert!(p.bypasses("192.168.1.20"));
|
||||
assert!(p.bypasses("intranet"));
|
||||
assert!(!p.bypasses("intranet2"));
|
||||
assert!(p.bypasses("localhost") && p.bypasses("127.0.0.1") && p.bypasses("[::1]"));
|
||||
assert_eq!(p.route_for_url("https://user@api.example.com:8443/v1"), ProxyRoute::Direct);
|
||||
assert_eq!(p.curl_args("http://192.168.0.5/"), ["--noproxy", "*"]);
|
||||
assert!(matches!(p.route_for_url("https://github.com"), ProxyRoute::Via(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_processes_get_the_manual_proxy() {
|
||||
let p = ProxySettings {
|
||||
no_proxy: "*.corp, 10.*".into(),
|
||||
authenticate: true,
|
||||
login: "me".into(),
|
||||
password: "pw".into(),
|
||||
..manual("proxy", 3128)
|
||||
};
|
||||
let env = p.child_env();
|
||||
let get = |k: &str| env.iter().find(|(n, _)| n == k).and_then(|(_, v)| v.clone()).unwrap();
|
||||
assert_eq!(get("HTTPS_PROXY"), "http://me:pw@proxy:3128");
|
||||
assert_eq!(get("http_proxy"), "http://me:pw@proxy:3128");
|
||||
assert_eq!(get("NO_PROXY"), "localhost,127.0.0.1,::1,.corp,10.*");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn url_hosts() {
|
||||
assert_eq!(url_host("https://Example.com:443/a?b").as_deref(), Some("example.com"));
|
||||
assert_eq!(url_host("http://u:p@[::1]:80/").as_deref(), Some("::1"));
|
||||
assert_eq!(url_host("example.com/x").as_deref(), Some("example.com"));
|
||||
assert_eq!(url_host("file:///tmp/x"), None);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
pub use crate::editor_settings::*;
|
||||
pub use crate::inspection_settings::*;
|
||||
pub use crate::proxy_settings::{ProxyKind, ProxyMode, ProxySettings};
|
||||
pub use crate::remote_settings::*;
|
||||
pub use crate::workflow_settings::*;
|
||||
|
||||
@@ -25,6 +26,8 @@ pub struct Settings {
|
||||
/// keymap's own overrides. `keymap` may name one of these ids.
|
||||
pub custom_keymaps: BTreeMap<String, CustomKeymap>,
|
||||
pub notifications: NotificationSettings,
|
||||
/// System Settings › HTTP Proxy (global only).
|
||||
pub proxy: ProxySettings,
|
||||
/// Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript).
|
||||
pub languages: LanguagesSettings,
|
||||
/// Project Structure: source / test / resource / excluded folders (project-relative).
|
||||
@@ -134,6 +137,7 @@ impl Default for Settings {
|
||||
keymap_overrides: BTreeMap::new(),
|
||||
custom_keymaps: BTreeMap::new(),
|
||||
notifications: NotificationSettings::default(),
|
||||
proxy: ProxySettings::default(),
|
||||
languages: LanguagesSettings::default(),
|
||||
project_structure: ProjectStructureSettings::default(),
|
||||
vcs: VcsSettings::default(),
|
||||
|
||||
@@ -395,6 +395,8 @@ mod tests {
|
||||
assert_eq!(changed_names(&before, &after), ["B", "C", "D"]);
|
||||
}
|
||||
|
||||
// Used by the Unix-only post-start tests.
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
#[derive(Default)]
|
||||
struct Events(Mutex<Vec<IdeEvent>>);
|
||||
impl EventSink for Events {
|
||||
@@ -403,6 +405,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
fn run(cmd: LifecycleCommand, root: &Path) -> Vec<IdeEvent> {
|
||||
let events = Arc::new(Events::default());
|
||||
let sink: SharedSink = events.clone();
|
||||
@@ -410,6 +413,7 @@ mod tests {
|
||||
events.0.lock().clone()
|
||||
}
|
||||
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
fn failure(events: &[IdeEvent]) -> Option<String> {
|
||||
events.iter().find_map(|e| match e {
|
||||
IdeEvent::Notify { level: NotifyLevel::Error, body, .. } => body.clone(),
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
pub mod environment;
|
||||
pub mod ops;
|
||||
mod project;
|
||||
mod proxy;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
@@ -56,6 +57,8 @@ pub struct Host {
|
||||
pub remote: Arc<ide_remote::RemoteService>,
|
||||
/// What child processes get beyond this process's environment (Reload Environment, `remoteEnv`).
|
||||
pub environment: environment::Environment,
|
||||
/// The HTTP proxy's saved password (see `proxy.rs`).
|
||||
proxy_password: ide_ssh::secrets::SecretFile,
|
||||
pub(crate) sink_for: SinkFactory,
|
||||
owner: fn(&str) -> &str,
|
||||
pub runtime: tokio::runtime::Handle,
|
||||
@@ -71,7 +74,8 @@ impl Host {
|
||||
let global_settings = SettingsStore::load(&config_dir, None);
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
Self {
|
||||
let host = Self {
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
|
||||
ssh,
|
||||
environment: environment::Environment::new(project_environment, data_dir.clone()),
|
||||
@@ -89,7 +93,9 @@ impl Host {
|
||||
runtime,
|
||||
projects: RwLock::default(),
|
||||
requests: Default::default(),
|
||||
}
|
||||
};
|
||||
host.apply_proxy();
|
||||
host
|
||||
}
|
||||
|
||||
/// The tree-sitter grammars (blocks only if start-up warm-up is still running).
|
||||
|
||||
@@ -43,10 +43,10 @@ pub fn current(host: &Host, window: &str) -> Option<ProjectInfo> {
|
||||
|
||||
/// Effective settings for the window's project, or global settings without one.
|
||||
pub fn settings(host: &Host, window: &str) -> Settings {
|
||||
match host.project(window) {
|
||||
host.with_proxy_password(match host.project(window) {
|
||||
Ok(p) => p.settings.effective(),
|
||||
Err(_) => host.global_settings.effective(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
|
||||
@@ -64,7 +64,8 @@ pub struct SettingsApplied {
|
||||
|
||||
/// Sets `key` to `value` (JSON text, e.g. `14` or `"dark"`) for the window's
|
||||
/// project or globally, and applies it to the open projects: file defaults,
|
||||
/// file types, language servers, index scope and SSH configurations.
|
||||
/// file types, language servers, index scope, SSH configurations and the HTTP proxy
|
||||
/// (whose password goes to the saved passwords, not the settings file).
|
||||
pub fn set_settings(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -77,6 +78,11 @@ pub fn set_settings(
|
||||
let current = host.project(window).ok();
|
||||
// A LightEdit window has no project layer: its values are global.
|
||||
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
|
||||
let is_proxy = key == "proxy" || key.starts_with("proxy.");
|
||||
let Some(value) = host.take_proxy_password(key, value)? else {
|
||||
host.apply_proxy();
|
||||
return Ok(SettingsApplied { settings: settings(host, window), project_scope, roots_changed: None });
|
||||
};
|
||||
let settings = match ¤t {
|
||||
Some(p) if project_scope => p.settings.set(scope, key, value)?,
|
||||
Some(p) => {
|
||||
@@ -113,6 +119,9 @@ pub fn set_settings(
|
||||
if key == "ssh" || key.starts_with("ssh.") {
|
||||
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
|
||||
}
|
||||
if is_proxy {
|
||||
host.apply_proxy();
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
if ["languages", "tools", "languageServers"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
|
||||
for project in affected() {
|
||||
@@ -132,5 +141,5 @@ pub fn set_settings(
|
||||
});
|
||||
}
|
||||
let roots_changed = current.as_ref().filter(|_| roots_changed && project_scope).map(|p| p.root.clone().into());
|
||||
Ok(SettingsApplied { settings, project_scope, roots_changed })
|
||||
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! System Settings › HTTP Proxy on the host: the global settings made current for
|
||||
//! connections and child processes, the password kept in the saved passwords
|
||||
//! (owner-only `proxy-password.json`) instead of `settings.toml`.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::settings::Settings;
|
||||
|
||||
const PASSWORD_KEY: &str = "httpProxy";
|
||||
|
||||
impl Host {
|
||||
/// `settings` with the saved proxy password filled in, as the Settings dialog edits it.
|
||||
pub fn with_proxy_password(&self, mut settings: Settings) -> Settings {
|
||||
// A password typed into settings.toml by hand counts too, unless one was saved.
|
||||
if let Some(password) = self.proxy_password.get(PASSWORD_KEY) {
|
||||
settings.proxy.password = password;
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Makes the global proxy settings the proxy of every later connection and child process.
|
||||
pub fn apply_proxy(&self) {
|
||||
let settings = self.with_proxy_password(self.global_settings.effective());
|
||||
if let Some(problem) = settings.proxy.problem() {
|
||||
tracing::warn!("HTTP proxy: {problem}");
|
||||
}
|
||||
ide_core::proxy_settings::set_proxy(settings.proxy);
|
||||
}
|
||||
|
||||
/// Takes the proxy password out of a settings write of `key` and saves it.
|
||||
/// Returns the value left to write, `None` when nothing is.
|
||||
pub(crate) fn take_proxy_password(
|
||||
&self,
|
||||
key: &str,
|
||||
mut value: serde_json::Value,
|
||||
) -> IdeResult<Option<serde_json::Value>> {
|
||||
let password = match key {
|
||||
"proxy.password" => Some(value.take()),
|
||||
"proxy" => value.as_object_mut().and_then(|o| o.remove("password")),
|
||||
_ => return Ok(Some(value)),
|
||||
};
|
||||
if let Some(password) = password {
|
||||
match password.as_str().filter(|p| !p.is_empty()) {
|
||||
Some(p) => self.proxy_password.set(PASSWORD_KEY, p)?,
|
||||
None => self.proxy_password.delete(PASSWORD_KEY),
|
||||
}
|
||||
}
|
||||
Ok((key != "proxy.password").then_some(value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! System Settings › HTTP Proxy: applied on write, the password kept out of settings.toml.
|
||||
|
||||
use ide_core::NullSink;
|
||||
use ide_core::proxy_settings::{ProxyMode, ProxyRoute, proxy};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_workspace::SettingsScope;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn host(base: &std::path::Path) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}))
|
||||
}
|
||||
|
||||
fn set(host: &Host, key: &str, value: &str) -> ide_core::settings::Settings {
|
||||
ops::project::set_settings(host, "main", SettingsScope::Global, key, value).unwrap().settings
|
||||
}
|
||||
|
||||
fn settings_files(base: &std::path::Path) -> String {
|
||||
let mut text = String::new();
|
||||
for entry in walk(&base.join("config")) {
|
||||
text.push_str(&std::fs::read_to_string(entry).unwrap_or_default());
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() { out.extend(walk(&path)) } else { out.push(path) }
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn manual_proxy_applies_and_the_password_is_saved_apart() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
assert_eq!(proxy().mode, ProxyMode::Auto);
|
||||
|
||||
set(&host, "proxy.mode", "\"manual\"");
|
||||
set(&host, "proxy.host", "\"proxy.corp\"");
|
||||
set(&host, "proxy.port", "3128");
|
||||
set(&host, "proxy.authenticate", "true");
|
||||
set(&host, "proxy.login", "\"me\"");
|
||||
let settings = set(&host, "proxy.password", "\"s3cret\"");
|
||||
assert_eq!(settings.proxy.password, "s3cret", "the dialog sees the saved password");
|
||||
assert_eq!(
|
||||
proxy().route_for_url("https://example.com/"),
|
||||
ProxyRoute::Via("http://me:s3cret@proxy.corp:3128".into())
|
||||
);
|
||||
|
||||
assert!(!settings_files(tmp.path()).contains("s3cret"), "no password in settings.toml");
|
||||
let saved = std::fs::read_to_string(tmp.path().join("data/proxy-password.json")).unwrap();
|
||||
assert!(saved.contains("s3cret"));
|
||||
assert_eq!(ops::project::settings(&host, "main").proxy.password, "s3cret");
|
||||
|
||||
// A whole-table write keeps the password out of the file too; an empty one forgets it.
|
||||
let settings = set(&host, "proxy", r#"{"mode":"none","host":"proxy.corp","password":""}"#);
|
||||
assert_eq!(settings.proxy.password, "");
|
||||
assert!(!settings_files(tmp.path()).contains("password"));
|
||||
assert_eq!(proxy().route_for_url("https://example.com/"), ProxyRoute::Direct);
|
||||
|
||||
set(&host, "proxy", r#"{"mode":"auto"}"#);
|
||||
assert_eq!(proxy().mode, ProxyMode::Auto);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! The one place the backend builds an HTTP client: TLS with the platform's
|
||||
//! certificates, timeouts, and the proxy of System Settings › HTTP Proxy.
|
||||
|
||||
use ide_core::proxy_settings::{ProxyMode, ProxyRoute, ProxySettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// `builder` routed as `proxy` says: direct, the environment's proxy (reqwest's
|
||||
/// default), or the manual proxy except for the "No proxy for" hosts.
|
||||
pub fn with_proxy(builder: reqwest::ClientBuilder, proxy: &ProxySettings) -> reqwest::ClientBuilder {
|
||||
match proxy.mode {
|
||||
ProxyMode::Auto => builder,
|
||||
ProxyMode::None => builder.no_proxy(),
|
||||
ProxyMode::Manual => {
|
||||
let proxy = proxy.clone();
|
||||
// A custom proxy also turns off the environment's.
|
||||
builder.proxy(reqwest::Proxy::custom(move |url| match proxy.route(url.host_str()) {
|
||||
ProxyRoute::Via(via) => Some(via),
|
||||
ProxyRoute::Direct | ProxyRoute::System => None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A client for `proxy`.
|
||||
pub fn build(proxy: &ProxySettings) -> IdeResult<reqwest::Client> {
|
||||
use rustls_platform_verifier::BuilderVerifierExt;
|
||||
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let tls = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| fail(e.to_string()))?
|
||||
.with_platform_verifier()
|
||||
.map_err(|e| fail(e.to_string()))?
|
||||
.with_no_client_auth();
|
||||
let builder = reqwest::Client::builder()
|
||||
.tls_backend_preconfigured(tls)
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")));
|
||||
with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string()))
|
||||
}
|
||||
|
||||
/// The client for the current proxy settings, rebuilt when they change.
|
||||
pub fn shared() -> IdeResult<reqwest::Client> {
|
||||
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
|
||||
let proxy = ide_core::proxy_settings::proxy();
|
||||
let mut cached = CLIENT.lock();
|
||||
if let Some((settings, client)) = cached.as_ref()
|
||||
&& **settings == *proxy
|
||||
{
|
||||
return Ok(client.clone());
|
||||
}
|
||||
let client = build(&proxy)?;
|
||||
*cached = Some((proxy, client.clone()));
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// HTTP Proxy › Check connection: GETs `url` through `proxy` (the settings as
|
||||
/// edited, not yet applied). Any response but `407` counts as connected.
|
||||
pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
if let Some(problem) = proxy.problem() {
|
||||
return Err(IdeError::invalid(problem));
|
||||
}
|
||||
let url = url.trim();
|
||||
let url = if url.contains("://") { url.to_owned() } else { format!("http://{url}") };
|
||||
let client = build(proxy)?;
|
||||
let request = client.get(&url).timeout(Duration::from_secs(30));
|
||||
let response = tokio::select! {
|
||||
r = request.send() => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?,
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
};
|
||||
let status = response.status();
|
||||
if status == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED {
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "Proxy authentication required (407)"));
|
||||
}
|
||||
Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned())
|
||||
}
|
||||
|
||||
/// reqwest errors with their causes ("error sending request: … connection refused").
|
||||
pub(crate) fn describe(e: &reqwest::Error) -> String {
|
||||
use std::error::Error;
|
||||
let mut msg = e.to_string();
|
||||
let mut source = e.source();
|
||||
while let Some(s) = source {
|
||||
let s_msg = s.to_string();
|
||||
if !msg.contains(&s_msg) {
|
||||
msg.push_str(": ");
|
||||
msg.push_str(&s_msg);
|
||||
}
|
||||
source = s.source();
|
||||
}
|
||||
msg
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::proxy_settings::ProxyKind;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
/// A one-shot HTTP server on loopback: answers `200` and hands back the request head.
|
||||
fn server() -> (u16, std::thread::JoinHandle<String>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let handle = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut head = String::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
head.push_str(&line);
|
||||
}
|
||||
let mut stream = stream;
|
||||
stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").unwrap();
|
||||
head
|
||||
});
|
||||
(port, handle)
|
||||
}
|
||||
|
||||
fn manual(port: u16) -> ProxySettings {
|
||||
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
async fn get(proxy: &ProxySettings, url: &str) -> IdeResult<String> {
|
||||
check_connection(proxy, url, &CancellationToken::new()).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn builds_for_every_mode() {
|
||||
for mode in [ProxyMode::None, ProxyMode::Auto, ProxyMode::Manual] {
|
||||
for kind in [ProxyKind::Http, ProxyKind::Socks] {
|
||||
let p = ProxySettings { mode, kind, host: "proxy".into(), port: 3128, ..Default::default() };
|
||||
assert!(build(&p).is_ok(), "{mode:?} {kind:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_proxy_receives_the_request_with_credentials() {
|
||||
let (port, proxy_server) = server();
|
||||
let proxy = ProxySettings { authenticate: true, login: "me".into(), password: "s3cret".into(), ..manual(port) };
|
||||
assert_eq!(get(&proxy, "http://example.invalid/ping").await.unwrap(), "200 OK");
|
||||
let head = proxy_server.join().unwrap();
|
||||
assert!(head.starts_with("GET http://example.invalid/ping HTTP/1.1"), "{head}");
|
||||
// base64("me:s3cret")
|
||||
assert!(head.to_ascii_lowercase().contains("proxy-authorization: basic bwu6cznjcmv0"), "{head}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_proxy_without_authentication_sends_no_credentials() {
|
||||
let (port, proxy_server) = server();
|
||||
let proxy = ProxySettings { login: "me".into(), password: "x".into(), ..manual(port) };
|
||||
get(&proxy, "http://example.invalid/").await.unwrap();
|
||||
assert!(!proxy_server.join().unwrap().to_ascii_lowercase().contains("proxy-authorization"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_proxy_hosts_and_no_proxy_mode_connect_directly() {
|
||||
// Nothing listens on the proxy port: a request through it would fail.
|
||||
let dead = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let (port, target) = server();
|
||||
let listed = ProxySettings { no_proxy: "example.com, 127.0.*".into(), ..manual(dead) };
|
||||
assert!(listed.bypasses("127.0.0.1"));
|
||||
get(&listed, &format!("http://127.0.0.1:{port}/direct")).await.unwrap();
|
||||
assert!(target.join().unwrap().starts_with("GET /direct HTTP/1.1"));
|
||||
|
||||
let (port, target) = server();
|
||||
let none = ProxySettings { mode: ProxyMode::None, ..manual(dead) };
|
||||
get(&none, &format!("http://127.0.0.1:{port}/none")).await.unwrap();
|
||||
assert!(target.join().unwrap().starts_with("GET /none HTTP/1.1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn check_reports_errors() {
|
||||
let dead = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let e = get(&manual(dead), "http://example.invalid/").await.unwrap_err();
|
||||
assert!(!e.message.is_empty());
|
||||
let e = get(&manual(0), "http://example.invalid/").await.unwrap_err();
|
||||
assert!(e.message.contains("port"), "{}", e.message);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Preparing (substitution, body includes) and executing requests.
|
||||
|
||||
use crate::client::describe;
|
||||
use crate::env::{Environments, Resolver};
|
||||
use crate::parse::{BodyPart, RawRequest};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
@@ -7,7 +8,6 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
/// Bodies above this are cut (the full size is still reported).
|
||||
@@ -98,29 +98,6 @@ pub fn prepare(
|
||||
})
|
||||
}
|
||||
|
||||
fn client() -> IdeResult<reqwest::Client> {
|
||||
static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
|
||||
CLIENT
|
||||
.get_or_init(|| {
|
||||
use rustls_platform_verifier::BuilderVerifierExt;
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let tls = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_platform_verifier()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_no_client_auth();
|
||||
reqwest::Client::builder()
|
||||
.tls_backend_preconfigured(tls)
|
||||
.connect_timeout(std::time::Duration::from_secs(30))
|
||||
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.map_err(|e| e.to_string())
|
||||
})
|
||||
.clone()
|
||||
.map_err(|e| IdeError::internal(format!("HTTP client: {e}")))
|
||||
}
|
||||
|
||||
fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
|
||||
if let Some(ct) = content_type {
|
||||
let ct = ct.to_ascii_lowercase();
|
||||
@@ -148,7 +125,7 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
|
||||
|
||||
/// Sends `req`; cancelled when `cancel` fires.
|
||||
pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult<HttpResponse> {
|
||||
let client = client()?;
|
||||
let client = crate::client::shared()?;
|
||||
let method = reqwest::Method::from_bytes(req.method.as_bytes())
|
||||
.map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?;
|
||||
let mut builder = client.request(method, &req.url);
|
||||
@@ -205,22 +182,6 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
|
||||
})
|
||||
}
|
||||
|
||||
/// reqwest errors with their causes ("error sending request: … connection refused").
|
||||
fn describe(e: &reqwest::Error) -> String {
|
||||
use std::error::Error;
|
||||
let mut msg = e.to_string();
|
||||
let mut source = e.source();
|
||||
while let Some(s) = source {
|
||||
let s_msg = s.to_string();
|
||||
if !msg.contains(&s_msg) {
|
||||
msg.push_str(": ");
|
||||
msg.push_str(&s_msg);
|
||||
}
|
||||
source = s.source();
|
||||
}
|
||||
msg
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//!
|
||||
//! [`parse`] splits a file into requests, [`env`] resolves `{{variables}}` from
|
||||
//! `http-client(.private).env.json`, [`exec`] sends a request (cancellable,
|
||||
//! timed) and [`history`] keeps the responses.
|
||||
//! timed) and [`history`] keeps the responses. [`client`] builds every HTTP client
|
||||
//! of the backend, with the proxy of System Settings › HTTP Proxy.
|
||||
|
||||
pub mod client;
|
||||
pub mod env;
|
||||
pub mod exec;
|
||||
pub mod history;
|
||||
|
||||
@@ -218,8 +218,17 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported(feature: &str) -> IdeError {
|
||||
IdeError::unavailable(format!("no running language server supports {feature}"))
|
||||
/// No target for `feature`: names the running servers that lack it, so the UI can
|
||||
/// tell "the server can't do this" from "no server is running" (the UI's
|
||||
/// `unavailableText` matches the "… doesn't support …" wording).
|
||||
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
|
||||
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
|
||||
if running.is_empty() {
|
||||
IdeError::unavailable(format!("no running language server supports {feature}"))
|
||||
} else {
|
||||
let servers = running.join(", ");
|
||||
IdeError::unavailable(format!("{servers} doesn't support {feature}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds per-server results: any success wins over errors; errors surface only
|
||||
@@ -830,7 +839,7 @@ impl LspManager {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let targets = self.ready_targets(&snap.servers, pred).await;
|
||||
if targets.is_empty() {
|
||||
return Err(unsupported(feature));
|
||||
return Err(unsupported(&snap.servers, feature));
|
||||
}
|
||||
Ok((snap, targets))
|
||||
}
|
||||
@@ -1183,7 +1192,7 @@ impl LspManager {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
|
||||
if targets.is_empty() {
|
||||
return Err(unsupported("workspace symbols"));
|
||||
return Err(unsupported(&servers, "workspace symbols"));
|
||||
}
|
||||
let requests = targets.iter().map(|t| {
|
||||
let cancel = &cancel;
|
||||
|
||||
@@ -520,6 +520,20 @@ async fn inline_completion_only_from_servers_that_advertise_it() {
|
||||
assert!(plain.requested("textDocument/inlineCompletion").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unsupported_feature_names_the_running_servers_that_lack_it() {
|
||||
let h = harness(&[("plain", incremental_caps()), ("other", json!({ "textDocumentSync": 2 }))]);
|
||||
let (doc, _) = h.open("a.mk", "let x = fo");
|
||||
for name in ["plain", "other"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let e = h.mgr.inline_completion(doc, Pos::new(0, 10), false, Default::default()).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert_eq!(e.message, "plain, other doesn't support inline completion");
|
||||
let e = h.mgr.type_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming).await.unwrap_err();
|
||||
assert_eq!(e.message, "plain, other doesn't support type hierarchy");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Saved SSH passwords / key passphrases of SSH configurations, in the app's
|
||||
//! data directory rather than the OS credential store (no system prompts).
|
||||
//! One JSON object, configuration id → secret; owner-only on Unix.
|
||||
//! Saved passwords (SSH passwords / key passphrases by configuration id, the HTTP
|
||||
//! proxy's), in the app's data directory rather than the OS credential store (no
|
||||
//! system prompts). One JSON object, key → secret; owner-only on Unix.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
@@ -35,14 +35,14 @@ impl SecretFile {
|
||||
if all.remove(key).is_some()
|
||||
&& let Err(e) = self.write(&all)
|
||||
{
|
||||
tracing::warn!("saved SSH passwords: {}", e.message);
|
||||
tracing::warn!("{}", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&self) -> BTreeMap<String, String> {
|
||||
match std::fs::read(&self.path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
tracing::warn!("saved SSH passwords: {}: {e}", self.path.display());
|
||||
tracing::warn!("saved passwords: {}: {e}", self.path.display());
|
||||
BTreeMap::new()
|
||||
}),
|
||||
Err(_) => BTreeMap::new(),
|
||||
@@ -50,7 +50,7 @@ impl SecretFile {
|
||||
}
|
||||
|
||||
fn write(&self, all: &BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let err = |e: std::io::Error| IdeError::unavailable(format!("saved SSH passwords: {e}"));
|
||||
let err = |e: std::io::Error| IdeError::unavailable(format!("saved passwords: {}: {e}", self.path.display()));
|
||||
if let Some(dir) = self.path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(err)?;
|
||||
}
|
||||
|
||||
@@ -198,6 +198,8 @@ impl Http {
|
||||
let mut cmd = Command::new(&self.curl);
|
||||
own_group(ide_core::process::prepare(&mut cmd));
|
||||
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
|
||||
// System Settings › HTTP Proxy (a manual proxy comes in through `prepare`'s environment).
|
||||
cmd.args(ide_core::proxy_settings::proxy().curl_args(url));
|
||||
if self.https_only {
|
||||
cmd.args(["--proto", "=https", "--proto-redir", "=https"]);
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn settings_get(window: Window, state: State<'_, AppState>) -> Settings {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn settings_get_global(state: State<'_, AppState>) -> Settings {
|
||||
state.global_settings.effective()
|
||||
state.host.with_proxy_password(state.global_settings.effective())
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
@@ -196,11 +196,9 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P
|
||||
tauri::async_runtime::spawn(async move { lsp.reconfigure().await });
|
||||
}
|
||||
crate::commands::ssh::apply_ssh_settings(&state);
|
||||
state.host.apply_proxy();
|
||||
state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() });
|
||||
let settings = match state.project(window.label()) {
|
||||
Ok(p) => p.settings.effective(),
|
||||
Err(_) => state.global_settings.effective(),
|
||||
};
|
||||
let settings = ide_host::ops::project::settings(&state.host, window.label());
|
||||
Ok(SettingsImport { settings, storage })
|
||||
}
|
||||
|
||||
|
||||
@@ -76,3 +76,11 @@ pub fn http_history_get(window: Window, state: State<'_, AppState>, id: String)
|
||||
pub fn http_history_clear(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
|
||||
state.project(window.label())?.http_history.clear()
|
||||
}
|
||||
|
||||
/// System Settings › HTTP Proxy › Check connection: GETs `url` through `proxy` as
|
||||
/// edited (not yet applied); the response status, or why there was none.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn proxy_check_connection(proxy: ide_core::settings::ProxySettings, url: String) -> IdeResult<String> {
|
||||
ide_http::client::check_connection(&proxy, &url, &ide_core::CancellationToken::new()).await
|
||||
}
|
||||
@@ -394,6 +394,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
http::http_history,
|
||||
http::http_history_get,
|
||||
http::http_history_clear,
|
||||
http::proxy_check_connection,
|
||||
db::db_sources,
|
||||
db::db_save_sources,
|
||||
db::db_set_password,
|
||||
|
||||
@@ -295,7 +295,8 @@ fn updater(app: &AppHandle) -> IdeResult<Option<tauri_plugin_updater::Updater>>
|
||||
return Ok(None);
|
||||
}
|
||||
let env = update_endpoint_env();
|
||||
let mut builder = app.updater_builder();
|
||||
let proxy = ide_core::proxy_settings::proxy();
|
||||
let mut builder = app.updater_builder().configure_client(move |b| ide_http::client::with_proxy(b, &proxy));
|
||||
if let Some(url) = env {
|
||||
let url = url.parse().map_err(|e| IdeError::invalid(format!("OPENIDEA_UPDATE_ENDPOINT: {e}")))?;
|
||||
builder = builder.endpoints(vec![url]).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
|
||||
@@ -850,6 +850,11 @@ export const commands = {
|
||||
httpHistory: () => typedError<HttpHistoryEntry[], IdeError>(__TAURI_INVOKE("http_history")),
|
||||
httpHistoryGet: (id: string) => typedError<HttpExchange, IdeError>(__TAURI_INVOKE("http_history_get", { id })),
|
||||
httpHistoryClear: () => typedError<null, IdeError>(__TAURI_INVOKE("http_history_clear")),
|
||||
/**
|
||||
* System Settings › HTTP Proxy › Check connection: GETs `url` through `proxy` as
|
||||
* edited (not yet applied); the response status, or why there was none.
|
||||
*/
|
||||
proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError<string, IdeError>(__TAURI_INVOKE("proxy_check_connection", { proxy, url })),
|
||||
dbSources: () => typedError<DataSource[], IdeError>(__TAURI_INVOKE("db_sources")),
|
||||
dbSaveSources: (sources: DataSource[]) => typedError<null, IdeError>(__TAURI_INVOKE("db_save_sources", { sources })),
|
||||
/**
|
||||
@@ -1174,6 +1179,15 @@ export type AgentRegistry = {
|
||||
warning: string | null,
|
||||
};
|
||||
|
||||
/** An API request the agent is about to retry. */
|
||||
export type AgentRetry = {
|
||||
attempt: number,
|
||||
maxRetries: number | null,
|
||||
/** When the next attempt starts (ms since the epoch). */
|
||||
retryAtMs: number | null,
|
||||
error: string | null,
|
||||
};
|
||||
|
||||
/** Where an agent comes from. */
|
||||
export type AgentSource = { kind: "builtin" } |
|
||||
/** Defined by the user in `<config>/agents/<id>.toml`. */
|
||||
@@ -1233,6 +1247,11 @@ export type AgentTask = {
|
||||
capabilities?: AgentCapabilities,
|
||||
/** When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said. */
|
||||
resetsMs?: number | null,
|
||||
/**
|
||||
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
|
||||
* by its next output or any status change.
|
||||
*/
|
||||
retry?: AgentRetry | null,
|
||||
};
|
||||
|
||||
export type AgentToolDiff = {
|
||||
@@ -4511,6 +4530,30 @@ export type ProjectStructureSettings = {
|
||||
excludeFiles?: string,
|
||||
};
|
||||
|
||||
export type ProxyKind = "http" | "socks";
|
||||
|
||||
export type ProxyMode =
|
||||
/** Every connection goes direct. */
|
||||
"none" |
|
||||
/** The system's proxy: `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` of the environment. */
|
||||
"auto" |
|
||||
/** The proxy configured here. */
|
||||
"manual";
|
||||
|
||||
export type ProxySettings = {
|
||||
mode?: ProxyMode,
|
||||
kind?: ProxyKind,
|
||||
host?: string,
|
||||
port?: number,
|
||||
/** Hosts reached directly, comma-separated; `*` matches any characters (`*.example.com`, `192.168.*`). */
|
||||
noProxy?: string,
|
||||
/** Send `login` / `password` to the proxy. */
|
||||
authenticate?: boolean,
|
||||
login?: string,
|
||||
/** Kept in the saved passwords rather than `settings.toml`; filled in when settings are read. */
|
||||
password?: string,
|
||||
};
|
||||
|
||||
export type PruneTarget = "containers" |
|
||||
/** Dangling images only. */
|
||||
"images" |
|
||||
@@ -5139,6 +5182,8 @@ export type Settings_Deserialize = {
|
||||
*/
|
||||
customKeymaps?: { [key in string]: CustomKeymap },
|
||||
notifications?: NotificationSettings,
|
||||
/** System Settings › HTTP Proxy (global only). */
|
||||
proxy?: ProxySettings,
|
||||
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
|
||||
languages?: LanguagesSettings,
|
||||
/** Project Structure: source / test / resource / excluded folders (project-relative). */
|
||||
@@ -5192,6 +5237,8 @@ export type Settings_Serialize = {
|
||||
*/
|
||||
customKeymaps: { [key in string]: CustomKeymap },
|
||||
notifications: NotificationSettings,
|
||||
/** System Settings › HTTP Proxy (global only). */
|
||||
proxy: ProxySettings,
|
||||
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
|
||||
languages: LanguagesSettings,
|
||||
/** Project Structure: source / test / resource / excluded folders (project-relative). */
|
||||
|
||||
@@ -21,6 +21,7 @@ const {
|
||||
ghostText,
|
||||
inlineCompletionExtension,
|
||||
nextWord,
|
||||
registerInlineCompletionActions,
|
||||
requestInline,
|
||||
toSuggestions,
|
||||
} = await import("./inlineCompletion");
|
||||
@@ -136,3 +137,49 @@ describe("inline completion", () => {
|
||||
expect(nextWord(" ")).toBe(" ");
|
||||
});
|
||||
});
|
||||
|
||||
describe("inline completion without a provider", () => {
|
||||
const unavailable = (message: string) => ({
|
||||
status: "error" as const,
|
||||
error: { kind: "unavailable" as const, message },
|
||||
});
|
||||
const hintText = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
|
||||
|
||||
async function invoke(view: EditorView) {
|
||||
const { useEditorRegistry } = await import("@/editor/api");
|
||||
const { getAction } = await import("@/platform/actions");
|
||||
useEditorRegistry.setState({ active: { view, ctx: view.state.facet(lspDoc)! } as never });
|
||||
const off = registerInlineCompletionActions();
|
||||
void getAction("editor.inlineCompletion.trigger")!.run({ ctx: {} } as never);
|
||||
off();
|
||||
}
|
||||
|
||||
it.each([
|
||||
[
|
||||
"names the running server that lacks it",
|
||||
"jdtls doesn't support inline completion",
|
||||
"jdtls doesn't support inline completion",
|
||||
],
|
||||
[
|
||||
"says no server runs when none does",
|
||||
"no running language server supports inline completion",
|
||||
"No language server available",
|
||||
],
|
||||
])("on explicit invocation %s", async (_, message, shown) => {
|
||||
const view = editor("String s = ");
|
||||
ipc.lspInlineCompletion.mockResolvedValueOnce(unavailable(message));
|
||||
await invoke(view);
|
||||
await vi.waitFor(() => expect(hintText()).toBe(shown));
|
||||
});
|
||||
|
||||
it("stays silent while typing", async () => {
|
||||
const view = editor("String s = ");
|
||||
ipc.lspInlineCompletion.mockResolvedValue(unavailable("jdtls doesn't support inline completion"));
|
||||
expect(await requestInline(view, true)).toBe(false);
|
||||
view.dispatch({ changes: { from: 11, insert: "x" }, userEvent: "input.type" });
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
expect(hintText()).toBeNull();
|
||||
expect(ghostDom(view)).toBeNull();
|
||||
ipc.lspInlineCompletion.mockReset();
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type Command,
|
||||
type InlineCompletionItem,
|
||||
type RequestId,
|
||||
unavailableText,
|
||||
} from "@/platform/ipc";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
@@ -312,7 +313,7 @@ export function registerInlineCompletionActions(): () => void {
|
||||
try {
|
||||
if (!(await requestInline(v, false))) showHint(v, "No inline suggestions");
|
||||
} catch (e) {
|
||||
showHint(v, isUnavailable(e) ? "No language server provides inline completion" : String(e));
|
||||
showHint(v, isUnavailable(e) ? unavailableText(e) : String(e));
|
||||
}
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -8,7 +8,8 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
return { ...actual, isTauri: () => true };
|
||||
});
|
||||
|
||||
const { lspRequest } = await import("./lsp");
|
||||
const { lspRequest, reportLspError } = await import("./lsp");
|
||||
const { IpcError } = await import("@/platform/ipc");
|
||||
|
||||
describe("lspRequest", () => {
|
||||
it("waits until open editors' edits reached the backend", async () => {
|
||||
@@ -27,3 +28,27 @@ describe("lspRequest", () => {
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("reportLspError", () => {
|
||||
const unavailable = (message: string) => new IpcError({ kind: "unavailable", message });
|
||||
const hintText = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
|
||||
|
||||
it.each([
|
||||
["jdtls doesn't support type hierarchy", "jdtls doesn't support type hierarchy"],
|
||||
["pyright, ruff doesn't support code lens", "pyright, ruff doesn't support code lens"],
|
||||
["no running language server supports rename", "No language server available"],
|
||||
["jdtls is not running", "No language server available"],
|
||||
])("explicit %s → %s", (message, shown) => {
|
||||
const view = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
|
||||
reportLspError(view, unavailable(message), true);
|
||||
expect(hintText()).toBe(shown);
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("stays silent for background requests", () => {
|
||||
const view = new EditorView({ state: EditorState.create({ doc: "x" }), parent: document.body });
|
||||
reportLspError(view, unavailable("jdtls doesn't support inlay hints"), false);
|
||||
expect(hintText()).toBeNull();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Facet } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { whenAllSynced, type EditorDocContext } from "@/editor/api";
|
||||
import { IpcError, call, isCancelled, isTauri } from "@/platform/ipc";
|
||||
import { IpcError, call, isCancelled, isTauri, unavailableText } from "@/platform/ipc";
|
||||
import type { IdeError } from "@/bindings";
|
||||
import { showHint } from "./hint";
|
||||
|
||||
@@ -44,7 +44,8 @@ export const NO_SERVER = "No language server available";
|
||||
|
||||
/**
|
||||
* Error policy: background requests fail silently; explicit actions show a
|
||||
* small hint at the caret ("No language server available" for missing servers).
|
||||
* small hint at the caret ("No language server available" for missing servers,
|
||||
* "jdtls doesn't support X" when the running server lacks the feature).
|
||||
*/
|
||||
export function reportLspError(view: EditorView | null, e: unknown, explicit: boolean) {
|
||||
if (isCancelled(e)) return;
|
||||
@@ -52,7 +53,7 @@ export function reportLspError(view: EditorView | null, e: unknown, explicit: bo
|
||||
if (!isUnavailable(e)) console.debug("[lsp]", e);
|
||||
return;
|
||||
}
|
||||
showHint(view, isUnavailable(e) ? NO_SERVER : e instanceof Error ? e.message : String(e));
|
||||
showHint(view, isUnavailable(e) ? unavailableText(e, NO_SERVER) : e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
/** Runs `fn` once `ms` after the last call; `cancel()` drops a pending run. */
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
|
||||
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
|
||||
import { call, commands, isCancelled, isTauri, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { basename } from "@/platform/project";
|
||||
import { editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
|
||||
@@ -482,7 +482,12 @@ export async function safeDelete(view: EditorView): Promise<void> {
|
||||
applyDeletion(view, docBefore, target, comments);
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return;
|
||||
showHint(view, isUnavailable(e) ? cannotPerform("No language server is available") : cannotPerform(errorText(e)));
|
||||
showHint(
|
||||
view,
|
||||
isUnavailable(e)
|
||||
? cannotPerform(unavailableText(e, "No language server is available"))
|
||||
: cannotPerform(errorText(e)),
|
||||
);
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
|
||||
@@ -437,6 +437,10 @@
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.retrying {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.composerArea {
|
||||
flex: none;
|
||||
display: flex;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import type { AgentChange, AgentEntry, AgentTask, AgentUsage } from "@/bindings";
|
||||
import type { AgentChange, AgentEntry, AgentRetry, AgentTask, AgentUsage } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
import { useTx, tx } from "@/platform/i18n";
|
||||
import { TaskStatusIcon } from "./AgentsView";
|
||||
import { Composer } from "./Composer";
|
||||
import { canSend, emptyDraft, usageLabel, workTime } from "./composerModel";
|
||||
import { canSend, emptyDraft, retryParts, usageLabel, workTime } from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { findRanges, formatDuration, formatSentAt } from "./conversation";
|
||||
import { Markdown } from "./Markdown";
|
||||
@@ -381,7 +381,11 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
|
||||
{!subagent && (task.status === "running" || task.status === "starting") && !waiting && (
|
||||
<div className={styles.working}>
|
||||
<Spinner size={12} />
|
||||
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
|
||||
{task.retry ? (
|
||||
<Retrying retry={task.retry} />
|
||||
) : (
|
||||
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
|
||||
)}
|
||||
{lastUser?.sentMs != null && !lastUser.doneMs && <Elapsed since={lastUser.sentMs} />}
|
||||
</div>
|
||||
)}
|
||||
@@ -393,6 +397,20 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
|
||||
type UserEntry = Extract<AgentEntry, { type: "user" }>;
|
||||
|
||||
/** Time since `since`, ticking every second. */
|
||||
/** The agent lost its API connection (or was refused) and retries on its own. */
|
||||
function Retrying({ retry }: { retry: AgentRetry }) {
|
||||
const tx = useTx();
|
||||
const now = useNow(1000);
|
||||
const { attempt, wait } = retryParts(retry, now);
|
||||
return (
|
||||
<span className={styles.retrying} title={retry.error ?? undefined}>
|
||||
{wait > 0
|
||||
? tx`API request failed, retrying in ${wait}s (attempt ${attempt})`
|
||||
: tx`API request failed, retrying (attempt ${attempt})`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Elapsed({ since }: { since: number }) {
|
||||
const now = useNow(1000);
|
||||
return <span className={styles.muted}>{formatDuration(now - since)}</span>;
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
nextValue,
|
||||
recall,
|
||||
toPrompt,
|
||||
retryParts,
|
||||
usageLabel,
|
||||
workTime,
|
||||
} from "./composerModel";
|
||||
@@ -264,3 +265,11 @@ describe("turns", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("retryParts", () => {
|
||||
it("counts down to the next attempt and shows the limit when known", () => {
|
||||
const retry = { attempt: 3, maxRetries: 10, retryAtMs: 5_400, error: "Connection error." };
|
||||
expect(retryParts(retry, 1_000)).toEqual({ attempt: "3/10", wait: 5 });
|
||||
expect(retryParts({ ...retry, maxRetries: null }, 9_000)).toEqual({ attempt: "3", wait: 0 });
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,13 @@
|
||||
/** Pure composer helpers: `@` / `/` completion, attachments, history recall, settings. */
|
||||
import type { AgentCommand, AgentConfigOption, AgentEntry, AgentImage, AgentPrompt, AgentUsage } from "@/bindings";
|
||||
import type {
|
||||
AgentCommand,
|
||||
AgentConfigOption,
|
||||
AgentEntry,
|
||||
AgentImage,
|
||||
AgentPrompt,
|
||||
AgentRetry,
|
||||
AgentUsage,
|
||||
} from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export interface FileRef {
|
||||
@@ -131,6 +139,14 @@ export function nextValue(option: AgentConfigOption, current = option.current):
|
||||
}
|
||||
|
||||
/** "12%" of the context window and a tooltip with the numbers. */
|
||||
/** A pending API retry: "3/10" (or "3" when the agent gives no limit) and the seconds left. */
|
||||
export function retryParts(r: AgentRetry, now: number): { attempt: string; wait: number } {
|
||||
return {
|
||||
attempt: r.maxRetries != null ? `${r.attempt}/${r.maxRetries}` : String(r.attempt),
|
||||
wait: r.retryAtMs == null ? 0 : Math.max(0, Math.ceil((r.retryAtMs - now) / 1000)),
|
||||
};
|
||||
}
|
||||
|
||||
export function usageLabel(u: AgentUsage): { short: string; detail: string } {
|
||||
const pct = Math.min(100, Math.round((u.used / u.size) * 100));
|
||||
return { short: `${pct}%`, detail: tx`${tokens(u.used)} / ${tokens(u.size)} tokens` };
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { EditorView } from "@codemirror/view";
|
||||
import { activeEditor, editorsFor } from "@/editor/api";
|
||||
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { IpcError, call, commands, isCancelled, isTauri } from "@/platform/ipc";
|
||||
import { IpcError, call, commands, isCancelled, isTauri, unavailableText } from "@/platform/ipc";
|
||||
import type { IdeError } from "@/bindings";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
|
||||
@@ -36,7 +36,7 @@ export function hint(text: string, tone: "info" | "warning" | "error" = "info")
|
||||
export function reportError(e: unknown) {
|
||||
if (isCancelled(e)) return;
|
||||
hint(
|
||||
isUnavailable(e) ? "No language server available" : e instanceof Error ? e.message : String(e),
|
||||
isUnavailable(e) ? unavailableText(e) : e instanceof Error ? e.message : String(e),
|
||||
isUnavailable(e) ? "info" : "error",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { EDITOR_EXTRA_DEFAULTS, validateEditorExtras, type EditorExtras } from "@/platform/editorSettings";
|
||||
import { DEFAULT_WORKFLOW, validateWorkflow, type WorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { DEFAULT_INSPECTIONS, validateInspections, type InspectionSettingsValid } from "@/platform/inspections";
|
||||
import { DEFAULT_PROXY, validateProxy, type ProxySettingsValid } from "@/platform/proxySettings";
|
||||
import {
|
||||
DEFAULT_APPEARANCE_EXTRAS,
|
||||
DEFAULT_GENERAL_EXTRAS,
|
||||
@@ -77,6 +78,8 @@ export interface ValidSettings extends WorkflowSettings {
|
||||
keymapOverrides: Record<string, string[]>;
|
||||
customKeymaps: Record<string, CustomKeymapSettings>;
|
||||
notifications: NotificationsValid;
|
||||
/** System Settings › HTTP Proxy (global). */
|
||||
proxy: ProxySettingsValid;
|
||||
languages: LanguagesValid;
|
||||
projectStructure: ProjectStructureValid;
|
||||
inspections: InspectionSettingsValid;
|
||||
@@ -143,6 +146,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
keymapOverrides: {},
|
||||
customKeymaps: {},
|
||||
notifications: DEFAULT_NOTIFICATIONS,
|
||||
proxy: DEFAULT_PROXY,
|
||||
languages: DEFAULT_LANGUAGES,
|
||||
projectStructure: DEFAULT_PROJECT_STRUCTURE,
|
||||
inspections: DEFAULT_INSPECTIONS,
|
||||
@@ -245,6 +249,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
keymapOverrides: overrides,
|
||||
customKeymaps,
|
||||
notifications: validateNotifications(root.notifications),
|
||||
proxy: validateProxy(root.proxy),
|
||||
languages: validateLanguages(root.languages),
|
||||
projectStructure: validateProjectStructure(root.projectStructure),
|
||||
inspections: validateInspections(root.inspections),
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.modes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.radio {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 28px;
|
||||
}
|
||||
.radio input {
|
||||
margin: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.disabled {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.hint {
|
||||
padding-left: 20px;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
/* Manual configuration, indented under its radio button. */
|
||||
.manual {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 20px;
|
||||
}
|
||||
.kinds {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
.hostRow {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 24px;
|
||||
}
|
||||
.host {
|
||||
width: 220px;
|
||||
}
|
||||
.port {
|
||||
width: 64px;
|
||||
}
|
||||
.wide {
|
||||
width: 360px;
|
||||
}
|
||||
.toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
}
|
||||
.auth {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 20px;
|
||||
}
|
||||
.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
.ok {
|
||||
color: var(--success, var(--fg-muted));
|
||||
}
|
||||
|
||||
.check {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.popup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
max-width: 480px;
|
||||
}
|
||||
.urlRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.result {
|
||||
min-height: 1lh;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Appearance & Behavior pages, laid out like IntelliJ IDEA / PyCharm:
|
||||
* Appearance, System Settings (+ Language and Region, Date Formats) and
|
||||
* Appearance, System Settings (+ Language and Region, Date Formats, HTTP Proxy) and
|
||||
* Notifications. Every option is wired (see `appearanceRuntime`, workbench
|
||||
* theme / tool windows / notifications, app title / windows, `platform/dateFormat`).
|
||||
*/
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "../model/behaviorSchema";
|
||||
import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
|
||||
import type { PageSpec } from "./spec";
|
||||
import { HTTP_PROXY_PAGE } from "./httpProxy";
|
||||
import styles from "./Behavior.module.css";
|
||||
import { tx, useT } from "@/platform/i18n";
|
||||
|
||||
@@ -673,6 +674,7 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
HTTP_PROXY_PAGE,
|
||||
{
|
||||
id: "notifications",
|
||||
title: "Notifications",
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Appearance & Behavior › System Settings › HTTP Proxy: how the IDE's own
|
||||
* connections (HTTP Client, tool / JDK / agent downloads, update checks) reach
|
||||
* the network. A manual proxy also reaches child processes as `HTTP_PROXY`.
|
||||
*/
|
||||
import { useId, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import {
|
||||
PROXY_PORT_LIMITS,
|
||||
proxyProblem,
|
||||
withProxyKind,
|
||||
type ProxyKindValid,
|
||||
type ProxyModeValid,
|
||||
type ProxySettingsValid,
|
||||
} from "@/platform/proxySettings";
|
||||
import { Button, Checkbox, Input, Popup, T } from "@/ui";
|
||||
import { NumberInput, Row, SearchLabel } from "../components/Form";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { stage } from "../model/staging";
|
||||
import type { PageSpec } from "./spec";
|
||||
import styles from "./HttpProxy.module.css";
|
||||
|
||||
const MODES: Array<{ value: ProxyModeValid; label: string; hint?: string }> = [
|
||||
{ value: "none", label: "No proxy" },
|
||||
{
|
||||
value: "auto",
|
||||
label: "Auto-detect proxy settings",
|
||||
hint: "Uses the system proxy: the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.",
|
||||
},
|
||||
{ value: "manual", label: "Manual proxy configuration" },
|
||||
];
|
||||
|
||||
const KINDS: Array<{ value: ProxyKindValid; label: string }> = [
|
||||
{ value: "http", label: "HTTP" },
|
||||
{ value: "socks", label: "SOCKS" },
|
||||
];
|
||||
|
||||
/** The staged proxy settings and a setter per field (each written as its own key). */
|
||||
function useProxy(): [ProxySettingsValid, (patch: Partial<ProxySettingsValid>) => void] {
|
||||
const [proxy] = useSetting<ProxySettingsValid>("proxy", "global");
|
||||
const { pageId } = usePageContext();
|
||||
const update = (patch: Partial<ProxySettingsValid>) => {
|
||||
for (const [field, value] of Object.entries(patch)) stage(pageId, "global", `proxy.${field}`, value);
|
||||
};
|
||||
return [proxy, update];
|
||||
}
|
||||
|
||||
function Radio({
|
||||
name,
|
||||
checked,
|
||||
onSelect,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
name: string;
|
||||
checked: boolean;
|
||||
onSelect: () => void;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<label className={clsx(styles.radio, disabled && styles.disabled)}>
|
||||
<input type="radio" name={name} checked={checked} disabled={disabled} onChange={onSelect} />
|
||||
<SearchLabel text={label} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function ProxyOptions() {
|
||||
const [proxy, update] = useProxy();
|
||||
const name = useId();
|
||||
const kindName = useId();
|
||||
const ids = {
|
||||
host: useId(),
|
||||
port: useId(),
|
||||
noProxy: useId(),
|
||||
login: useId(),
|
||||
password: useId(),
|
||||
};
|
||||
const manual = proxy.mode === "manual";
|
||||
const auth = manual && proxy.authenticate;
|
||||
const problem = proxyProblem(proxy);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.modes} role="radiogroup" aria-label={tx("Proxy")}>
|
||||
{MODES.map((m) => (
|
||||
<div key={m.value}>
|
||||
<Radio
|
||||
name={name}
|
||||
checked={proxy.mode === m.value}
|
||||
onSelect={() => update({ mode: m.value })}
|
||||
label={m.label}
|
||||
/>
|
||||
{m.hint && (
|
||||
<div className={styles.hint}>
|
||||
<T>{m.hint}</T>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.manual}>
|
||||
<div className={styles.kinds} role="radiogroup" aria-label={tx("Proxy type")}>
|
||||
{KINDS.map((k) => (
|
||||
<Radio
|
||||
key={k.value}
|
||||
name={kindName}
|
||||
checked={proxy.kind === k.value}
|
||||
disabled={!manual}
|
||||
onSelect={() => update(withProxyKind(proxy, k.value))}
|
||||
label={k.label}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.hostRow}>
|
||||
<Row label="Host name" htmlFor={ids.host}>
|
||||
<Input
|
||||
id={ids.host}
|
||||
className={styles.host}
|
||||
disabled={!manual}
|
||||
value={proxy.host}
|
||||
onChange={(e) => update({ host: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Port number" htmlFor={ids.port}>
|
||||
{manual ? (
|
||||
<NumberInput
|
||||
id={ids.port}
|
||||
value={proxy.port}
|
||||
onChange={(port) => update({ port })}
|
||||
{...PROXY_PORT_LIMITS}
|
||||
integer
|
||||
aria-label="Port number"
|
||||
/>
|
||||
) : (
|
||||
<Input id={ids.port} className={styles.port} value={String(proxy.port)} disabled readOnly />
|
||||
)}
|
||||
</Row>
|
||||
</div>
|
||||
<Row
|
||||
label="No proxy for"
|
||||
htmlFor={ids.noProxy}
|
||||
hint="Comma-separated host names; * matches any characters, e.g. *.example.com, 192.168.*"
|
||||
>
|
||||
<Input
|
||||
id={ids.noProxy}
|
||||
className={styles.wide}
|
||||
disabled={!manual}
|
||||
value={proxy.noProxy}
|
||||
onChange={(e) => update({ noProxy: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<div className={styles.toggle}>
|
||||
<Checkbox
|
||||
checked={proxy.authenticate}
|
||||
disabled={!manual}
|
||||
onChange={(authenticate) => update({ authenticate })}
|
||||
label={<SearchLabel text="Proxy authentication" />}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.auth}>
|
||||
<Row label="Login" htmlFor={ids.login}>
|
||||
<Input
|
||||
id={ids.login}
|
||||
className={styles.host}
|
||||
disabled={!auth}
|
||||
value={proxy.login}
|
||||
onChange={(e) => update({ login: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Password" htmlFor={ids.password}>
|
||||
<Input
|
||||
id={ids.password}
|
||||
type="password"
|
||||
className={styles.host}
|
||||
disabled={!auth}
|
||||
value={proxy.password}
|
||||
onChange={(e) => update({ password: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
{problem && (
|
||||
<div className={styles.error} role="alert">
|
||||
<T>{problem}</T>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<CheckConnection proxy={proxy} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type CheckState = { status: "idle" | "running" } | { status: "ok" | "failed"; text: string };
|
||||
|
||||
/** Check connection…: asks for a URL and GETs it with the settings as edited. */
|
||||
function CheckConnection({ proxy }: { proxy: ProxySettingsValid }) {
|
||||
const t = useTx();
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const urlId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [url, setUrl] = useState("http://");
|
||||
const [state, setState] = useState<CheckState>({ status: "idle" });
|
||||
const check = async () => {
|
||||
setState({ status: "running" });
|
||||
try {
|
||||
const status = await call(commands.proxyCheckConnection(proxy, url));
|
||||
setState({ status: "ok", text: t`Connection successful: ${status}` });
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
setState({
|
||||
status: "failed",
|
||||
text: t`Problem with connection: ${message}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
const running = state.status === "running";
|
||||
return (
|
||||
<div className={styles.check}>
|
||||
<Button
|
||||
ref={anchor}
|
||||
size="small"
|
||||
disabled={!isTauri() || !!proxyProblem(proxy)}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
<T>Check connection…</T>
|
||||
</Button>
|
||||
<Popup
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
anchor={anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
aria-label="Check connection"
|
||||
>
|
||||
<form
|
||||
className={styles.popup}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!running && url.trim()) void check();
|
||||
}}
|
||||
>
|
||||
<label htmlFor={urlId}>
|
||||
<T>Enter any URL to check connection to:</T>
|
||||
</label>
|
||||
<span className={styles.urlRow}>
|
||||
<Input id={urlId} autoFocus className={styles.wide} value={url} onChange={(e) => setUrl(e.target.value)} />
|
||||
<Button size="small" type="submit" disabled={running || !url.trim()}>
|
||||
<T>Check</T>
|
||||
</Button>
|
||||
</span>
|
||||
<span
|
||||
role="status"
|
||||
className={clsx(
|
||||
styles.result,
|
||||
state.status === "ok" && styles.ok,
|
||||
state.status === "failed" && styles.error,
|
||||
)}
|
||||
>
|
||||
{state.status === "ok" || state.status === "failed" ? state.text : running ? t("Connecting…") : ""}
|
||||
</span>
|
||||
</form>
|
||||
</Popup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const HTTP_PROXY_PAGE: PageSpec = {
|
||||
id: "general.httpProxy",
|
||||
title: "HTTP Proxy",
|
||||
order: 2,
|
||||
keywords: ["proxy", "network", "socks", "http_proxy", "no_proxy", "connection"],
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Manual proxy configuration",
|
||||
keywords: [
|
||||
"No proxy",
|
||||
"Auto-detect proxy settings",
|
||||
"Host name",
|
||||
"Port number",
|
||||
"No proxy for",
|
||||
"Proxy authentication",
|
||||
"Login",
|
||||
"Password",
|
||||
"Check connection…",
|
||||
],
|
||||
component: ProxyOptions,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -182,19 +182,100 @@
|
||||
.noHighlight :global(.cm-changedText) {
|
||||
background: none !important;
|
||||
}
|
||||
.unsynced :global(.cm-mergeView) {
|
||||
/* Side-by-side without alignment (IDEA's default): each pane scrolls itself. */
|
||||
.unaligned :global(.cm-mergeView) {
|
||||
overflow: hidden;
|
||||
}
|
||||
.unsynced :global(.cm-mergeViewEditors) {
|
||||
.unaligned :global(.cm-mergeViewEditors) {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
.unsynced :global(.cm-mergeViewEditor) {
|
||||
.unaligned :global(.cm-mergeViewEditor) {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.unsynced :global(.cm-mergeViewEditor > .cm-editor) {
|
||||
height: 100%;
|
||||
/* Overrides MergeView's base theme, which leaves scrolling to the outer view. */
|
||||
.unaligned :global(.cm-mergeViewEditor > .cm-editor),
|
||||
.unaligned :global(.cm-mergeViewEditor > .cm-editor > .cm-scroller) {
|
||||
height: 100% !important;
|
||||
}
|
||||
.unaligned :global(.cm-mergeViewEditor > .cm-editor > .cm-scroller) {
|
||||
overflow: auto !important;
|
||||
}
|
||||
.host :global(.cm-diffDivider) {
|
||||
position: relative;
|
||||
flex: none;
|
||||
width: 30px;
|
||||
overflow: hidden;
|
||||
background: var(--bg-app);
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.host :global(.cm-diffDivider svg) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
/* Opaque mixes of the line backgrounds (cm.ts), so bands and their midlines read as one shape. */
|
||||
.host :global(.cm-diffBand-inserted) {
|
||||
--band: color-mix(in srgb, var(--success) 26%, var(--bg-app));
|
||||
}
|
||||
.host :global(.cm-diffBand-deleted) {
|
||||
--band: color-mix(in srgb, var(--danger) 26%, var(--bg-app));
|
||||
}
|
||||
.host :global(.cm-diffBand-modified) {
|
||||
--band: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
|
||||
}
|
||||
.host :global(.cm-diffBand:not(.cm-diffBand-modified)) {
|
||||
fill: var(--band);
|
||||
}
|
||||
.host :global(.cm-diffBandLine) {
|
||||
fill: none;
|
||||
stroke: var(--band);
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.host :global(.cm-diffBandStopA) {
|
||||
stop-color: color-mix(in srgb, var(--gutter-deleted) 20%, var(--bg-app));
|
||||
}
|
||||
.host :global(.cm-diffBandStopB) {
|
||||
stop-color: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
|
||||
}
|
||||
.host :global(.cm-diffDivider button.cm-diffArrow) {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small);
|
||||
background: none;
|
||||
color: var(--fg-subtle);
|
||||
cursor: pointer;
|
||||
}
|
||||
.host :global(.cm-diffDivider button.cm-diffArrow-a-to-b) {
|
||||
left: 1px;
|
||||
}
|
||||
.host :global(.cm-diffDivider button.cm-diffArrow-b-to-a) {
|
||||
right: 1px;
|
||||
}
|
||||
.host :global(.cm-diffDivider button.cm-diffArrow:hover) {
|
||||
color: var(--fg-strong);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
/* Where the other pane has lines this one lacks. */
|
||||
.host :global(.cm-diffGap-inserted) {
|
||||
box-shadow: inset 0 1px 0 var(--success);
|
||||
}
|
||||
.host :global(.cm-diffGap-deleted) {
|
||||
box-shadow: inset 0 1px 0 var(--danger);
|
||||
}
|
||||
.host :global(.cm-diffGap-inserted.cm-diffGapEnd) {
|
||||
box-shadow: inset 0 -1px 0 var(--success);
|
||||
}
|
||||
.host :global(.cm-diffGap-deleted.cm-diffGapEnd) {
|
||||
box-shadow: inset 0 -1px 0 var(--danger);
|
||||
}
|
||||
|
||||
/* Review comments under diff lines (pull requests). */
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
type DiffSide,
|
||||
} from "./diffInput";
|
||||
import { diffAnnotations } from "./diffAnnotations";
|
||||
import { UnalignedPanes } from "./diffScroll";
|
||||
import { groupOf } from "./changes";
|
||||
import { inclusionGutter } from "./hunkInclusion";
|
||||
import { hunksOverlapping } from "./hunks";
|
||||
@@ -65,6 +66,8 @@ interface Views {
|
||||
b: EditorView;
|
||||
a: EditorView | null;
|
||||
merge: MergeView | null;
|
||||
/** Unpadded side-by-side panes with synchronized scrolling (IDEA). */
|
||||
panes: UnalignedPanes | null;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
@@ -227,18 +230,23 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
const editableB = !!attached?.b && !attached.b.readOnly;
|
||||
const ready = !!attached && !!statics && lang !== null;
|
||||
|
||||
// Read when the views are built; toggling it later goes through `setSync`.
|
||||
const syncScroll = useRef(opts.syncScroll);
|
||||
syncScroll.current = opts.syncScroll;
|
||||
|
||||
// (Re)build the CodeMirror views.
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host || !attached || !statics || lang === null) return;
|
||||
const textA = attached.a?.text() ?? statics.a ?? "";
|
||||
const textB = attached.b?.text() ?? statics.b ?? "";
|
||||
const scrollTop = viewsRef.current
|
||||
? viewsRef.current.merge
|
||||
? (viewsRef.current.merge.dom as HTMLElement).scrollTop
|
||||
: viewsRef.current.b.scrollDOM.scrollTop
|
||||
const prev = viewsRef.current;
|
||||
const scrollTop = prev
|
||||
? prev.merge && !prev.panes
|
||||
? (prev.merge.dom as HTMLElement).scrollTop
|
||||
: prev.b.scrollDOM.scrollTop
|
||||
: null;
|
||||
viewsRef.current?.destroy();
|
||||
prev?.destroy();
|
||||
host.textContent = "";
|
||||
const listener = EditorView.updateListener.of((u) => {
|
||||
if (u.selectionSet || u.docChanged) updateChunkInfo();
|
||||
@@ -272,11 +280,21 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
let views: Views;
|
||||
if (opts.mode === "split") {
|
||||
let merge: MergeView | null = null;
|
||||
const panes = opts.alignChanges
|
||||
? null
|
||||
: new UnalignedPanes({
|
||||
sync: syncScroll.current,
|
||||
arrows:
|
||||
editableA || editableB
|
||||
? { toA: editableA, toB: editableB, apply: (i, source) => merge && applyChunk(merge, i, source) }
|
||||
: undefined,
|
||||
});
|
||||
const mv = new MergeView({
|
||||
a: {
|
||||
doc: textA,
|
||||
extensions: [
|
||||
side(attached.a, editableA, "left"),
|
||||
panes?.extension ?? [],
|
||||
focusTracker("a"),
|
||||
findWatch("a"),
|
||||
editableA ? hoverRevert((_v, i) => merge && applyChunk(merge, i, "b")) : [],
|
||||
@@ -286,6 +304,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
doc: textB,
|
||||
extensions: [
|
||||
side(attached.b, editableB, "right"),
|
||||
panes?.extension ?? [],
|
||||
listener,
|
||||
focusTracker("b"),
|
||||
findWatch("b"),
|
||||
@@ -294,17 +313,36 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
],
|
||||
},
|
||||
parent: host,
|
||||
revertControls: editableB ? "a-to-b" : editableA ? "b-to-a" : undefined,
|
||||
// Unaligned panes draw their arrows on their own divider.
|
||||
revertControls: panes ? undefined : editableB ? "a-to-b" : editableA ? "b-to-a" : undefined,
|
||||
renderRevertControl:
|
||||
editableA || editableB ? arrowControls(() => merge, { toA: editableA, toB: editableB }) : undefined,
|
||||
!panes && (editableA || editableB)
|
||||
? arrowControls(() => merge, { toA: editableA, toB: editableB })
|
||||
: undefined,
|
||||
highlightChanges,
|
||||
gutter: true,
|
||||
// Unpadded panes tint the gutters of changed lines instead of a change bar.
|
||||
gutter: !panes,
|
||||
collapseUnchanged,
|
||||
diffConfig,
|
||||
});
|
||||
merge = mv;
|
||||
views = { a: mv.a, b: mv.b, merge: mv, destroy: () => mv.destroy() };
|
||||
if (scrollTop != null) requestAnimationFrame(() => ((mv.dom as HTMLElement).scrollTop = scrollTop));
|
||||
panes?.attach(mv);
|
||||
views = {
|
||||
a: mv.a,
|
||||
b: mv.b,
|
||||
merge: mv,
|
||||
panes,
|
||||
destroy: () => {
|
||||
panes?.destroy();
|
||||
mv.destroy();
|
||||
},
|
||||
};
|
||||
if (scrollTop != null)
|
||||
requestAnimationFrame(() => {
|
||||
// The left pane of unpadded panes follows by itself.
|
||||
if (!panes) (mv.dom as HTMLElement).scrollTop = scrollTop;
|
||||
else mv.b.scrollDOM.scrollTop = scrollTop;
|
||||
});
|
||||
} else {
|
||||
const view = new EditorView({
|
||||
doc: textB,
|
||||
@@ -338,7 +376,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
}),
|
||||
],
|
||||
});
|
||||
views = { a: null, b: view, merge: null, destroy: () => view.destroy() };
|
||||
views = { a: null, b: view, merge: null, panes: null, destroy: () => view.destroy() };
|
||||
if (scrollTop != null) requestAnimationFrame(() => (view.scrollDOM.scrollTop = scrollTop));
|
||||
}
|
||||
viewsRef.current = views;
|
||||
@@ -349,6 +387,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
statics,
|
||||
lang,
|
||||
opts.mode,
|
||||
opts.alignChanges,
|
||||
opts.collapse,
|
||||
opts.ignore,
|
||||
opts.highlight,
|
||||
@@ -360,6 +399,8 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
path,
|
||||
]);
|
||||
|
||||
useEffect(() => viewsRef.current?.panes?.setSync(opts.syncScroll), [opts.syncScroll]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
viewsRef.current?.destroy();
|
||||
@@ -603,9 +644,10 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
if (neighbour) void openDiff(neighbour, { preview: true });
|
||||
};
|
||||
const toolbarRef = useRef<HTMLDivElement | null>(null);
|
||||
const showSettings = () => {
|
||||
const r = toolbarRef.current?.getBoundingClientRect();
|
||||
showContextMenu({ x: r ? r.left + 8 : 120, y: r ? r.bottom : 120 }, [
|
||||
/** The viewer settings menu, under the toolbar's gear (`from`) or its start. */
|
||||
const showSettings = (from?: HTMLElement) => {
|
||||
const r = (from ?? toolbarRef.current)?.getBoundingClientRect();
|
||||
showContextMenu({ x: r ? r.left + (from ? 0 : 8) : 120, y: r ? r.bottom : 120 }, [
|
||||
{ kind: "header", label: "Viewer" },
|
||||
{
|
||||
id: "split",
|
||||
@@ -654,6 +696,13 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
disabled: opts.mode !== "split",
|
||||
run: () => setOpts({ syncScroll: !opts.syncScroll }),
|
||||
},
|
||||
{
|
||||
id: "align",
|
||||
label: "Align Changes",
|
||||
checked: opts.alignChanges,
|
||||
disabled: opts.mode !== "split",
|
||||
run: () => setOpts({ alignChanges: !opts.alignChanges }),
|
||||
},
|
||||
]);
|
||||
};
|
||||
const nav = useRef<DiffNavigator>({
|
||||
@@ -805,6 +854,14 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
? tx`${chunkInfo.count} difference`
|
||||
: tx`${chunkInfo.count} differences`}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="settings"
|
||||
title="Settings"
|
||||
shortcut={shortcutLabel("diff.showSettings")}
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) => showSettings(e.currentTarget)}
|
||||
/>
|
||||
</div>
|
||||
{opts.mode === "split" ? (
|
||||
<div className={styles.labels}>
|
||||
@@ -860,7 +917,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
|
||||
className={clsx(
|
||||
styles.host,
|
||||
opts.highlight === "none" && styles.noHighlight,
|
||||
opts.mode === "split" && !opts.syncScroll && styles.unsynced,
|
||||
opts.mode === "split" && (opts.alignChanges ? !opts.syncScroll && styles.unsynced : styles.unaligned),
|
||||
)}
|
||||
hidden={!!error || !ready}
|
||||
aria-label={diffTitle(data)}
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from "../diffOptions";
|
||||
import { clipboardDiffData, compareFilesData, parseTextsArg } from "../compare";
|
||||
import { diffInput, diffTitle, sideFile, sideKey } from "../diffInput";
|
||||
import { viewerBase } from "../cm";
|
||||
import { changedLineGutters, viewerBase } from "../cm";
|
||||
|
||||
const doc = (s: string) => Text.of(s.split("\n"));
|
||||
|
||||
@@ -24,8 +24,22 @@ describe("diff options", () => {
|
||||
it("parses stored options with per-field defaults", () => {
|
||||
expect(parseDiffOptions(null)).toEqual(DEFAULT_DIFF_OPTIONS);
|
||||
expect(
|
||||
parseDiffOptions({ mode: "split", ignore: "trim", highlight: "lines", collapse: false, syncScroll: false }),
|
||||
).toEqual({ mode: "split", ignore: "trim", highlight: "lines", collapse: false, syncScroll: false });
|
||||
parseDiffOptions({
|
||||
mode: "split",
|
||||
ignore: "trim",
|
||||
highlight: "lines",
|
||||
collapse: false,
|
||||
syncScroll: false,
|
||||
alignChanges: false,
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "split",
|
||||
ignore: "trim",
|
||||
highlight: "lines",
|
||||
collapse: false,
|
||||
syncScroll: false,
|
||||
alignChanges: false,
|
||||
});
|
||||
expect(parseDiffOptions({ ignore: "bogus", highlight: 3, collapse: "x" })).toEqual(DEFAULT_DIFF_OPTIONS);
|
||||
});
|
||||
|
||||
@@ -155,6 +169,26 @@ describe("diff options", () => {
|
||||
parent.remove();
|
||||
});
|
||||
|
||||
it("carries the change background into the line number gutter", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
|
||||
const mv = new MergeView({
|
||||
a: { doc: "keep\nlet x = 1;\nend\n", extensions },
|
||||
b: { doc: "keep\nlet x = 2;\nadded\nend\n", extensions },
|
||||
parent,
|
||||
gutter: false,
|
||||
diffConfig: { override: whitespaceDiff("none") },
|
||||
});
|
||||
const numbers = (v: typeof mv.a, cls: string) =>
|
||||
[...v.dom.querySelectorAll(`.cm-lineNumbers .${cls}`)].map((e) => e.textContent);
|
||||
expect(numbers(mv.a, "cm-diffChangedGutter")).toEqual(["2"]);
|
||||
expect(numbers(mv.b, "cm-diffChangedGutter")).toEqual(["2", "3"]);
|
||||
expect(numbers(mv.b, "cm-diffWholeGutter")).toEqual(["3"]);
|
||||
mv.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
|
||||
it("marks a deleted last line as a whole line", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Chunk, MergeView } from "@codemirror/merge";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { bandAt, bandPath, transferY, type Band } from "../diffScroll";
|
||||
|
||||
const doc = (s: string) => Text.of(s.split("\n"));
|
||||
const LINE = 20;
|
||||
|
||||
/** The band at `y` of side `from` in two texts with every line LINE px tall. */
|
||||
function bands(a: string, b: string) {
|
||||
const da = doc(a);
|
||||
const db = doc(b);
|
||||
const ext = (d: Text, from: number, to: number): [number, number] => {
|
||||
if (from > d.length) return [d.lines * LINE, d.lines * LINE];
|
||||
const top = (d.lineAt(from).number - 1) * LINE;
|
||||
return from >= to ? [top, top] : [top, d.lineAt(Math.min(to - 1, d.length)).number * LINE];
|
||||
};
|
||||
const chunks = Chunk.build(da, db);
|
||||
return (y: number, from: "a" | "b"): Band =>
|
||||
bandAt(
|
||||
chunks,
|
||||
(c) => ext(da, c.fromA, c.toA),
|
||||
(c) => ext(db, c.fromB, c.toB),
|
||||
da.lines * LINE,
|
||||
db.lines * LINE,
|
||||
y,
|
||||
from,
|
||||
);
|
||||
}
|
||||
|
||||
describe("unaligned side-by-side scrolling", () => {
|
||||
// Right side inserts three lines after line 2 and changes line 5 into two lines.
|
||||
const a = "1\n2\n3\n4\n5\n6\n7";
|
||||
const b = "1\n2\nx\ny\nz\n3\n4\nfive\nfive'\n6\n7";
|
||||
const bandOf = bands(a, b);
|
||||
const at = (y: number, from: "a" | "b") => transferY([bandOf(y, from)], y, from);
|
||||
|
||||
it("splits both documents into unchanged and changed bands", () => {
|
||||
const row = (x: Band) => [x.a0, x.a1, x.b0, x.b1, x.changed];
|
||||
expect([0, 39, 40, 79, 80, 99, 100, 139].map((y) => row(bandOf(y, "a")))).toEqual([
|
||||
[0, 40, 0, 40, false],
|
||||
[0, 40, 0, 40, false],
|
||||
[40, 80, 100, 140, false],
|
||||
[40, 80, 100, 140, false],
|
||||
[80, 100, 140, 180, true],
|
||||
[80, 100, 140, 180, true],
|
||||
[100, 140, 180, 220, false],
|
||||
[100, 140, 180, 220, false],
|
||||
]);
|
||||
expect([0, 40, 99, 100, 140, 179, 180].map((y) => row(bandOf(y, "b")))).toEqual([
|
||||
[0, 40, 0, 40, false],
|
||||
[40, 40, 40, 100, true],
|
||||
[40, 40, 40, 100, true],
|
||||
[40, 80, 100, 140, false],
|
||||
[80, 100, 140, 180, true],
|
||||
[80, 100, 140, 180, true],
|
||||
[100, 140, 180, 220, false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps unchanged text straight through", () => {
|
||||
expect(at(10, "a")).toBe(10);
|
||||
expect(at(50, "a")).toBe(110);
|
||||
expect(at(130, "a")).toBe(210);
|
||||
expect(at(210, "b")).toBe(130);
|
||||
});
|
||||
|
||||
it("jumps over an insertion when scrolling the side without it", () => {
|
||||
expect(at(39, "a")).toBe(39);
|
||||
expect(at(40, "a")).toBe(100);
|
||||
});
|
||||
|
||||
it("waits at the boundary while the inserted lines scroll by", () => {
|
||||
for (const y of [40, 60, 99]) expect(at(y, "b")).toBe(40);
|
||||
});
|
||||
|
||||
it("follows line by line inside a change, then waits at the shorter end", () => {
|
||||
expect(at(150, "b")).toBe(90);
|
||||
expect(at(170, "b")).toBe(100);
|
||||
expect(at(90, "a")).toBe(150);
|
||||
});
|
||||
|
||||
it("scales unchanged text of different heights (wrapped lines)", () => {
|
||||
const stretched = [{ a0: 0, a1: 100, b0: 0, b1: 200, changed: false }];
|
||||
expect(transferY(stretched, 50, "a")).toBe(100);
|
||||
expect(transferY(stretched, 50, "b")).toBe(25);
|
||||
});
|
||||
|
||||
it("draws an empty side as a sliver on its boundary", () => {
|
||||
expect(bandPath(30, 40, 40, 40, 100)).toBe("M0 39C9 39 21 40 30 40L30 100C21 100 9 41 0 41Z");
|
||||
});
|
||||
|
||||
it("can keep MergeView from padding the panes", () => {
|
||||
// UnalignedPanes replaces this (private) method; a rename upstream would bring the padding back.
|
||||
expect(typeof (MergeView.prototype as unknown as { measure: unknown }).measure).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import type { EditorInput } from "@/workbench/contributions";
|
||||
import { Chunk } from "@codemirror/merge";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { iconMarkup } from "@/ui";
|
||||
import { ContextMenuHost, iconMarkup } from "@/ui";
|
||||
|
||||
const probe = vi.fn();
|
||||
const openFile = vi.fn();
|
||||
@@ -80,6 +80,40 @@ describe("Diff toolbar", () => {
|
||||
expect(probe).toHaveBeenCalledWith("/p/a.ts");
|
||||
});
|
||||
|
||||
it("turns on aligned changes from the settings menu (off by default)", async () => {
|
||||
localStorage.clear();
|
||||
texts.HEAD = "a\nb\n";
|
||||
texts.abc123 = "a\nnew\nb\n";
|
||||
render(
|
||||
<>
|
||||
<DiffEditor input={input} />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2));
|
||||
// Unpadded panes joined by the divider.
|
||||
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).not.toBeNull());
|
||||
expect(document.querySelector(".cm-changeGutter")).toBeNull();
|
||||
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffWholeGutter")?.textContent).toBe("2");
|
||||
// The lock turns scrolling together off without rebuilding the panes.
|
||||
const divider = document.querySelector(".cm-diffDivider");
|
||||
(await screen.findByRole("button", { name: "Synchronize Scrolling" })).click();
|
||||
await waitFor(() => expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!).syncScroll).toBe(false));
|
||||
expect(document.querySelector(".cm-diffDivider")).toBe(divider);
|
||||
(await screen.findByRole("button", { name: "Settings" })).click();
|
||||
const item = await screen.findByRole("menuitemcheckbox", { name: "Align Changes" });
|
||||
expect(item.getAttribute("aria-checked")).toBe("false");
|
||||
item.click();
|
||||
// Padded panes with a change bar.
|
||||
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).toBeNull());
|
||||
expect(document.querySelector(".cm-changeGutter")).not.toBeNull();
|
||||
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!)).toMatchObject({
|
||||
alignChanges: true,
|
||||
syncScroll: false,
|
||||
});
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("has no Jump to Source when the file is gone from the working tree", async () => {
|
||||
probe.mockRejectedValue(new Error("no such file"));
|
||||
render(<DiffEditor input={input} />);
|
||||
|
||||
+68
-11
@@ -3,11 +3,21 @@
|
||||
* based theme + syntax colours and lazy language loading by file name.
|
||||
*/
|
||||
import { HighlightStyle, LanguageDescription, syntaxHighlighting, type LanguageSupport } from "@codemirror/language";
|
||||
import { Compartment, EditorState, RangeSetBuilder, type Extension, type Line } from "@codemirror/state";
|
||||
import {
|
||||
Compartment,
|
||||
EditorState,
|
||||
RangeSet,
|
||||
RangeSetBuilder,
|
||||
StateField,
|
||||
type Extension,
|
||||
type Line,
|
||||
} from "@codemirror/state";
|
||||
import {
|
||||
Decoration,
|
||||
EditorView,
|
||||
GutterMarker,
|
||||
ViewPlugin,
|
||||
gutterLineClass,
|
||||
highlightActiveLine,
|
||||
keymap,
|
||||
lineNumbers,
|
||||
@@ -27,17 +37,16 @@ import { useProject } from "@/platform/project";
|
||||
const wholeLine = Decoration.line({ class: "cm-diffWholeLine" });
|
||||
|
||||
/**
|
||||
* Marks the changed lines that have no counterpart on the other side (inserted
|
||||
* or deleted as a whole) so they get a solid background. Lines paired with a
|
||||
* line on the other side keep the line tint plus word-level highlights.
|
||||
* Calls `f` for the changed lines of a side-by-side pane between `vpFrom` and
|
||||
* `vpTo`, with whether the line has no counterpart on the other side (inserted
|
||||
* or deleted as a whole). Lines paired with a line on the other side keep the
|
||||
* line tint plus word-level highlights.
|
||||
*/
|
||||
function wholeLineDeco(view: EditorView): DecorationSet {
|
||||
const info = getChunks(view.state);
|
||||
if (!info || !info.side) return Decoration.none;
|
||||
function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (line: Line, whole: boolean) => void) {
|
||||
const info = getChunks(state);
|
||||
if (!info || !info.side) return;
|
||||
const isA = info.side === "a";
|
||||
const { doc } = view.state;
|
||||
const { from: vpFrom, to: vpTo } = view.viewport;
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
const { doc } = state;
|
||||
for (const chunk of info.chunks) {
|
||||
const from = isA ? chunk.fromA : chunk.fromB;
|
||||
const to = isA ? chunk.toA : chunk.toB;
|
||||
@@ -49,11 +58,46 @@ function wholeLineDeco(view: EditorView): DecorationSet {
|
||||
const covered = (line: Line) =>
|
||||
ranges.some(([f = 0, t = 0]) => (f <= line.from && t > line.to) || (f < line.from && t >= line.to));
|
||||
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < Math.min(to, vpTo);) {
|
||||
if (otherEmpty || covered(line)) builder.add(line.from, line.from, wholeLine);
|
||||
f(line, otherEmpty || covered(line));
|
||||
if (line.number === doc.lines) break;
|
||||
line = doc.line(line.number + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Solid background for the lines changed as a whole. */
|
||||
function wholeLineDeco(view: EditorView): DecorationSet {
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, whole) => {
|
||||
if (whole) builder.add(line.from, line.from, wholeLine);
|
||||
});
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
class LineClassMarker extends GutterMarker {
|
||||
constructor(readonly elementClass: string) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
const changedGutter = new LineClassMarker("cm-diffChangedGutter");
|
||||
const wholeGutter = new LineClassMarker("cm-diffChangedGutter cm-diffWholeGutter");
|
||||
|
||||
/** The line background of changed lines carried into the gutters (line numbers, inclusion boxes), as in IDEA. */
|
||||
export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
|
||||
create: (state) => changedGutterMarkers(state),
|
||||
update: (value, tr) =>
|
||||
tr.docChanged || getChunks(tr.startState)?.chunks !== getChunks(tr.state)?.chunks
|
||||
? changedGutterMarkers(tr.state)
|
||||
: value,
|
||||
provide: (f) => gutterLineClass.from(f),
|
||||
});
|
||||
|
||||
function changedGutterMarkers(state: EditorState): RangeSet<GutterMarker> {
|
||||
const builder = new RangeSetBuilder<GutterMarker>();
|
||||
forChangedLines(state, 0, state.doc.length + 1, (line, whole) =>
|
||||
builder.add(line.from, line.from, whole ? wholeGutter : changedGutter),
|
||||
);
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
@@ -143,6 +187,19 @@ export const viewerTheme = EditorView.theme(
|
||||
"&.cm-merge-b .cm-changedText, .cm-insertedLine .cm-changedText": {
|
||||
background: "color-mix(in srgb, var(--success) 26%, transparent)",
|
||||
},
|
||||
// Gutters of changed lines take the line background (changedLineGutters).
|
||||
"&.cm-merge-a .cm-diffChangedGutter": {
|
||||
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
|
||||
},
|
||||
"&.cm-merge-b .cm-diffChangedGutter": {
|
||||
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
|
||||
},
|
||||
"&.cm-merge-a .cm-diffWholeGutter": {
|
||||
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
|
||||
},
|
||||
"&.cm-merge-b .cm-diffWholeGutter": {
|
||||
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
|
||||
},
|
||||
".cm-changeGutter": { width: "3px", paddingLeft: "0" },
|
||||
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": { background: "var(--gutter-deleted)" },
|
||||
"&.cm-merge-b .cm-changedLineGutter": { background: "var(--gutter-modified)" },
|
||||
|
||||
@@ -17,7 +17,8 @@ export function applyChunk(mv: MergeView, index: number, source: "a" | "b") {
|
||||
dst.dispatch({ changes: transferChunk(chunk, source, src.state.doc, dst.state.doc), userEvent: "revert" });
|
||||
}
|
||||
|
||||
function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
|
||||
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
|
||||
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = `cm-diffArrow cm-diffArrow-${dir}`;
|
||||
|
||||
@@ -15,7 +15,13 @@ export interface DiffViewOptions {
|
||||
ignore: IgnorePolicy;
|
||||
highlight: HighlightPolicy;
|
||||
collapse: boolean;
|
||||
/** Side-by-side panes scroll together. */
|
||||
syncScroll: boolean;
|
||||
/**
|
||||
* Side-by-side panes are padded so that unchanged lines line up. Off, each pane
|
||||
* keeps its own height and a curved divider joins the changes (IDEA's default).
|
||||
*/
|
||||
alignChanges: boolean;
|
||||
}
|
||||
|
||||
export const IGNORE_OPTIONS: ReadonlyArray<{ value: IgnorePolicy; label: string }> = [
|
||||
@@ -37,6 +43,7 @@ export const DEFAULT_DIFF_OPTIONS: DiffViewOptions = {
|
||||
highlight: "words",
|
||||
collapse: true,
|
||||
syncScroll: true,
|
||||
alignChanges: false,
|
||||
};
|
||||
|
||||
const KEY = "openidea.vcs.diffOptions";
|
||||
@@ -54,6 +61,7 @@ export function parseDiffOptions(raw: unknown): DiffViewOptions {
|
||||
highlight: oneOf(o.highlight, HIGHLIGHT_OPTIONS, d.highlight),
|
||||
collapse: typeof o.collapse === "boolean" ? o.collapse : d.collapse,
|
||||
syncScroll: typeof o.syncScroll === "boolean" ? o.syncScroll : d.syncScroll,
|
||||
alignChanges: typeof o.alignChanges === "boolean" ? o.alignChanges : d.alignChanges,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* IDEA's side-by-side diff without alignment padding: each pane scrolls on its
|
||||
* own, scrolling one carries the other along through the changes
|
||||
* (SyncScrollSupport), and the divider between them draws a curved band per
|
||||
* change (DiffDividerDrawUtil) with the ">>" / "<<" arrows on it. Changed lines
|
||||
* tint their gutters instead of showing a change bar.
|
||||
*/
|
||||
import { RangeSetBuilder, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
|
||||
import { changedLineGutters } from "./cm";
|
||||
import { arrowButton } from "./diffControls";
|
||||
|
||||
type Side = "a" | "b";
|
||||
|
||||
/** A stretch of both documents in document pixels: unchanged text, or a change. */
|
||||
export interface Band {
|
||||
a0: number;
|
||||
a1: number;
|
||||
b0: number;
|
||||
b1: number;
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
/** Pixel [top, bottom] of a chunk's range in `view`; an empty range is the boundary it sits on. */
|
||||
function extent(view: EditorView, from: number, to: number): [number, number] {
|
||||
const len = view.state.doc.length;
|
||||
if (from > len) {
|
||||
const end = view.lineBlockAt(len).bottom;
|
||||
return [end, end];
|
||||
}
|
||||
const top = view.lineBlockAt(from).top;
|
||||
return from >= to ? [top, top] : [top, view.lineBlockAt(Math.min(to - 1, len)).bottom];
|
||||
}
|
||||
|
||||
/** First index in `[0, n)` for which `past` holds, given that it holds for a suffix. */
|
||||
function firstIndex(n: number, past: (i: number) => boolean): number {
|
||||
let lo = 0;
|
||||
let hi = n;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (past(mid)) hi = mid;
|
||||
else lo = mid + 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stretch of both documents around `y` of side `from`, from the top to
|
||||
* `endA` / `endB`: unchanged text, or a change (BaseSyncScrollable.processHelper).
|
||||
* Only the chunks next to `y` are measured.
|
||||
*/
|
||||
export function bandAt(
|
||||
chunks: readonly Chunk[],
|
||||
extentA: (c: Chunk) => [number, number],
|
||||
extentB: (c: Chunk) => [number, number],
|
||||
endA: number,
|
||||
endB: number,
|
||||
y: number,
|
||||
from: Side,
|
||||
): Band {
|
||||
const master = from === "a" ? extentA : extentB;
|
||||
const next = firstIndex(chunks.length, (i) => master(chunks[i]!)[0] > y);
|
||||
let a = 0;
|
||||
let b = 0;
|
||||
const prev = chunks[next - 1];
|
||||
if (prev) {
|
||||
const [a0, a1] = extentA(prev);
|
||||
const [b0, b1] = extentB(prev);
|
||||
if (y < (from === "a" ? a1 : b1)) return { a0, a1, b0, b1, changed: true };
|
||||
a = a1;
|
||||
b = b1;
|
||||
}
|
||||
const c = chunks[next];
|
||||
return c
|
||||
? { a0: a, a1: extentA(c)[0], b0: b, b1: extentB(c)[0], changed: false }
|
||||
: { a0: a, a1: endA, b0: b, b1: endB, changed: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* The position on the other side matching `y` of side `from`
|
||||
* (BaseSyncScrollable.transferLine, in pixels): unchanged text maps through,
|
||||
* and inside a change the other side follows line by line, then waits at the
|
||||
* end of its shorter part.
|
||||
*/
|
||||
export function transferY(bands: readonly Band[], y: number, from: Side): number {
|
||||
const fromA = from === "a";
|
||||
const band = bands.find((b) => y < (fromA ? b.a1 : b.b1)) ?? bands[bands.length - 1]!;
|
||||
const [m0, m1, s0, s1] = fromA ? [band.a0, band.a1, band.b0, band.b1] : [band.b0, band.b1, band.a0, band.a1];
|
||||
if (band.changed) return Math.min(s0 + (y - m0), s1);
|
||||
return m1 > m0 ? s0 + ((y - m0) * (s1 - s0)) / (m1 - m0) : s0;
|
||||
}
|
||||
|
||||
type ChangeKind = "inserted" | "deleted" | "modified";
|
||||
const kindOf = (c: Chunk): ChangeKind => (c.fromA === c.toA ? "inserted" : c.fromB === c.toB ? "deleted" : "modified");
|
||||
|
||||
/** The divider band between [a0, a1] on the left and [b0, b1] on the right (DiffDrawUtil.makeCurve). */
|
||||
export function bandPath(w: number, a0: number, a1: number, b0: number, b1: number): string {
|
||||
// An empty side is a 2px sliver on its boundary.
|
||||
if (a1 - a0 < 2) [a0, a1] = [a0 - 1, a0 + 1];
|
||||
if (b1 - b0 < 2) [b0, b1] = [b0 - 1, b0 + 1];
|
||||
const c1 = w * 0.3;
|
||||
const c2 = w * 0.7;
|
||||
return `M0 ${a0}C${c1} ${a0} ${c2} ${b0} ${w} ${b0}L${w} ${b1}C${c2} ${b1} ${c1} ${a1} 0 ${a1}Z`;
|
||||
}
|
||||
|
||||
const gapMark = (kind: ChangeKind, end: boolean) =>
|
||||
Decoration.line({ class: `cm-diffGap cm-diffGap-${kind}${end ? " cm-diffGapEnd" : ""}` });
|
||||
|
||||
/** A line where the other side has lines this one lacks, as in IDEA's empty-side marker. */
|
||||
function gapDeco(view: EditorView): DecorationSet {
|
||||
const info = getChunks(view.state);
|
||||
if (!info?.side) return Decoration.none;
|
||||
const isA = info.side === "a";
|
||||
const { doc } = view.state;
|
||||
const { from: vpFrom, to: vpTo } = view.viewport;
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
for (const c of info.chunks) {
|
||||
const [from, to] = isA ? [c.fromA, c.toA] : [c.fromB, c.toB];
|
||||
if (from !== to) continue;
|
||||
if (from > vpTo) break;
|
||||
if (from < vpFrom) continue;
|
||||
// Past the end of a document without a final line break: below its last line.
|
||||
const line = doc.lineAt(Math.min(from, doc.length));
|
||||
builder.add(line.from, line.from, gapMark(kindOf(c), from > doc.length));
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
const gapMarks = ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = gapDeco(view);
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.docChanged || u.viewportChanged || getChunks(u.startState)?.chunks !== getChunks(u.state)?.chunks)
|
||||
this.decorations = gapDeco(u.view);
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
);
|
||||
|
||||
const SVG = "http://www.w3.org/2000/svg";
|
||||
const ARROW_HEIGHT = 16;
|
||||
let gradients = 0;
|
||||
|
||||
export interface UnalignedPanesOptions {
|
||||
/** Scrolling one pane carries the other along. */
|
||||
sync: boolean;
|
||||
/** Divider arrows toward the editable sides; `apply` copies chunk `index` from `source`. */
|
||||
arrows?: { toA: boolean; toB: boolean; apply(index: number, source: Side): void };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll synchronization and the divider for a MergeView whose panes are not
|
||||
* padded into alignment. Add `extension` to both editors, then `attach` the view.
|
||||
*/
|
||||
export class UnalignedPanes {
|
||||
readonly extension: Extension;
|
||||
private mv: MergeView | null = null;
|
||||
private readonly divider = document.createElement("div");
|
||||
private readonly svg = document.createElementNS(SVG, "svg");
|
||||
private readonly bandLayer = document.createElementNS(SVG, "g");
|
||||
private readonly gradient = `cm-diffBandGradient-${++gradients}`;
|
||||
private readonly arrowEls = new Map<string, HTMLButtonElement>();
|
||||
/** Scroll position each pane was last moved to by the other one, to tell its echo from the user. */
|
||||
private readonly moved: Record<Side, { top: number | null; left: number | null }> = {
|
||||
a: { top: null, left: null },
|
||||
b: { top: null, left: null },
|
||||
};
|
||||
private sync: boolean;
|
||||
private frame = -1;
|
||||
private resize: ResizeObserver | null = null;
|
||||
private readonly cleanup: (() => void)[] = [];
|
||||
|
||||
constructor(private readonly opts: UnalignedPanesOptions) {
|
||||
this.sync = opts.sync;
|
||||
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
|
||||
this.divider.className = "cm-diffDivider";
|
||||
this.svg.setAttribute("aria-hidden", "true");
|
||||
this.svg.innerHTML =
|
||||
`<defs><linearGradient id="${this.gradient}" x1="0" x2="1">` +
|
||||
`<stop offset="0" class="cm-diffBandStopA"/><stop offset="1" class="cm-diffBandStopB"/>` +
|
||||
`</linearGradient></defs>`;
|
||||
this.svg.appendChild(this.bandLayer);
|
||||
this.divider.appendChild(this.svg);
|
||||
}
|
||||
|
||||
attach(mv: MergeView) {
|
||||
this.mv = mv;
|
||||
// MergeView pads the panes into alignment on each measure; these panes stay unpadded.
|
||||
(mv as unknown as { measure(): void }).measure = () => {};
|
||||
mv.a.dom.parentElement!.after(this.divider);
|
||||
for (const side of ["a", "b"] as const) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const onScroll = () => this.scrolled(side);
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
this.cleanup.push(() => el.removeEventListener("scroll", onScroll));
|
||||
}
|
||||
// The divider scrolls the right pane (and, when synchronized, through it the left one).
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
e.preventDefault();
|
||||
mv.b.scrollDOM.scrollBy(e.deltaX, e.deltaY);
|
||||
};
|
||||
this.divider.addEventListener("wheel", onWheel, { passive: false });
|
||||
this.cleanup.push(() => this.divider.removeEventListener("wheel", onWheel));
|
||||
if (typeof ResizeObserver !== "undefined") {
|
||||
this.resize = new ResizeObserver(() => this.schedule());
|
||||
this.resize.observe(this.divider);
|
||||
}
|
||||
requestAnimationFrame(() => this.resync());
|
||||
}
|
||||
|
||||
/** Brings the left pane in line with the right one. */
|
||||
resync() {
|
||||
if (this.mv && this.sync) this.follow("b");
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
/** Turns synchronized scrolling on (bringing the left pane in line) or off. */
|
||||
setSync(on: boolean) {
|
||||
if (on === this.sync) return;
|
||||
this.sync = on;
|
||||
this.resync();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.frame >= 0) cancelAnimationFrame(this.frame);
|
||||
this.resize?.disconnect();
|
||||
for (const f of this.cleanup) f();
|
||||
this.divider.remove();
|
||||
this.mv = null;
|
||||
}
|
||||
|
||||
private view(side: Side): EditorView {
|
||||
return side === "a" ? this.mv!.a : this.mv!.b;
|
||||
}
|
||||
|
||||
private scrolled(side: Side) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const moved = this.moved[side];
|
||||
const echo =
|
||||
(moved.top !== null || moved.left !== null) &&
|
||||
(moved.top === null || Math.abs(el.scrollTop - moved.top) <= 1) &&
|
||||
(moved.left === null || Math.abs(el.scrollLeft - moved.left) <= 1);
|
||||
moved.top = moved.left = null;
|
||||
if (!echo && this.sync) this.follow(side);
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
private bandAt(y: number, from: Side): Band {
|
||||
const { a, b, chunks } = this.mv!;
|
||||
return bandAt(
|
||||
chunks,
|
||||
(c) => extent(a, c.fromA, c.toA),
|
||||
(c) => extent(b, c.fromB, c.toB),
|
||||
a.lineBlockAt(a.state.doc.length).bottom,
|
||||
b.lineBlockAt(b.state.doc.length).bottom,
|
||||
y,
|
||||
from,
|
||||
);
|
||||
}
|
||||
|
||||
/** Scrolls the other pane to match `from`, anchored a third down the pane (SyncScrollSupport). */
|
||||
private follow(from: Side) {
|
||||
const to: Side = from === "a" ? "b" : "a";
|
||||
const master = this.view(from);
|
||||
const slave = this.view(to);
|
||||
const anchor = master.scrollDOM.clientHeight / 3;
|
||||
const at = master.scrollDOM.scrollTop + anchor - docOffset(master);
|
||||
const y = transferY([this.bandAt(at, from)], at, from);
|
||||
const el = slave.scrollDOM;
|
||||
const top = Math.max(0, Math.min(y + docOffset(slave) - anchor, el.scrollHeight - el.clientHeight));
|
||||
const moved = this.moved[to];
|
||||
if (Math.abs(el.scrollTop - top) >= 1) {
|
||||
const before = el.scrollTop;
|
||||
el.scrollTop = top;
|
||||
if (el.scrollTop !== before) moved.top = el.scrollTop;
|
||||
}
|
||||
const left = master.scrollDOM.scrollLeft;
|
||||
if (el.scrollLeft !== left) {
|
||||
const before = el.scrollLeft;
|
||||
el.scrollLeft = left;
|
||||
if (el.scrollLeft !== before) moved.left = el.scrollLeft;
|
||||
}
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (this.frame < 0 && this.mv) this.frame = requestAnimationFrame(() => this.draw());
|
||||
}
|
||||
|
||||
private draw() {
|
||||
this.frame = -1;
|
||||
const mv = this.mv;
|
||||
if (!mv) return;
|
||||
const rect = this.divider.getBoundingClientRect();
|
||||
const w = rect.width;
|
||||
const h = rect.height;
|
||||
if (!w || !h) return;
|
||||
this.svg.setAttribute("width", String(w));
|
||||
this.svg.setAttribute("height", String(h));
|
||||
this.svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
|
||||
const offA = mv.a.documentTop - rect.top;
|
||||
const offB = mv.b.documentTop - rect.top;
|
||||
const lineHeight = mv.a.defaultLineHeight;
|
||||
const arrowTop = (y0: number, y1: number) =>
|
||||
y1 - y0 < 2 ? y0 - ARROW_HEIGHT / 2 : y0 + (Math.min(lineHeight, y1 - y0) - ARROW_HEIGHT) / 2;
|
||||
const arrows = this.opts.arrows;
|
||||
const shown = new Set<string>();
|
||||
let paths = "";
|
||||
const { chunks } = mv;
|
||||
// Chunks run down both panes in order: start at the first one reaching into either.
|
||||
const first = Math.min(
|
||||
firstIndex(chunks.length, (i) => extent(mv.a, chunks[i]!.fromA, chunks[i]!.toA)[1] + offA >= -1),
|
||||
firstIndex(chunks.length, (i) => extent(mv.b, chunks[i]!.fromB, chunks[i]!.toB)[1] + offB >= -1),
|
||||
);
|
||||
for (let i = first; i < chunks.length; i++) {
|
||||
const c = chunks[i]!;
|
||||
const [a0, a1] = extent(mv.a, c.fromA, c.toA).map((y) => y + offA) as [number, number];
|
||||
const [b0, b1] = extent(mv.b, c.fromB, c.toB).map((y) => y + offB) as [number, number];
|
||||
if (a0 > h + 1 && b0 > h + 1) break;
|
||||
if (a1 < -1 && b1 < -1) continue;
|
||||
const kind = kindOf(c);
|
||||
const fill = kind === "modified" ? ` fill="url(#${this.gradient})"` : "";
|
||||
const mid = (a0 + a1) / 2;
|
||||
const midB = (b0 + b1) / 2;
|
||||
paths +=
|
||||
`<path class="cm-diffBand cm-diffBand-${kind}"${fill} d="${bandPath(w, a0, a1, b0, b1)}"/>` +
|
||||
`<path class="cm-diffBandLine cm-diffBand-${kind}" d="M0 ${mid}C${w * 0.3} ${mid} ${w * 0.7} ${midB} ${w} ${midB}"/>`;
|
||||
if (arrows?.toB) this.placeArrow(shown, i, "a-to-b", arrowTop(a0, a1), h);
|
||||
if (arrows?.toA) this.placeArrow(shown, i, "b-to-a", arrowTop(b0, b1), h);
|
||||
}
|
||||
this.bandLayer.innerHTML = paths;
|
||||
for (const [key, el] of this.arrowEls)
|
||||
if (!shown.has(key)) {
|
||||
el.remove();
|
||||
this.arrowEls.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private placeArrow(shown: Set<string>, index: number, dir: "a-to-b" | "b-to-a", top: number, h: number) {
|
||||
if (top < -ARROW_HEIGHT || top > h) return;
|
||||
const key = `${index}${dir}`;
|
||||
let el = this.arrowEls.get(key);
|
||||
if (!el) {
|
||||
el = arrowButton(dir, (i) => this.opts.arrows?.apply(i, dir === "a-to-b" ? "a" : "b"));
|
||||
this.arrowEls.set(key, el);
|
||||
this.divider.appendChild(el);
|
||||
}
|
||||
el.dataset.chunk = String(index);
|
||||
el.style.top = `${top}px`;
|
||||
shown.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Offset of the document's top within the pane's scrolled content. */
|
||||
function docOffset(view: EditorView): number {
|
||||
return view.documentTop - view.scrollDOM.getBoundingClientRect().top + view.scrollDOM.scrollTop;
|
||||
}
|
||||
@@ -34,6 +34,18 @@ export function isCancelled(e: unknown): boolean {
|
||||
return e instanceof IpcError && e.kind === "cancelled";
|
||||
}
|
||||
|
||||
/** Backend `unavailable` message when servers run but none has the feature: "jdtls doesn't support inline completion". */
|
||||
const LACKS_FEATURE = /^\S.* doesn't support \S.*$/;
|
||||
|
||||
/**
|
||||
* What to tell the user when a language-server feature is `unavailable`: the
|
||||
* running server that lacks it, so a working server doesn't read as missing;
|
||||
* `fallback` when no server is running.
|
||||
*/
|
||||
export function unavailableText(e: unknown, fallback = "No language server available"): string {
|
||||
return e instanceof IpcError && e.kind === "unavailable" && LACKS_FEATURE.test(e.message) ? e.message : fallback;
|
||||
}
|
||||
|
||||
// Ids are shared by every window of the backend and outlive a reload there (a cancel that
|
||||
// arrives before its request began is remembered), so each page starts at a random point.
|
||||
let nextId = 1 + Math.floor(Math.random() * 0x7000_0000);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
", e.g.": ",例如",
|
||||
", then press Tab.": ",然后按 Tab。",
|
||||
"? This cannot be undone.": "?此操作无法撤消。",
|
||||
"API request failed, retrying (attempt {attempt})": "API 请求失败,正在重试(第 {attempt} 次)",
|
||||
"API request failed, retrying in {wait}s (attempt {attempt})": "API 请求失败,{wait} 秒后重试(第 {attempt} 次)",
|
||||
"A charset in .editorconfig takes precedence. Change one file's encoding from the status bar.": ".editorconfig 中的 charset 优先。可以从状态栏更改单个文件的编码。",
|
||||
"A command line, e.g. /bin/zsh --login. Leave empty to use the login shell.": "命令行,例如 /bin/zsh --login。留空则使用登录 Shell。",
|
||||
"A line breakpoint that is removed after it is hit": "命中后即移除的行断点",
|
||||
@@ -58,6 +60,7 @@
|
||||
"Adjust colors for red-green vision deficiency": "针对红绿色觉缺陷调整颜色",
|
||||
"After Replace": "替换后",
|
||||
"After Stop, the process gets this long to exit after the interrupt before it is killed.": "停止后,进程在收到中断信号后有这么长时间退出,超时将被强制终止。",
|
||||
"Align Changes": "对齐更改",
|
||||
"All": "全部",
|
||||
"All Places": "所有位置",
|
||||
"All breakpoints": "所有断点",
|
||||
@@ -2574,7 +2577,27 @@
|
||||
"Call Inline Completion": "调用内联补全",
|
||||
"Inline completion is off for this language": "此语言已关闭内联补全",
|
||||
"No inline suggestions": "没有内联建议",
|
||||
"No language server provides inline completion": "没有语言服务器提供内联补全",
|
||||
"{servers} doesn't support {feature}": "{servers} 不支持{feature}",
|
||||
"completion": "代码补全",
|
||||
"inline completion": "内联补全",
|
||||
"hover": "快速文档",
|
||||
"signature help": "形参信息",
|
||||
"go to definition": "转到定义",
|
||||
"go to declaration": "转到声明",
|
||||
"go to type definition": "转到类型声明",
|
||||
"go to implementation": "转到实现",
|
||||
"find references": "查找用法",
|
||||
"document highlights": "高亮用法",
|
||||
"code actions": "代码操作",
|
||||
"rename": "重命名",
|
||||
"formatting": "重新格式化代码",
|
||||
"range formatting": "格式化选中代码",
|
||||
"inlay hints": "嵌入提示",
|
||||
"code lens": "代码透镜",
|
||||
"document links": "文档链接",
|
||||
"call hierarchy": "调用层次结构",
|
||||
"type hierarchy": "类型层次结构",
|
||||
"workspace symbols": "工作区符号",
|
||||
"Insert Inline Proposal": "插入内联建议",
|
||||
"Insert Inline Proposal: Next Word": "插入内联建议:下一个单词",
|
||||
"Hide Inline Proposal": "隐藏内联建议",
|
||||
@@ -4664,5 +4687,28 @@
|
||||
"Code insight needs the index; it can't be stopped": "代码洞察依赖索引,无法停止",
|
||||
"Waiting for other tasks": "正在等待其他任务",
|
||||
"This task can't be cancelled": "此任务无法取消",
|
||||
"Cancelled": "已取消"
|
||||
"Cancelled": "已取消",
|
||||
"No proxy": "不使用代理",
|
||||
"Auto-detect proxy settings": "自动检测代理设置",
|
||||
"Uses the system proxy: the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables.": "使用系统代理:HTTP_PROXY、HTTPS_PROXY 和 NO_PROXY 环境变量。",
|
||||
"Manual proxy configuration": "手动配置代理",
|
||||
"Proxy": "代理",
|
||||
"Proxy type": "代理类型",
|
||||
"Host name": "主机名",
|
||||
"Port number": "端口号",
|
||||
"No proxy for": "不对以下主机使用代理",
|
||||
"Comma-separated host names; * matches any characters, e.g. *.example.com, 192.168.*": "以逗号分隔的主机名;* 匹配任意字符,例如 *.example.com, 192.168.*",
|
||||
"Proxy authentication": "代理身份验证",
|
||||
"Login": "登录名",
|
||||
"Connection successful: {status}": "连接成功:{status}",
|
||||
"Problem with connection: {message}": "连接出现问题:{message}",
|
||||
"Check connection…": "检查连接…",
|
||||
"Check connection": "检查连接",
|
||||
"Enter any URL to check connection to:": "输入要检查连接的任意 URL:",
|
||||
"Check": "检查",
|
||||
"HTTP Proxy": "HTTP 代理",
|
||||
"Proxy host is empty": "代理主机为空",
|
||||
"Invalid proxy host": "代理主机无效",
|
||||
"Proxy port must be between 1 and 65535": "代理端口必须介于 1 和 65535 之间",
|
||||
"Proxy login is empty": "代理登录名为空"
|
||||
}
|
||||
@@ -155,6 +155,7 @@ const UNTRANSLATED = new Set<string>([
|
||||
"GOPATH",
|
||||
"GOROOT",
|
||||
"HEAD",
|
||||
"HTTP",
|
||||
"JDK",
|
||||
"JDK 1.4.x",
|
||||
"JDK 5 - 8",
|
||||
@@ -162,6 +163,7 @@ const UNTRANSLATED = new Set<string>([
|
||||
"NULL",
|
||||
"ORDER BY",
|
||||
"SDK",
|
||||
"SOCKS",
|
||||
"SSH/SSL",
|
||||
"SSL",
|
||||
"TODO",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateSettings } from "@/features/settings/model/schema";
|
||||
import { DEFAULT_PROXY, proxyProblem, validateProxy, withProxyKind, type ProxySettingsValid } from "./proxySettings";
|
||||
|
||||
const manual = (patch: Partial<ProxySettingsValid> = {}): ProxySettingsValid => ({
|
||||
...DEFAULT_PROXY,
|
||||
mode: "manual",
|
||||
host: "proxy.corp",
|
||||
port: 3128,
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe("validateProxy", () => {
|
||||
it("defaults to auto-detect", () => {
|
||||
expect(validateProxy(undefined)).toEqual(DEFAULT_PROXY);
|
||||
expect(DEFAULT_PROXY.mode).toBe("auto");
|
||||
expect(validateSettings({}).proxy).toEqual(DEFAULT_PROXY);
|
||||
});
|
||||
|
||||
it("keeps valid values", () => {
|
||||
const raw = {
|
||||
mode: "manual",
|
||||
kind: "socks",
|
||||
host: "10.0.0.1",
|
||||
port: 1081,
|
||||
noProxy: "*.example.com, 192.168.*",
|
||||
authenticate: true,
|
||||
login: "me",
|
||||
password: "pw",
|
||||
};
|
||||
expect(validateProxy(raw)).toEqual(raw);
|
||||
expect(validateProxy({ mode: "none" }).mode).toBe("none");
|
||||
});
|
||||
|
||||
it("falls back on malformed values", () => {
|
||||
const p = validateProxy({ mode: "pac", kind: "ftp", host: 7, port: 70000, authenticate: "yes", login: null });
|
||||
expect(p).toEqual(DEFAULT_PROXY);
|
||||
expect(validateProxy({ kind: "socks", port: 0 }).port).toBe(1080);
|
||||
expect(validateProxy({ port: 80.5 }).port).toBe(80);
|
||||
expect(validateProxy([]).mode).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe("withProxyKind", () => {
|
||||
it("moves a default port along and keeps a custom one", () => {
|
||||
expect(withProxyKind(manual({ port: 80 }), "socks")).toMatchObject({ kind: "socks", port: 1080 });
|
||||
expect(withProxyKind(manual({ kind: "socks", port: 1080 }), "http").port).toBe(80);
|
||||
expect(withProxyKind(manual({ port: 3128 }), "socks").port).toBe(3128);
|
||||
});
|
||||
});
|
||||
|
||||
describe("proxyProblem", () => {
|
||||
it("checks only a manual configuration", () => {
|
||||
expect(proxyProblem({ ...DEFAULT_PROXY, host: "" })).toBeNull();
|
||||
expect(proxyProblem({ ...DEFAULT_PROXY, mode: "none" })).toBeNull();
|
||||
expect(proxyProblem(manual())).toBeNull();
|
||||
});
|
||||
|
||||
it("reports a missing or invalid host, port and login", () => {
|
||||
expect(proxyProblem(manual({ host: " " }))).toBe("Proxy host is empty");
|
||||
expect(proxyProblem(manual({ host: "http://proxy" }))).toBe("Invalid proxy host");
|
||||
expect(proxyProblem(manual({ host: "user@proxy" }))).toBe("Invalid proxy host");
|
||||
expect(proxyProblem(manual({ port: 0 }))).toBe("Proxy port must be between 1 and 65535");
|
||||
expect(proxyProblem(manual({ authenticate: true, login: "" }))).toBe("Proxy login is empty");
|
||||
expect(proxyProblem(manual({ authenticate: true, login: "me", password: "" }))).toBeNull();
|
||||
expect(proxyProblem(manual({ authenticate: false, login: "" }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* System Settings › HTTP Proxy as the UI consumes it (mirrors
|
||||
* `ide-core::proxy_settings` defaults). Normalisation never throws.
|
||||
*/
|
||||
export type ProxyModeValid = "none" | "auto" | "manual";
|
||||
export type ProxyKindValid = "http" | "socks";
|
||||
|
||||
export interface ProxySettingsValid {
|
||||
mode: ProxyModeValid;
|
||||
kind: ProxyKindValid;
|
||||
host: string;
|
||||
port: number;
|
||||
/** Comma-separated host globs reached directly (`*.example.com, 192.168.*`). */
|
||||
noProxy: string;
|
||||
authenticate: boolean;
|
||||
login: string;
|
||||
/** Kept in the saved passwords by the backend, not in settings.toml. */
|
||||
password: string;
|
||||
}
|
||||
|
||||
export const PROXY_DEFAULT_PORT: Record<ProxyKindValid, number> = {
|
||||
http: 80,
|
||||
socks: 1080,
|
||||
};
|
||||
export const PROXY_PORT_LIMITS = { min: 1, max: 65535 } as const;
|
||||
|
||||
export const DEFAULT_PROXY: ProxySettingsValid = {
|
||||
mode: "auto",
|
||||
kind: "http",
|
||||
host: "",
|
||||
port: PROXY_DEFAULT_PORT.http,
|
||||
noProxy: "",
|
||||
authenticate: false,
|
||||
login: "",
|
||||
password: "",
|
||||
};
|
||||
|
||||
type Obj = Record<string, unknown>;
|
||||
const obj = (v: unknown): Obj => (v && typeof v === "object" && !Array.isArray(v) ? (v as Obj) : {});
|
||||
const str = (v: unknown) => (typeof v === "string" ? v : "");
|
||||
|
||||
export function validateProxy(raw: unknown): ProxySettingsValid {
|
||||
const p = obj(raw);
|
||||
const mode: ProxyModeValid = p.mode === "none" || p.mode === "manual" ? p.mode : "auto";
|
||||
const kind: ProxyKindValid = p.kind === "socks" ? "socks" : "http";
|
||||
const port =
|
||||
typeof p.port === "number" &&
|
||||
Number.isInteger(p.port) &&
|
||||
p.port >= PROXY_PORT_LIMITS.min &&
|
||||
p.port <= PROXY_PORT_LIMITS.max
|
||||
? p.port
|
||||
: PROXY_DEFAULT_PORT[kind];
|
||||
return {
|
||||
mode,
|
||||
kind,
|
||||
host: str(p.host),
|
||||
port,
|
||||
noProxy: str(p.noProxy),
|
||||
authenticate: p.authenticate === true,
|
||||
login: str(p.login),
|
||||
password: str(p.password),
|
||||
};
|
||||
}
|
||||
|
||||
/** Switching HTTP ⇄ SOCKS moves a default port along. */
|
||||
export function withProxyKind(p: ProxySettingsValid, kind: ProxyKindValid): ProxySettingsValid {
|
||||
const port = p.port === PROXY_DEFAULT_PORT[p.kind] ? PROXY_DEFAULT_PORT[kind] : p.port;
|
||||
return { ...p, kind, port };
|
||||
}
|
||||
|
||||
/** What keeps a manual configuration from working (as the backend checks it), or `null`. */
|
||||
export function proxyProblem(p: ProxySettingsValid): string | null {
|
||||
if (p.mode !== "manual") return null;
|
||||
const host = p.host.trim();
|
||||
if (!host) return "Proxy host is empty";
|
||||
if (/[/@\s]/.test(host)) return "Invalid proxy host";
|
||||
if (p.port < PROXY_PORT_LIMITS.min || p.port > PROXY_PORT_LIMITS.max) {
|
||||
return "Proxy port must be between 1 and 65535";
|
||||
}
|
||||
if (p.authenticate && !p.login.trim()) return "Proxy login is empty";
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user