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

...
Автор SHA1 Повідомлення Дата
l0ng-ai c51383d2f9 Merge remote-tracking branch 'origin/main' into t7015 2026-11-30 22:55:14 +08:00
l0ng-ai 9f1380cf04 fix(agents): edit user messages in place without layout jump (#7007)
Clicking Edit on a user message replaced the bubble with a full-width, left-aligned textarea and dropped the timestamp and You label, so the text jumped. Editing now stays inside the user message container: the header is kept, the editor takes the measured bubble width (bounded by the bubble max-width) with the same padding, and the actions sit under it.
2026-11-30 22:54:56 +08:00
l0ng-ai 338e1a5b02 fix(agents): keep active and pinned task order stable (#7002)
Active status groups and active tasks in custom groups were ordered by updatedMs, so concurrent turns, status changes, renames and per-task MCP/skill/memory overrides kept reshuffling the list. They now sort by creation time, newest first, and Pinned keeps its pinned order including manual drag overrides. Renaming a task or changing its overrides no longer bumps updated_ms.
2026-11-30 22:52:26 +08:00
l0ng-ai 092cde1319 fix(agents): prevent native context menu on conversation images (#6995)
Right-clicking a conversation image thumbnail or its full-size preview showed the WebView's native image menu (Open Image in New Window, Download Image, Copy Image). Both contextmenu handlers stopped propagation without preventing the default action; they now call preventDefault as well.
2026-11-30 22:50:39 +08:00
LU XIANGRUIтаwildcatDownstairs fc1e1838ca feat(run): run Xcode apps on a connected iPhone or iPad (#7056)
The Xcode run destination chooser lists paired iPhones and iPads from devicectl under a Devices header, marking ones that are not connected or have Developer Mode off. Running on a device stops before building when the device is not ready or the app would be unsigned (CODE_SIGNING_ALLOWED = NO, or automatic signing without a team), and otherwise builds with -allowProvisioningUpdates, installs with devicectl and launches with --console so output shows in the Run console and Stop ends the app. Scheme environment goes through DEVICECTL_CHILD_*, and a failed launch adds an unlock hint after devicectl's error. Debugging on a device is not supported yet. Install and launch on real hardware were exercised with a stubbed xcrun only.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:45:00 +08:00
solhovoy 9a9a536525 feat(bookmarks): show a tooltip on gutter bookmarks, update the icon and add Rename Bookmark to context menu (#7057)
Hovering a bookmark in the editor gutter shows its description, or the line text when it has none, and the marker carries the same text as its accessible label. The plain marker uses the shared filled bookmark icon at 13px instead of a custom outline. The gutter context menu on a bookmarked line offers Rename Bookmark…, which opens the bookmark description editor, next to Delete Bookmark.

Co-authored-by: solhovoy <[email protected]>
2026-11-30 22:39:04 +08:00
LU XIANGRUIтаwildcatDownstairs 2d7928374e fix(ui): keep list and popup match highlights off the editor scheme's search colour (#7045)
Matched characters in Search Everywhere and every chooser built on HighlightedText used --bg-search-match, which editor colour schemes rewrite for their Search result attribute (Darcula: dark green), so the popup highlight turned dark green instead of the SearchMatch gold. Lists now read new --bg-list-match / --fg-list-match tokens set per theme (dark, light, high contrast, palette themes) and mapped from IntelliJ theme SearchMatch keys; they are not scheme variables, so applying a colour scheme leaves them alone. In-editor search marks and code previews still follow the scheme. The Harbor Night template and the theme token docs include the new tokens.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:18:41 +08:00
audichuang 58eb5ae667 fix(network): route plugin WebSockets and the MCP probe through the IDE proxy (#7062)
The plugin WebSocket API opened a direct socket and the MCP server probe built a bare reqwest client, so both ignored the IDE's proxy settings (Manual and the macOS PAC). Plugin WebSockets now open their TCP stream through ide_http::tunnel; loopback stays direct in every mode, and a proxy the tunnel cannot speak to (SOCKS, https://) keeps the previous direct connection. The tunnel's reason, such as a proxy that needs a login, is part of the failure message. The MCP probe uses the shared ide_http client builder and sets the MCP headers and 12 s limit per request, with protocol headers taking precedence over configured ones. The tunnel also no longer double-brackets IPv6 literals ([[::1]]:port), which broke the Jupyter kernel channels for IPv6 hosts.

Co-authored-by: audichuang <[email protected]>
2026-11-30 22:12:37 +08:00
Игорь Тихомиров 0698ebb9b0 fix(php): check Composer dependencies from the project owning vendor files (#7053)
A file inside an installed package under vendor/ (or a custom config.vendor-dir) has its own composer.json, so the dependency check treated the package as a separate Composer project and reported it as not installed. The check now walks from the content root inward and attributes a file to the outermost project whose vendor directory contains it; nested projects outside vendor still use their own manifest.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 22:09:31 +08:00
l0ng-ai 647e564127 fix(ui): align descriptive columns in option pickers (#7032)
Option descriptions in pickers such as Effort Level started at different horizontal positions because each virtualized row sized its own label. The shared select can now align descriptions in one column sized from the widest rendered label, capped for narrow menus and re-measured when fonts change; agent effort, model and configuration pickers, agent defaults, task isolation and Git fetch tag modes use it.
2026-11-30 22:06:17 +08:00
l0ng-ai edd2e90b9b feat(editor): colour Vue component tags apart from HTML elements (#7059)
Component tags in Vue templates (<Icon>, <el-input>) had the same colour as HTML elements. PascalCase or hyphenated tag names now use a new --syn-custom-tag token, the Custom tag name colour: #2fbaa3 in Islands Dark and #b21dbf in Islands Light, with values for high contrast, the palette themes and Harbor Night; other themes fall back to the tag colour.

Fixes #6894
2026-11-30 21:59:52 +08:00
nako-ruruтаnako-ruru 5bfefff5e1 feat(jni): navigate between Java native methods and C++ JNI implementations (#7020)
Go to Declaration on a Java native method opens its Java_<mangled name> implementation in C/C++ files, and on such a function goes back to the native declaration, with a chooser for several targets. Symbols come from the project index, with a text search as fallback; JNI names are mangled and unmangled per the JNI spec (escapes, nested classes, overload signatures). Contributed definition providers may now answer asynchronously.

Co-authored-by: nako-ruru <[email protected]>
2026-11-30 21:45:44 +08:00
LU XIANGRUIтаwildcatDownstairs 49097bf5c0 feat(swift): show SwiftLint findings as diagnostics (#7029)
Swift files below a .swiftlint.yml are linted with swiftlint lint --reporter json: an opened or saved file by its path (so excluded paths and nested configs apply), an edited buffer through stdin. Findings show in the editor and Problems with severity and rule id. SwiftLint joins the tool registry as an installable CLI under Swift; a missing swiftlint is reported once, and nothing runs in Restricted Mode.

Closes #7028

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:39:53 +08:00
LU XIANGRUIтаwildcatDownstairs 09a44bebbe feat(lsp): serve C-family files of Xcode projects through sourcekit-lsp (#7023)
In an Xcode project plain clangd finds no compile flags, so headers on the target's search paths and the generated <Module>-Swift.h were not found. C, C++, Objective-C and Objective-C++ now list sourcekit-lsp before clangd with require-root-marker on buildServer.json and replaces clangd: with an Xcode BSP config sourcekit-lsp serves them with the build server's flags; without one, or without sourcekit-lsp, clangd serves as before.

Closes #7022

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:32:00 +08:00
LU XIANGRUIтаwildcatDownstairs 7237a37104 feat(language): bundle the Objective-C tree-sitter grammar for outline, folding and symbols (#7027)
Bundles tree-sitter-objc (MIT) with an outline query for Objective-C and Objective-C++: @interface/@implementation/@protocol blocks, categories, methods named by selector, properties, instance variables, C declarations and #pragma mark labels, so the Structure view, folding and the symbol index work for .m and .mm files. The built-in syntax-error diagnostics skip both languages, since the grammar misreads Apple's macros and C++.

Closes #7026

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:29:33 +08:00
LU XIANGRUIтаwildcatDownstairs c864cec32f feat(languages): recognize Apple entitlements, privacy manifests, String Catalogs, xcconfig and .strings files (#7021)
.entitlements and .xcprivacy open as XML property lists and .xcstrings as JSON; .xcconfig and .strings get small language definitions that use the C mode for comments, #include and quoted strings. Each gets a matching file icon.

Closes #7018

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:25:40 +08:00
l0ng-ai f7f2efaace feat(debugger): evaluate the expression of an operator on hover and Quick Evaluate (#7055)
Hovering or Alt-clicking an operator while suspended evaluated nothing, because only identifiers, member chains and calls were taken. An operator now gives the expression it belongs to, from the syntax tree: && gives a > 1 && !flag, > gives a > 1, ! gives !flag. A hover leaves out expressions with calls, increments or assignments, which Quick Evaluate still evaluates; an identifier is still just the identifier.

Fixes #7000
2026-11-30 21:19:38 +08:00
l0ng-ai e8cb141d86 fix(plugins): activate plugins whose activation event fired before they loaded (#7054)
A remote project's server receives the desktop's plugin packages after the window has opened its files, so on-language:twig reached the server before the Twig plugin was installed there and was lost; the plugin stayed inactive and Twig files got no highlighting or completion. The same happened locally when a plugin was installed with a matching file already open. The host now remembers the language, file and view activation events fired so far (bounded) and activates a plugin that loads later if one matches, and the window reports on-language again when the active file's language changes.

Fixes #7014
2026-11-30 21:16:47 +08:00
l0ng-ai 23edb66193 fix(agents): align task controls and questions with workbench styling 2026-11-30 18:31:37 +08:00
117 змінених файлів з 3424 додано та 385 видалено

No files matched your search

Створено
+11
Переглянути файл
@@ -4684,6 +4684,7 @@ dependencies = [
"tree-sitter-make",
"tree-sitter-md",
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-php",
"tree-sitter-prisma-io",
@@ -10642,6 +10643,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-objc"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-ocaml"
version = "0.26.0"
-4
Переглянути файл
@@ -2762,7 +2762,6 @@ impl AgentManager {
}
s.task.title = title;
s.title_renamed = true;
s.task.updated_ms = now_ms();
}
task.persist();
task.emit_task();
@@ -3126,7 +3125,6 @@ impl AgentManager {
let changed = s.task.mcp_overrides != cleaned;
if changed {
s.task.mcp_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.snapshot())
};
@@ -3158,7 +3156,6 @@ impl AgentManager {
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
@@ -3194,7 +3191,6 @@ impl AgentManager {
let changed = s.task.memory_overrides != next_boxed;
if changed {
s.task.memory_overrides = next_boxed;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
+33
Переглянути файл
@@ -6928,3 +6928,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
mgr2.shutdown();
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn metadata_edits_do_not_bump_updated_ms() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let fixed_ms = 1_234.0;
handle.state.lock().task.updated_ms = fixed_ms;
mgr.rename(&task.id, "Custom Title").unwrap();
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
assert_eq!(after_mcp.updated_ms, fixed_ms);
let after_skill =
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
assert_eq!(after_skill.updated_ms, fixed_ms);
let after_memory = mgr
.set_memory_overrides(
&task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
+7
Переглянути файл
@@ -27,6 +27,7 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
mod swiftlint;
pub mod trust;
mod ts_code_style;
mod tsc_watch;
@@ -464,6 +465,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
@@ -704,6 +708,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
+139 -26
Переглянути файл
@@ -1115,11 +1115,16 @@ pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
match server.transport {
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
McpTransport::Http | McpTransport::Sse => {
Ok(probe_http_mcp_server(&server, &ide_core::proxy_settings::proxy()).await)
}
}
}
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
async fn probe_http_mcp_server(
server: &ide_core::settings::AgentMcpServer,
proxy: &ide_core::proxy_settings::ProxySettings,
) -> McpProbeResult {
let started = std::time::Instant::now();
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
@@ -1145,31 +1150,36 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
headers.insert(name, val);
}
}
let client =
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
Ok(c) => c,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("HTTP client error: {e}")),
};
}
};
let client = match ide_http::client::build(proxy) {
Ok(c) => c,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("HTTP client error: {}", e.message)),
};
}
};
// The shared client has no MCP headers or 12 s limit of its own. The protocol's headers win over the
// configured ones, as they did over the client's default headers.
let post = |client: &reqwest::Client, url: &str, session_id: Option<&str>| {
let mut headers = headers.clone();
headers.insert(reqwest::header::CONTENT_TYPE, reqwest::header::HeaderValue::from_static("application/json"));
if let Some(value) = session_id.and_then(|sid| reqwest::header::HeaderValue::from_str(sid).ok()) {
headers.insert("mcp-session-id", value);
}
client.post(url).headers(headers).timeout(std::time::Duration::from_secs(12))
};
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
let client = client.clone();
let url = url.to_owned();
async move {
let mut req =
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
if let Some(sid) = session_id.as_deref() {
req = req.header("Mcp-Session-Id", sid);
}
let req = post(&client, &url, session_id.as_deref()).body(body.to_string());
let resp = req
.send()
.await
@@ -1218,7 +1228,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
};
// Best-effort `notifications/initialized` + `tools/list`.
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
let not_req = post(&client, url, session_id.as_deref()).body(
serde_json::json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
@@ -1226,9 +1236,6 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
})
.to_string(),
);
if let Some(sid) = session_id.as_deref() {
not_req = not_req.header("Mcp-Session-Id", sid);
}
let _ = not_req.send().await;
let tools_res = post_rpc(
@@ -1866,6 +1873,112 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
mod tests {
use super::*;
#[tokio::test]
async fn the_mcp_probe_goes_through_the_manual_proxy_and_keeps_its_headers() {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let settings = ide_core::proxy_settings::ProxySettings {
mode: ide_core::proxy_settings::ProxyMode::Manual,
host: "127.0.0.1".into(),
port: address.port(),
..Default::default()
};
let proxy = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut head = String::new();
while !head.ends_with("\r\n\r\n") {
if reader.read_line(&mut head).unwrap() == 0 {
break;
}
}
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
head
});
let server = ide_core::settings::AgentMcpServer {
transport: McpTransport::Http,
url: Some("http://mcp-target.invalid/mcp".into()),
headers: [("X-Test".to_owned(), "1".to_owned())].into(),
..Default::default()
};
let result = probe_http_mcp_server(&server, &settings).await;
assert!(!result.ok);
// A probe that bypassed the proxy leaves it waiting in `accept`; a dummy connection releases it.
let _ = std::net::TcpStream::connect(address);
let head = proxy.join().unwrap().to_ascii_lowercase();
assert!(head.starts_with("post http://mcp-target.invalid/mcp http/1.1"), "{head}");
assert!(head.contains("accept: application/json, text/event-stream"), "{head}");
assert!(head.contains("x-test: 1"), "{head}");
}
#[tokio::test]
async fn mcp_protocol_headers_win_over_configured_ones_in_all_three_requests() {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let server = std::thread::spawn(move || {
let mut heads = Vec::new();
for reply in [
r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}"#,
"",
r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#,
] {
let (mut stream, _) = listener.accept().unwrap();
let mut raw = Vec::new();
let mut byte = [0u8; 1];
while !raw.ends_with(b"\r\n\r\n") {
stream.read_exact(&mut byte).unwrap();
raw.push(byte[0]);
}
let head = String::from_utf8(raw).unwrap().to_ascii_lowercase();
let length = head
.lines()
.find_map(|line| line.strip_prefix("content-length: "))
.map_or(0, |value| value.trim().parse().unwrap());
let mut body = vec![0u8; length];
stream.read_exact(&mut body).unwrap();
heads.push(head);
let _ = stream.write_all(
format!(
"HTTP/1.1 200 OK\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
reply.len()
)
.as_bytes(),
);
}
heads
});
let settings = ide_core::proxy_settings::ProxySettings {
mode: ide_core::proxy_settings::ProxyMode::None,
..Default::default()
};
let server_config = ide_core::settings::AgentMcpServer {
transport: McpTransport::Http,
url: Some(format!("http://127.0.0.1:{port}/mcp")),
headers: [
("Content-Type".to_owned(), "text/plain".to_owned()),
("Mcp-Session-Id".to_owned(), "configured".to_owned()),
("Accept".to_owned(), "text/x-configured".to_owned()),
]
.into(),
..Default::default()
};
let result = probe_http_mcp_server(&server_config, &settings).await;
assert!(result.ok, "{:?}", result.error);
let heads = server.join().unwrap();
let values = |head: &str, name: &str| -> Vec<String> {
head.lines().filter_map(|line| line.strip_prefix(name)).map(|v| v.trim().to_owned()).collect()
};
for (i, head) in heads.iter().enumerate() {
assert_eq!(values(head, "content-type:"), ["application/json"], "request {i}: {head}");
assert_eq!(values(head, "accept:"), ["text/x-configured"], "request {i}: {head}");
// The first request has no session yet, so the configured value stands.
let session = if i == 0 { "configured" } else { "s1" };
assert_eq!(values(head, "mcp-session-id:"), [session], "request {i}: {head}");
}
}
#[test]
fn an_agent_installs_once_at_a_time() {
let first = Installing::begin("test-agent").unwrap();
+3 -3
Переглянути файл
@@ -8,9 +8,9 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
/// no change feed, and one listing takes a fraction of a second.
/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
#[command(trust = trusted)]
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
let root = host.project(window)?.root.clone();
+24 -2
Переглянути файл
@@ -422,6 +422,10 @@ pub struct PluginHost {
initial_load: (Mutex<bool>, Condvar),
/// `on-startup-finished` has fired.
startup_finished: AtomicBool,
/// Language, file and view activation events fired so far (with their project), so a plugin
/// installed or synced afterwards (a remote server gets its packages after the window opened
/// files) still activates for a Twig file that is already open.
fired_activations: Mutex<Vec<(ActivationEvent, Option<PathBuf>)>>,
/// The theme last announced with `ThemeChanged`.
announced_theme: Mutex<Option<ActiveTheme>>,
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
@@ -541,6 +545,7 @@ impl PluginHost {
lifecycle: Mutex::new(()),
initial_load: (Mutex::new(false), Condvar::new()),
startup_finished: AtomicBool::new(false),
fired_activations: Mutex::new(Vec::new()),
announced_theme: Mutex::new(None),
announced_languages: AtomicU64::new(0),
announced_skills: AtomicU64::new(0),
@@ -699,6 +704,16 @@ impl PluginHost {
/// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`).
pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) {
{
let mut fired = self.fired_activations.lock();
let entry = (event.clone(), project.map(Path::to_path_buf));
if !fired.contains(&entry) {
if fired.len() >= MAX_FIRED_ACTIVATIONS {
fired.remove(0);
}
fired.push(entry);
}
}
let targets: Vec<_> = self
.plugins
.read()
@@ -3096,8 +3111,12 @@ impl PluginHost {
meta.pending = pending;
meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static };
}
let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire);
let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire))
|| self.fired_activations.lock().iter().any(|(event, project)| {
(plugin.dev_root.is_none() || plugin.dev_root == *project)
&& plugin.manifest().activation.iter().any(|a| activation_matches(a, event))
});
if eager {
let _ = self.ensure_active(plugin, None);
}
@@ -3725,6 +3744,9 @@ fn counts(m: &Manifest) -> Vec<ContributionCount> {
m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect()
}
/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first).
const MAX_FIRED_ACTIVATIONS: usize = 512;
fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool {
match (declared, fired) {
(ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*",
+118 -11
Переглянути файл
@@ -5,6 +5,10 @@ use super::{
network_inbox::{Inbox, Push},
};
use futures::{SinkExt, StreamExt};
use ide_core::{
IdeResult,
proxy_settings::{ProxyMode, ProxySettings},
};
use ide_plugin::WebSocketBatch;
use parking_lot::Mutex;
use std::{
@@ -17,7 +21,7 @@ use std::{
};
use tokio::sync::{Notify, watch};
use tokio_tungstenite::{
Connector, connect_async_tls_with_config,
Connector, client_async_tls_with_config,
tungstenite::{
Message,
client::IntoClientRequest,
@@ -128,11 +132,20 @@ impl WebSocketHub {
.map(Arc::new)
.map(Connector::Rustls)
.map_err(|error| ConnectError::Failed(error.message))?;
let (socket, response) =
tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls)))
let target = reqwest::Url::parse(url).map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?;
// Through the IDE's proxy settings, like the Jupyter kernel channels.
let (socket, response) = tokio::time::timeout(timeout, async {
// The tunnel's reason (a proxy that needs a login, refuses or is unreachable) helps the user.
let stream = open_stream(&target, &ide_core::proxy_settings::proxy())
.await
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
.map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?;
.map_err(|error| format!("WebSocket connection failed: {}", error.message))?;
client_async_tls_with_config(request, stream, Some(config), Some(tls))
.await
.map_err(|_| "WebSocket connection failed".to_owned())
})
.await
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
.map_err(ConnectError::Failed)?;
if !subprotocol.is_empty()
&& response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok())
!= Some(subprotocol)
@@ -257,14 +270,30 @@ impl WebSocketHub {
}
}
fn validate_url(url: &str) -> Result<(), String> {
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
// `host_str` keeps an IPv6 address in brackets.
let loopback = parsed.host_str().is_some_and(|host| {
/// `host_str` keeps an IPv6 address in brackets.
fn is_loopback(url: &reqwest::Url) -> bool {
url.host_str().is_some_and(|host| {
let host = host.trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
});
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) {
})
}
/// The TCP stream to `url` under `settings`. Loopback stays direct in every mode (plaintext `ws://` is
/// loopback-only); a proxy the tunnel cannot speak to (SOCKS) keeps the direct connection plugins had before.
async fn open_stream(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<tokio::net::TcpStream> {
if is_loopback(url) {
return ide_http::tunnel::connect_best_effort(
url,
&ProxySettings { mode: ProxyMode::None, ..Default::default() },
)
.await;
}
ide_http::tunnel::connect_best_effort(url, settings).await
}
fn validate_url(url: &str) -> Result<(), String> {
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && is_loopback(&parsed)) {
return Err("WebSocket requires WSS outside loopback".into());
}
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
@@ -392,6 +421,84 @@ mod tests {
(url, task)
}
fn manual(port: u16) -> ProxySettings {
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
}
async fn head_of_first_connection(listener: TcpListener) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut client, _) = listener.accept().await.unwrap();
let mut head = Vec::new();
let mut byte = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
client.read_exact(&mut byte).await.unwrap();
head.push(byte[0]);
}
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await.unwrap();
String::from_utf8(head).unwrap()
}
#[tokio::test]
async fn a_manual_proxy_carries_the_connection() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let settings = manual(listener.local_addr().unwrap().port());
let proxy = tokio::spawn(head_of_first_connection(listener));
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
assert!(open_stream(&url, &settings).await.is_err());
// A connection that bypasses the proxy leaves it waiting, so bound the wait.
let asked = tokio::time::timeout(Duration::from_secs(2), proxy).await.expect("the proxy was never asked");
assert!(asked.unwrap().starts_with("CONNECT ws-target.invalid:443 HTTP/1.1\r\n"));
}
#[tokio::test]
async fn loopback_stays_direct_in_every_mode() {
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
let proxy_port = proxy.local_addr().unwrap().port();
let proxy_task = tokio::spawn(head_of_first_connection(proxy));
let target = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url =
reqwest::Url::parse(&format!("ws://localhost:{}/socket", target.local_addr().unwrap().port())).unwrap();
let settings = manual(proxy_port);
open_stream(&url, &settings).await.unwrap();
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
// Auto mode asks the system proxy, which may be set in the environment: loopback must not.
open_stream(&url, &ProxySettings::default()).await.unwrap();
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
assert!(tokio::time::timeout(Duration::from_millis(200), proxy_task).await.is_err(), "the proxy was asked");
}
#[tokio::test]
async fn an_ipv6_loopback_websocket_connects() {
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
let url = format!("ws://[::1]:{}/socket", listener.local_addr().unwrap().port());
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
socket.send(Message::Binary(vec![7].into())).await.unwrap();
socket.close(None).await.unwrap();
});
let hub = WebSocketHub::default();
hub.connect("plugin", "/project", &url, &[], "", Duration::from_secs(2)).await.unwrap();
server.await.unwrap();
}
#[tokio::test]
async fn a_refusing_proxy_says_why() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let settings = manual(listener.local_addr().unwrap().port());
let proxy = tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
let (mut client, _) = listener.accept().await.unwrap();
client.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await.unwrap();
// Keep the socket open until the client has read the reply.
tokio::time::sleep(Duration::from_millis(200)).await;
});
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
let error = open_stream(&url, &settings).await.unwrap_err();
assert!(error.message.contains("needs a login"), "{}", error.message);
proxy.await.unwrap();
}
#[tokio::test]
async fn outbound_message_reaches_the_websocket_server() {
let (url, server) = server().await;
+10
Переглянути файл
@@ -77,6 +77,7 @@ pub struct Project {
pub(crate) widget_preview: ide_flutter::ToolServer,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) swiftlint: Option<Arc<crate::swiftlint::SwiftLint>>,
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
pub(crate) watcher: Arc<Watcher>,
/// Watchers of the Project Structure content roots outside the project folder.
@@ -419,6 +420,8 @@ impl Host {
trusted.clone(),
);
documents.add_observer(phpstan.clone());
let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), sink.clone(), trusted.clone());
documents.add_observer(swiftlint.clone());
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
@@ -441,6 +444,7 @@ impl Host {
let window = window.to_owned();
let kotlin_bridge = kotlin_bridge.clone();
let phpstan = phpstan.clone();
let swiftlint = swiftlint.clone();
let repos = repos.clone();
let git_metadata = git_metadata.clone();
let settings = settings.clone();
@@ -470,6 +474,7 @@ impl Host {
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
kotlin_bridge.files_changed(changed.iter().chain(&batch.removed));
phpstan.files_removed(batch.removed.iter());
swiftlint.files_removed(batch.removed.iter());
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
if composer_changed(&root, changed.iter().chain(&batch.removed))
@@ -720,6 +725,7 @@ impl Host {
notebooks,
kotlin_bridge: Some(kotlin_bridge),
phpstan: Some(phpstan),
swiftlint: Some(swiftlint),
tsc_watch: Some(tsc_watch),
watcher,
content_watchers: Mutex::new(content_watchers),
@@ -786,6 +792,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.start(&self.runtime);
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.start(&self.runtime);
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
@@ -1017,6 +1026,7 @@ impl Host {
notebooks,
kotlin_bridge: None,
phpstan: None,
swiftlint: None,
tsc_watch: None,
watcher: Arc::new(watcher),
content_watchers: Mutex::new(Vec::new()),
+404
Переглянути файл
@@ -0,0 +1,404 @@
//! Swift files below a `.swiftlint.yml` -> `swiftlint lint --reporter json` -> `swiftlint` diagnostics.
//!
//! A file as saved is linted by its path, so the configuration's `excluded` paths and nested
//! configurations apply; an edited buffer is linted through stdin, unless its saved file was excluded.
use ide_core::event::NotifyLevel;
use ide_core::output_encoding::decode_tool_output;
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
use ide_text::AppliedChange;
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
use parking_lot::Mutex;
use serde::Deserialize;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Output, Stdio};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::sync::Notify;
const DELAY: Duration = Duration::from_millis(400);
const SOURCE: &str = "swiftlint";
const CONFIG: &str = ".swiftlint.yml";
/// What to lint: the saved file, or the text of its edited buffer.
#[derive(Clone, Debug, PartialEq)]
enum Job {
Saved,
Buffer(String),
}
pub(crate) struct SwiftLint {
root: PathBuf,
sink: SharedSink,
trusted: Arc<AtomicBool>,
lifetime: CancellationToken,
/// The latest job per file; a newer one replaces it, and its result is dropped.
pending: Mutex<BTreeMap<PathBuf, Job>>,
changed: Notify,
/// Files with SwiftLint diagnostics, the only ones a clean result or a close clears.
shown: Mutex<HashSet<PathBuf>>,
/// Files the configuration excludes, as found by their last saved-file lint.
excluded: Mutex<HashSet<PathBuf>>,
/// Failures already reported (a missing `swiftlint` included), each once until a run succeeds.
reported: Mutex<Option<String>>,
}
impl SwiftLint {
pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc<AtomicBool>) -> Arc<Self> {
Arc::new(Self {
root,
sink,
trusted,
lifetime: CancellationToken::new(),
pending: Mutex::new(BTreeMap::new()),
changed: Notify::new(),
shown: Mutex::new(HashSet::new()),
excluded: Mutex::new(HashSet::new()),
reported: Mutex::new(None),
})
}
pub(crate) fn start(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
let linter = self.clone();
runtime.spawn(async move { linter.run().await });
}
pub(crate) fn stop(&self) {
self.lifetime.cancel();
}
fn queue(&self, path: &Path, job: Job) {
if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") {
return;
}
self.pending.lock().insert(path.to_path_buf(), job);
self.changed.notify_one();
}
/// Trusting the project lints its open files; Restricted Mode drops what was shown.
pub(crate) fn trust_changed(&self, trusted: bool, open: impl Iterator<Item = DocumentInfo>) {
if trusted {
open.for_each(|info| self.opened(&info));
} else {
self.pending.lock().clear();
let shown: Vec<PathBuf> = self.shown.lock().iter().cloned().collect();
for path in shown {
self.publish(path, Vec::new());
}
}
}
/// Deleted files and folders lose their diagnostics.
pub(crate) fn files_removed<'a>(&self, removed: impl Iterator<Item = &'a PathBuf>) {
let removed: Vec<&PathBuf> = removed.collect();
self.excluded.lock().retain(|p| !removed.iter().any(|r| p.starts_with(r)));
let gone: Vec<PathBuf> =
self.shown.lock().iter().filter(|p| removed.iter().any(|r| p.starts_with(r))).cloned().collect();
for path in gone {
self.publish(path, Vec::new());
}
}
fn publish(&self, path: PathBuf, items: Vec<Diagnostic>) {
let mut shown = self.shown.lock();
if items.is_empty() {
if !shown.remove(&path) {
return;
}
} else {
shown.insert(path.clone());
}
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
}
async fn run(self: Arc<Self>) {
loop {
tokio::select! {
_ = self.lifetime.cancelled() => return,
_ = self.changed.notified() => {},
}
// Typing keeps replacing the pending job: lint once it pauses.
tokio::select! {
_ = self.lifetime.cancelled() => return,
_ = tokio::time::sleep(DELAY) => {},
}
loop {
let Some((path, job)) = self.pending.lock().pop_first() else { break };
if !self.trusted.load(Ordering::Acquire) {
continue;
}
let Some(dir) = config_dir(&self.root, &path) else {
self.publish(path, Vec::new());
continue;
};
if job != Job::Saved && self.excluded.lock().contains(&path) {
continue;
}
let text = match &job {
Job::Saved => None,
Job::Buffer(text) => Some(text.as_str()),
};
let Some(output) = lint(&dir, &path, text, &self.lifetime).await else { return };
// Edited again meanwhile: the newer job's result replaces this one. Restricted
// meanwhile: `trust_changed` already cleared the findings.
if self.pending.lock().contains_key(&path) || !self.trusted.load(Ordering::Acquire) {
continue;
}
let result = output.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \
or from Settings › Languages & Frameworks › Language Servers."
.to_string()
} else {
format!("Cannot run swiftlint: {e}")
}
});
let result = result.and_then(|o| parse(&decode_tool_output(&o.stdout), &decode_tool_output(&o.stderr)));
match result {
Ok(Report::Excluded) => {
self.excluded.lock().insert(path.clone());
self.publish(path, Vec::new());
*self.reported.lock() = None;
}
Ok(Report::Violations(violations)) => {
if job == Job::Saved {
self.excluded.lock().remove(&path);
}
let text = match job {
Job::Buffer(text) => text,
Job::Saved => std::fs::read(&path)
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default(),
};
let items = violations.into_iter().map(|v| diagnostic(v, &text)).collect();
self.publish(path, items);
*self.reported.lock() = None;
}
Err(text) => {
self.publish(path, Vec::new());
self.failure(text);
}
}
}
}
}
fn failure(&self, text: String) {
let mut reported = self.reported.lock();
if reported.as_ref() == Some(&text) {
return;
}
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "SwiftLint check failed".into(),
body: Some(text.clone()),
});
*reported = Some(text);
}
}
impl DocumentObserver for SwiftLint {
fn opened(&self, info: &DocumentInfo) {
let path = info.path.to_path_buf();
self.queue(&path, if info.dirty { Job::Buffer(info.text.clone()) } else { Job::Saved });
}
fn changed(
&self,
_doc: ide_core::DocId,
path: &Path,
_version: u32,
_changes: &[AppliedChange],
full_text: &dyn Fn() -> String,
) {
if path.extension().is_some_and(|e| e == "swift") {
self.queue(path, Job::Buffer(full_text()));
}
}
fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) {
self.queue(path, Job::Saved);
}
/// A closed buffer's unsaved text is gone, and with it what its diagnostics described.
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
self.pending.lock().remove(path);
self.publish(path.to_path_buf(), Vec::new());
}
}
/// The folder of the `.swiftlint.yml` nearest to `file` within the project, where SwiftLint
/// runs so it finds that configuration. Files outside the project, or below no configuration,
/// are not linted.
fn config_dir(root: &Path, file: &Path) -> Option<PathBuf> {
file.ancestors()
.skip(1)
.take_while(|d| d.starts_with(root))
.find(|d| d.join(CONFIG).is_file())
.map(Path::to_path_buf)
}
/// Runs `swiftlint lint` in `dir` on the saved `file`, or on `text` through stdin;
/// `None` when `cancel` fires first, which kills it.
async fn lint(
dir: &Path,
file: &Path,
text: Option<&str>,
cancel: &CancellationToken,
) -> Option<std::io::Result<Output>> {
let mut cmd = std::process::Command::new("swiftlint");
cmd.args(["lint", "--reporter", "json", "--quiet", "--no-cache"]).current_dir(dir);
match text {
Some(_) => cmd.arg("--use-stdin"),
None => cmd.arg("--force-exclude").arg(file),
};
ide_core::process::prepare(&mut cmd);
cmd.stdin(if text.is_some() { Stdio::piped() } else { Stdio::null() });
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let mut cmd = tokio::process::Command::from(cmd);
cmd.kill_on_drop(true);
let run = async {
let mut child = cmd.spawn()?;
if let (Some(text), Some(mut stdin)) = (text, child.stdin.take()) {
stdin.write_all(text.as_bytes()).await?;
}
child.wait_with_output().await
};
tokio::select! {
output = run => Some(output),
() = cancel.cancelled() => None,
}
}
/// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the
/// character counted in UTF-16 units.
#[derive(Debug, Deserialize, PartialEq)]
struct Violation {
line: Option<u32>,
character: Option<u32>,
reason: String,
rule_id: String,
severity: String,
}
#[derive(Debug, PartialEq)]
enum Report {
Violations(Vec<Violation>),
/// `--force-exclude` dropped the file: the configuration's `excluded` lists it.
Excluded,
}
/// The `--reporter json` report (SwiftLint exits with 2 when it has errors), or the text
/// to report when there is none.
fn parse(stdout: &str, stderr: &str) -> Result<Report, String> {
if let Ok(violations) = serde_json::from_str::<Vec<Violation>>(stdout.trim()) {
return Ok(Report::Violations(violations));
}
if stderr.contains("No lintable files found") {
return Ok(Report::Excluded);
}
let lines: Vec<&str> = stderr.lines().chain(stdout.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();
if lines.is_empty() {
return Err("SwiftLint ended with no report".into());
}
Err(lines.iter().take(20).copied().collect::<Vec<_>>().join("\n"))
}
fn diagnostic(v: Violation, text: &str) -> Diagnostic {
Diagnostic {
range: range(text, v.line, v.character),
severity: if v.severity.eq_ignore_ascii_case("error") { Severity::Error } else { Severity::Warning },
message: v.reason,
source: Some("SwiftLint".into()),
server: Some(SOURCE.into()),
code: Some(v.rule_id),
unnecessary: false,
deprecated: false,
}
}
/// The word at the reported position, or the line from its first non-blank character when
/// SwiftLint gives no column (or the column has no word: a semicolon, a brace).
fn range(text: &str, line: Option<u32>, character: Option<u32>) -> Range {
let line = line.unwrap_or(1).max(1) - 1;
let content = text.strip_prefix('\u{feff}').unwrap_or(text).split('\n').nth(line as usize).unwrap_or("");
let content: Vec<u16> = content.trim_end().encode_utf16().collect();
let len = u32::try_from(content.len()).unwrap_or(u32::MAX);
let Some(start) = character.map(|c| c.max(1) - 1).filter(|&c| c < len) else {
let indent = content.iter().take_while(|&&u| u == u16::from(b' ') || u == u16::from(b'\t')).count();
return Range { start: Pos { line, col: indent as u32 }, end: Pos { line, col: len } };
};
let word = |u: &u16| char::from_u32(u32::from(*u)).is_some_and(|c| c.is_alphanumeric() || c == '_');
let run = content[start as usize..].iter().take_while(|u| word(u)).count() as u32;
Range { start: Pos { line, col: start }, end: Pos { line, col: start + run.max(1) } }
}
#[cfg(test)]
mod tests {
use super::*;
const REPORT: &str = r#"[
{"character": 5, "file": null, "line": 1, "reason": "Variable name 'a_b' should only contain alphanumeric characters",
"rule_id": "identifier_name", "severity": "Error", "type": "Identifier Name"},
{"character": null, "file": "/p/A.swift", "line": 3, "reason": "Line should be 40 characters or less",
"rule_id": "line_length", "severity": "Warning", "type": "Line Length"},
{"character": 13, "file": null, "line": 2, "reason": "Lines should not have trailing semicolons",
"rule_id": "trailing_semicolon", "severity": "Warning", "type": "Trailing Semicolon"}
]"#;
#[test]
fn violations_map_to_diagnostics() {
let Ok(Report::Violations(violations)) = parse(REPORT, "") else { panic!() };
let text = "let a_b = 1\nlet 😀x = 1 ;\n let long = 2\n";
let items: Vec<Diagnostic> = violations.into_iter().map(|v| diagnostic(v, text)).collect();
let summary: Vec<_> = items.iter().map(|d| (d.code.as_deref().unwrap(), d.severity, d.range)).collect();
let r = |line, a, b| Range { start: Pos { line, col: a }, end: Pos { line, col: b } };
assert_eq!(
summary,
[
("identifier_name", Severity::Error, r(0, 4, 7)),
// No column: the line from its first non-blank character.
("line_length", Severity::Warning, r(2, 4, 16)),
// UTF-16 columns: the emoji takes two, and a semicolon gets one.
("trailing_semicolon", Severity::Warning, r(1, 12, 13)),
]
);
assert_eq!((items[0].source.as_deref(), items[0].server.as_deref()), (Some("SwiftLint"), Some("swiftlint")));
assert!(items[0].message.starts_with("Variable name 'a_b'"));
}
#[test]
fn excluded_files_and_failures_are_told_apart() {
assert_eq!(parse("[]\n", ""), Ok(Report::Violations(vec![])));
let excluded = "Error: No lintable files found at paths: 'Gen/g.swift'\n";
assert_eq!(parse("", excluded), Ok(Report::Excluded));
assert_eq!(parse("", "Fatal error: crashed\n\n"), Err("Fatal error: crashed".into()));
assert_eq!(parse("", ""), Err("SwiftLint ended with no report".into()));
// A bad column or line stays on the text.
assert_eq!(
range("x", Some(9), Some(40)),
Range { start: Pos { line: 8, col: 0 }, end: Pos { line: 8, col: 0 } }
);
}
#[test]
fn the_nearest_configuration_in_the_project_wins() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("p");
std::fs::create_dir_all(root.join("Sources/App")).unwrap();
std::fs::create_dir_all(root.join("Pkg/Sources")).unwrap();
let file = root.join("Sources/App/A.swift");
assert_eq!(config_dir(&root, &file), None);
std::fs::write(dir.path().join(CONFIG), "").unwrap();
assert_eq!(config_dir(&root, &file), None, "a configuration above the project is not the project's");
std::fs::write(root.join(CONFIG), "").unwrap();
std::fs::write(root.join("Pkg").join(CONFIG), "").unwrap();
assert_eq!(config_dir(&root, &file), Some(root.clone()));
assert_eq!(config_dir(&root, &root.join("Pkg/Sources/B.swift")), Some(root.join("Pkg")));
}
}
+4
Переглянути файл
@@ -267,6 +267,10 @@ impl crate::Host {
if let Some(phpstan) = &project.phpstan {
phpstan.interrupt();
}
if let Some(swiftlint) = &project.swiftlint {
let docs = project.documents.open_documents();
swiftlint.trust_changed(trusted, docs.into_iter().filter_map(|d| project.documents.snapshot(d).ok()));
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
+22
Переглянути файл
@@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf {
pkg
}
/// A language activation fired before the plugin was there (a remote server gets the desktop's
/// packages after the window opened its files; a plugin installed with such a file open)
/// activates it once it loads; one that never fired doesn't.
#[test]
fn plugins_loaded_after_their_activation_event_fired_activate() {
use ide_extension::ActivationEvent;
let tmp = tempfile::tempdir().unwrap();
let host = Arc::new(
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
);
host.load_all();
host.startup_finished();
host.activation_event(&ActivationEvent::Language("other".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive);
host.uninstall("misbehave").unwrap();
host.activation_event(&ActivationEvent::Language("mis".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active)));
}
/// Edit-path calls stop waiting at the soft deadline (the result is
/// dropped, the instance kept) and are interrupted at the hard one.
#[test]
+43 -9
Переглянути файл
@@ -3,7 +3,7 @@
use base64::Engine;
use hyper_util::client::proxy::matcher::Matcher;
use ide_core::proxy_settings::ProxyRoute;
use ide_core::proxy_settings::{ProxyRoute, ProxySettings};
use ide_core::{IdeError, IdeResult};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -21,28 +21,41 @@ const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
/// (or, in Auto mode, the system) routes that host to.
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
let route = ide_core::proxy_settings::proxy().route(url.host_str());
connect_with(url, route, SYSTEM_PAC, Matcher::from_system).await
connect_with(url, route, SYSTEM_PAC, Matcher::from_system, false).await
}
/// [`connect`] under explicit proxy `settings`; a proxy the tunnel cannot speak to (SOCKS) is skipped and
/// the connection goes direct, as it did before the proxy was consulted at all.
pub async fn connect_best_effort(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<TcpStream> {
connect_with(url, settings.route(url.host_str()), SYSTEM_PAC, Matcher::from_system, true).await
}
/// `host:port`; `host_str` already brackets an IPv6 address (the same rule as `pac.rs`'s `authority`).
fn authority(host: &str, port: u16) -> String {
if host.contains(':') && !host.starts_with('[') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }
}
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let target = authority(host, port);
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
}
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected.
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected;
/// `skip_unusable` sends a route the tunnel cannot speak to direct instead of failing.
async fn connect_with(
url: &reqwest::Url,
route: ProxyRoute,
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
matcher: impl FnOnce() -> Matcher,
skip_unusable: bool,
) -> IdeResult<TcpStream> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let target = authority(host, port);
let proxy = match route {
ProxyRoute::Direct => None,
ProxyRoute::Via(via) => Some(via),
@@ -75,6 +88,7 @@ async fn connect_with(
}
}
};
let proxy = proxy.filter(|proxy| !skip_unusable || proxy.starts_with("http://"));
let connecting = async {
let Some(proxy) = proxy else {
return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error));
@@ -219,7 +233,7 @@ mod tests {
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
@@ -235,7 +249,7 @@ mod tests {
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build()).await.unwrap();
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build(), false).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
}
@@ -244,7 +258,7 @@ mod tests {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy))
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy), false)
.await
.unwrap();
tokio::time::timeout(Duration::from_millis(300), listener.accept())
@@ -259,10 +273,30 @@ mod tests {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
}
#[tokio::test]
async fn an_unusable_proxy_is_skipped_only_when_asked() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
let socks = || ProxyRoute::Via("socks5h://127.0.0.1:1".into());
let none = || Matcher::builder().build();
assert!(connect_with(&url, socks(), |_| None, none, false).await.unwrap_err().message.contains("socks5h"));
connect_with(&url, socks(), |_| None, none, true).await.unwrap();
listener.accept().await.unwrap();
}
#[tokio::test]
async fn an_ipv6_literal_is_connected_to() {
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::Direct, |_| None, || Matcher::builder().build(), false).await.unwrap();
listener.accept().await.unwrap();
assert_eq!(authority("[::1]", 9), "[::1]:9");
}
#[test]
fn proxy_credentials_are_percent_decoded() {
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
+1
Переглянути файл
@@ -32,6 +32,7 @@ tree-sitter-java = "0.23.5"
tree-sitter-kotlin-ng = "1.1.0"
tree-sitter-c = "0.24.2"
tree-sitter-cpp = "0.23.4"
tree-sitter-objc = "3.0.2"
tree-sitter-c-sharp = "0.23.5"
tree-sitter-ruby = "0.23.1"
tree-sitter-php = "0.25.1"
+50
Переглянути файл
@@ -0,0 +1,50 @@
(class_interface . (identifier) @name category: (identifier) @detail) @def.extension
(class_implementation . (identifier) @name category: (identifier) @detail) @def.extension
(class_interface . (identifier) @name) @def.class
(class_implementation . (identifier) @name) @def.class
(protocol_declaration . (identifier) @name) @def.interface
(method_declaration ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
(method_definition ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
(property_declaration (struct_declaration (struct_declarator [
(identifier) @name
(pointer_declarator declarator: (identifier) @name)
(function_declarator declarator: (parenthesized_declarator (block_pointer_declarator declarator: (identifier) @name)))
]))) @def.property
(instance_variable (struct_declaration (struct_declarator [
(identifier) @name
(pointer_declarator declarator: (identifier) @name)
]))) @def.field
(preproc_call directive: (preproc_directive) @_d argument: (preproc_arg) @name
(#eq? @_d "#pragma") (#match? @name "^mark\\s")) @outline.heading
(function_definition
declarator: [
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
(pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)))
]) @def.function
(translation_unit (declaration
declarator: [
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
]) @def.function)
(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
(union_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
(enum_specifier name: (type_identifier) @name body: (enumerator_list)) @def.enum
(enumerator name: (identifier) @name) @def.enum_member
(field_declaration_list (field_declaration declarator: [
(field_identifier) @name
(pointer_declarator declarator: (field_identifier) @name)
(array_declarator declarator: (field_identifier) @name)
]) @def.field)
(type_definition declarator: (type_identifier) @name) @def.type
(preproc_def name: (identifier) @name) @def.macro
(preproc_function_def name: (identifier) @name parameters: (preproc_params) @detail) @def.macro
(translation_unit (declaration declarator: [
(identifier) @name
(init_declarator declarator: (identifier) @name)
(init_declarator declarator: (pointer_declarator declarator: (identifier) @name))
]) @def.variable)
+7
Переглянути файл
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
("slint", include_str!("../../../languages/slint.toml")),
("sql", include_str!("../../../languages/sql.toml")),
("svelte", include_str!("../../../languages/svelte.toml")),
("strings", include_str!("../../../languages/strings.toml")),
("swift", include_str!("../../../languages/swift.toml")),
("terraform", include_str!("../../../languages/terraform.toml")),
("terraform-vars", include_str!("../../../languages/terraform-vars.toml")),
@@ -98,6 +99,7 @@ const BUILTIN: &[(&str, &str)] = &[
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
("typst", include_str!("../../../languages/typst.toml")),
("vue", include_str!("../../../languages/vue.toml")),
("xcconfig", include_str!("../../../languages/xcconfig.toml")),
("xml", include_str!("../../../languages/xml.toml")),
("yaml", include_str!("../../../languages/yaml.toml")),
("zig", include_str!("../../../languages/zig.toml")),
@@ -1277,6 +1279,11 @@ mod tests {
("P.cs", "csharp"),
("V.swift", "swift"),
("AppDelegate.m", "objective-c"),
("App.entitlements", "xml"),
("PrivacyInfo.xcprivacy", "xml"),
("Localizable.xcstrings", "json"),
("Debug.xcconfig", "xcconfig"),
("en.lproj/Localizable.strings", "strings"),
("a.rb", "ruby"),
("Gemfile", "ruby"),
("show.html.erb", "erb"),
+18
Переглянути файл
@@ -156,6 +156,24 @@ pub(crate) static SPECS: &[Spec] = &[
imports: &["preproc_include", "using_declaration"],
constructors: NONE,
},
Spec {
name: "objc",
language: tree_sitter_objc::LANGUAGE,
outline: outline!("objc"),
highlights: None,
// `@interface` / `@implementation` / `@protocol` ... `@end` have no brackets.
fold_nodes: &[
"class_interface",
"class_implementation",
"protocol_declaration",
"preproc_if",
"preproc_ifdef",
"preproc_function_def",
],
fold_bodies: NONE,
imports: &["preproc_include", "module_import"],
constructors: NONE,
},
Spec {
name: "csharp",
language: tree_sitter_c_sharp::LANGUAGE,
+11 -1
Переглянути файл
@@ -180,7 +180,11 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
}
names.sort_by_key(|n| n.start_byte());
names.dedup_by_key(|n| n.id());
let base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
let mut base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
// Objective-C selectors: `- (id)initWithName:(id)n age:(int)a` is `initWithName:age:`.
if g.spec.name == "objc" && node.children(&mut node.walk()).any(|c| c.kind() == "method_parameter") {
base = names.iter().map(|n| format!("{}:", name_text(n, text))).collect();
}
if base.is_empty() {
continue;
}
@@ -539,6 +543,12 @@ fn name_text(n: &Node, text: &str) -> String {
let t = node_text(n, text);
// Ruby / Elixir symbols: `:total` -> `total`.
let t = if matches!(n.kind(), "simple_symbol" | "atom") { t.trim_start_matches(':') } else { t };
// Objective-C `#pragma mark - Lifecycle` -> `Lifecycle` (a bare `mark -` is a separator, so empty).
let t = if n.kind() == "preproc_arg" {
t.trim().trim_start_matches("mark").trim_start().trim_start_matches('-')
} else {
t
};
clean(t, 120)
}
+113
Переглянути файл
@@ -546,6 +546,119 @@ int main() { return 0; }
assert_eq!(t.iter().filter(|(n, k, _)| n == "draw" && *k == SymbolKind::Method).count(), 2);
}
#[test]
fn outline_objc() {
let src = r#"#import <Foundation/Foundation.h>
#define MAX 10
@protocol Greeting <NSObject>
- (NSString *)greet;
@optional
@property (nonatomic) int level;
@end
@interface Person : NSObject <Greeting> {
int _age;
}
@property (nonatomic, copy) NSString *name;
+ (instancetype)personWithName:(NSString *)name age:(int)age;
- (void)run;
@end
@interface Person (Extra)
- (void)extra;
@end
@implementation Person
#pragma mark - Lifecycle
+ (instancetype)personWithName:(NSString *)name age:(int)age {
return nil;
}
- (void)run {
}
@end
static int helper(int x) { return x; }
"#;
check_outline(
"objective-c",
src,
"
Macro MAX
Interface Greeting
Method greet
Property level
Class Person
Field _age
Property name
Method personWithName:age:
Method run
Namespace Person
Method extra
Class Person
Key Lifecycle
Method personWithName:age:
Method run
Function helper
",
);
let t = tags("objective-c", src);
assert!(has_tag(&t, "greet", SymbolKind::Method, Some("Greeting")));
assert!(has_tag(&t, "personWithName:age:", SymbolKind::Method, Some("Person")));
assert!(has_tag(&t, "extra", SymbolKind::Method, Some("Person")));
assert!(has_tag(&t, "name", SymbolKind::Property, Some("Person")));
assert!(!t.iter().any(|(n, _, _)| n == "Lifecycle"));
let t = tags("objective-c", "@interface A\n@property (copy) void (^onTap)(int i);\n@end\n");
assert!(has_tag(&t, "onTap", SymbolKind::Property, Some("A")), "{t:?}");
// `@interface` / `@protocol` / `@implementation` ... `@end` fold like a braced body.
let f = folds("objective-c", src);
for range in [(2, 6), (8, 14), (16, 18), (20, 27), (22, 24)] {
assert!(f.contains(&(range.0, range.1, FoldKind::Region)), "{range:?} not in {f:?}");
}
}
#[test]
fn outline_objective_cpp_keeps_the_objc_structure() {
// C++ declarations outside the ObjC blocks are lost to error recovery; the ObjC
// classes and methods, which are why a file is `.mm`, stay.
check_outline(
"objective-cpp",
r#"#import "Bridge.h"
#include <vector>
#include <string>
namespace engine {
class Renderer {
public:
void draw(const std::vector<int> &xs);
};
}
@implementation Bridge {
std::unique_ptr<engine::Renderer> _renderer;
}
- (instancetype)init {
self = [super init];
_renderer = std::make_unique<engine::Renderer>();
return self;
}
- (void)drawValues:(NSArray<NSNumber *> *)values {
std::vector<int> xs;
for (NSNumber *n in values) { xs.push_back(n.intValue); }
_renderer->draw(xs);
}
@end
static std::string helper() { return "x"; }
"#,
"
Class Bridge
Method init
Method drawValues:
Function helper
",
);
}
#[test]
fn outline_csharp() {
check_outline(
+48
Переглянути файл
@@ -8824,3 +8824,51 @@ async fn switch_source_header_asks_clangd_and_only_clangd() {
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
h.mgr.shutdown_all().await;
}
/// C-family files go to sourcekit-lsp in an Xcode project with a BSP config (`buildServer.json`),
/// which hands them to clangd with the build's flags; elsewhere, and when sourcekit-lsp is missing,
/// to plain clangd. Uses the shipped language definitions.
#[tokio::test(flavor = "multi_thread")]
async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
let registry = LanguageRegistry::load(None).unwrap();
for (language, ext) in [("c", "h"), ("cpp", "cpp"), ("objective-c", "m"), ("objective-cpp", "mm")] {
let shipped = registry.get(&LanguageId::new(language)).unwrap().language_servers;
let names: Vec<_> = shipped.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["sourcekit-lsp", "clangd"], "{language}");
let servers = [("sourcekit-lsp", incremental_caps()), ("clangd", incremental_caps())];
let as_shipped = |cfg: &mut LanguageServerConfig| {
let real = shipped.iter().find(|c| c.name == cfg.name).unwrap();
cfg.root_markers = real.root_markers.clone();
cfg.require_root_marker = real.require_root_marker;
cfg.replaces = real.replaces.clone();
};
let file = format!("Foo.{ext}");
// A plain folder, or one with only compile_commands.json: clangd alone.
let h = harness_configured(language, ext, &servers, as_shipped);
std::fs::write(h.root.join("compile_commands.json"), "[]").unwrap();
h.open(&file, "");
h.wait_status("clangd", ServerStatus::Ready).await;
assert!(h.statuses("sourcekit-lsp").is_empty(), "{language}");
h.mgr.shutdown_all().await;
// An Xcode project with buildServer.json: sourcekit-lsp alone, rooted at the config.
let h = harness_configured(language, ext, &servers, as_shipped);
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
let (_, path) = h.open(&file, "");
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
assert!(h.statuses("clangd").is_empty(), "{language}");
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), [h.root.clone()]);
h.mgr.shutdown_all().await;
// sourcekit-lsp not installed: clangd still serves.
let h = harness_configured(language, ext, &servers, as_shipped);
h.launcher.state("sourcekit-lsp").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
h.open(&file, "");
h.wait_status("sourcekit-lsp", ServerStatus::Missing).await;
h.wait_status("clangd", ServerStatus::Ready).await;
h.mgr.shutdown_all().await;
}
}
+117 -7
Переглянути файл
@@ -1,4 +1,5 @@
//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on.
//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through
//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on.
//!
//! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode
//! projects use this.
@@ -11,7 +12,8 @@ use specta::Type;
use std::path::Path;
use std::process::Command;
/// One simulator `simctl list devices available` reports.
/// One simulator `simctl list devices available` reports, or one physical device
/// `devicectl list devices` knows.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct IosSimulator {
@@ -19,10 +21,18 @@ pub struct IosSimulator {
pub name: String,
/// The runtime, as Xcode shows it: `iOS 27.0`.
pub runtime: String,
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`.
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
/// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
pub state: String,
/// An iPhone or iPad rather than a simulator.
pub physical: bool,
}
/// The states of a physical device.
pub const AVAILABLE: &str = "Available";
pub const UNAVAILABLE: &str = "Unavailable";
pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off";
/// An Xcode project or workspace directly in `root`, outside a Flutter project (whose
/// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter).
pub fn is_xcode_project(root: &Path) -> bool {
@@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
for d in list.as_array().into_iter().flatten() {
let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned);
let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue };
devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state }));
devices
.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false }));
}
}
devices.sort_by(|(va, a), (vb, b)| {
@@ -67,6 +78,67 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
Ok(devices.into_iter().map(|(_, d)| d).collect())
}
/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name.
/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them.
pub fn parse_devices(json: &str) -> IdeResult<Vec<IosSimulator>> {
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?;
let mut devices = Vec::new();
for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() {
let text = |old: &str, new: &str| {
d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned()
};
let reality = text("/hardwareProperties/reality", "/properties/hardware/reality");
let platform = text("/hardwareProperties/platform", "/properties/hardware/platform");
let udid = text("/hardwareProperties/udid", "/properties/hardware/udid");
if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() {
continue;
}
let version = d
.pointer("/deviceProperties/osVersionNumber")
.or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue"))
.and_then(Value::as_str)
.unwrap_or_default();
// `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`.
let connection = text("/connectionProperties/tunnelState", "/properties/connection/state");
let developer_mode = d
.pointer("/deviceProperties/developerModeStatus")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned());
let state = if connection == "unavailable" || connection.is_empty() {
UNAVAILABLE
} else if developer_mode.as_deref() == Some("disabled") {
DEVELOPER_MODE_OFF
} else {
AVAILABLE
};
devices.push(IosSimulator {
udid,
name: text("/deviceProperties/name", "/properties/state/name"),
runtime: format!("{platform} {version}").trim().to_owned(),
state: state.to_owned(),
physical: true,
});
}
devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid)));
Ok(devices)
}
/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when
/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode.
pub fn devices(dir: &Path) -> Vec<IosSimulator> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id()));
let path = file.to_string_lossy().into_owned();
let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]);
let json = std::fs::read_to_string(&file);
let _ = std::fs::remove_file(&file);
match (listed, json) {
(Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(),
_ => Vec::new(),
}
}
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
let mut cmd = Command::new(program);
@@ -82,10 +154,12 @@ fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String>
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
}
/// The available iOS simulators, sorted as [`parse_list`] does.
/// The available iOS simulators of the Xcode the project at `root` uses.
/// The available iOS simulators of the Xcode the project at `root` uses, sorted as
/// [`parse_list`] does, then the physical devices.
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)
let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?;
list.extend(devices(root));
Ok(list)
}
/// Boots a simulator; returns once `simctl` has it booted.
@@ -142,6 +216,42 @@ mod tests {
assert_eq!(parse_list("{}").unwrap(), []);
}
#[test]
fn lists_physical_devices_by_name_from_old_and_new_fields() {
// Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the
// deprecated fields too, one with `properties` only, a simulator and a Mac.
let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [
{"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
"deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"},
"connectionProperties": {"tunnelState": "disconnected"},
"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
"connection": {"state": "disconnected"}}},
{"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"},
"software": {"osVersionNumber": {"stringValue": "26.1"}},
"state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}},
"connection": {"state": "connected"}}},
{"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"},
"state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}},
"connection": {"state": "unavailable"}}},
{"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"},
"connectionProperties": {"tunnelState": "disconnected"}},
{"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"},
"connectionProperties": {"tunnelState": "connected"}}
]}}"#;
let devices = parse_devices(json).unwrap();
let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect();
assert_eq!(
rows,
[
("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true),
("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true),
("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true),
]
);
assert!(parse_devices("not json").is_err());
assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []);
}
#[test]
fn finds_xcode_projects_at_the_root_only() {
let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id()));
+218 -10
Переглянути файл
@@ -3,7 +3,8 @@
//! projects without any, but it takes a second or two, too slow for detection.
//!
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable;
//! `simctl`, for a connected iPhone or iPad and launches it there with `devicectl`, or, for a
//! macOS app, builds it for the Mac and runs its executable;
//! [`prepare`] turns the configuration into that process when it starts.
use ide_core::{IdeError, IdeResult};
@@ -305,17 +306,32 @@ pub fn mac_executable(settings: &str) -> Result<PathBuf, String> {
}
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
/// scheme's first application target.
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
/// scheme's first application target for the iOS Simulator, or with `device` for an iPhone or
/// iPad, which runs only an app signed with a development team.
pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), String> {
let apps = app_settings(settings)?;
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
let (platform, target) =
if device { ("iphoneos", "an iOS device") } else { ("iphonesimulator", "the iOS Simulator") };
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == platform) else {
return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) {
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
Some(platform) => format!("The scheme builds an app for {platform}, not {target}"),
None => "The scheme builds no application".to_owned(),
});
};
let get =
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
if device && app["CODE_SIGNING_ALLOWED"] == "NO" {
return Err(format!(
"{} is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps",
get("WRAPPER_NAME")?
));
}
if device && app["CODE_SIGN_STYLE"] == "Automatic" && get("DEVELOPMENT_TEAM").is_err() {
return Err(format!(
"Signing {} for a device needs a development team: choose one under Signing & Capabilities in Xcode",
get("WRAPPER_NAME")?
));
}
Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned()))
}
@@ -372,6 +388,49 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String {
)
}
/// The script a run on a physical device executes: build with the project's signing (letting
/// Xcode register the device and fetch profiles, as its own Run does), install, then launch with
/// the app's output on the console. The app's arguments follow the script as `$@`. A Stop's
/// SIGINT becomes a SIGTERM to `devicectl` (a background job ignores SIGINT), which passes it on
/// to the app. When `devicectl` itself fails to launch the app
/// (its JSON outcome is not `success`) and no Stop was asked for, a hint about a locked device
/// follows its error.
pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app: &Path, bundle_id: &str) -> String {
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id));
let hint = sh_quote(&format!("Could not launch the app on {name}. If it is locked, unlock it and run again."));
format!(
"set -e\n\
xcodebuild {} -allowProvisioningUpdates build\n\
xcrun devicectl device install app --device {udid} {app}\n\
set +e\n\
result=$(mktemp)\n\
xcrun devicectl device process launch --console --terminate-existing --json-output \"$result\" --device {udid} {bundle_id} -- \"$@\" &\n\
launch=$!\n\
trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\
wait $launch; status=$?\n\
while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\
if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\
rm -f \"$result\"\n\
exit $status\n",
build.join(" "),
)
}
/// Why a run cannot start on `device`, a physical one [`crate::simulator::devices`] listed.
fn device_unready(device: &crate::simulator::IosSimulator) -> Option<String> {
let name = &device.name;
match device.state.as_str() {
crate::simulator::UNAVAILABLE => Some(format!(
"{name} is not connected. Connect it with a cable or to this Mac's network, unlock it, and run again."
)),
crate::simulator::DEVELOPER_MODE_OFF => Some(format!(
"Developer Mode is off on {name}. Turn it on in Settings > Privacy & Security > Developer Mode, restart the device, and run again."
)),
_ => None,
}
}
/// The script a macOS run executes: build, then become the app's executable, so its output
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
@@ -417,7 +476,7 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data:
}
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
@@ -443,11 +502,32 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I
return Ok(());
}
let udid = destination.trim_start_matches("id=").to_owned();
let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid);
if let Some(reason) = device.as_ref().and_then(device_unready) {
return Err(IdeError::unavailable(reason));
}
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
let settings = show(&args)?;
let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?;
let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?;
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
if let Some(device) = device {
if wait {
return Err(IdeError::unavailable("Debugging an app on a physical device is not supported yet"));
}
config.command = "/bin/sh".into();
config.args = [
"-c".to_owned(),
device_launch_script(&args, &udid, &device.name, &app, &bundle_id),
"xcode-run".to_owned(),
]
.into_iter()
.chain(app_args)
.collect();
let env = std::mem::take(&mut config.env);
config.env = env.into_iter().map(|(k, v)| (format!("DEVICECTL_CHILD_{k}"), v)).collect();
return Ok(());
}
config.command = "/bin/sh".into();
config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id, wait), "xcode-run".to_owned()]
.into_iter()
@@ -625,14 +705,66 @@ mod tests {
)
};
assert_eq!(
built_app(&settings("iphonesimulator")).unwrap(),
built_app(&settings("iphonesimulator"), false).unwrap(),
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
);
assert_eq!(
built_app(&settings("macosx")).unwrap_err(),
built_app(&settings("macosx"), false).unwrap_err(),
"The scheme builds an app for macosx, not the iOS Simulator"
);
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
assert_eq!(built_app("[]", false).unwrap_err(), "The scheme builds no application");
assert_eq!(
built_app(&settings("iphonesimulator"), true).unwrap_err(),
"The scheme builds an app for iphonesimulator, not an iOS device"
);
}
#[test]
fn a_device_app_must_be_signed_with_a_team() {
let settings = |signing: &str| {
format!(
r#"[{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application",
"PLATFORM_NAME": "iphoneos", "TARGET_BUILD_DIR": "/dd/Debug-iphoneos", "WRAPPER_NAME": "App.app",
"PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App", {signing}}}}}]"#
)
};
let signed = settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": "ABCDE12345""#);
assert_eq!(
built_app(&signed, true).unwrap(),
(PathBuf::from("/dd/Debug-iphoneos/App.app"), "dev.example.App".to_owned())
);
let manual = settings(r#""CODE_SIGN_STYLE": "Manual", "DEVELOPMENT_TEAM": """#);
assert!(built_app(&manual, true).is_ok(), "manual signing names its profile; xcodebuild checks it");
assert_eq!(
built_app(&settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": """#), true).unwrap_err(),
"Signing App.app for a device needs a development team: choose one under Signing & Capabilities in Xcode"
);
assert_eq!(
built_app(&settings(r#""CODE_SIGNING_ALLOWED": "NO""#), true).unwrap_err(),
"App.app is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps"
);
}
#[test]
fn an_unready_device_says_what_to_do() {
let device = |state: &str| crate::simulator::IosSimulator {
udid: "U".into(),
name: "Test iPhone".into(),
runtime: "iOS 27.3".into(),
state: state.into(),
physical: true,
};
assert_eq!(device_unready(&device(crate::simulator::AVAILABLE)), None);
assert!(
device_unready(&device(crate::simulator::UNAVAILABLE))
.unwrap()
.starts_with("Test iPhone is not connected.")
);
assert!(
device_unready(&device(crate::simulator::DEVELOPER_MODE_OFF))
.unwrap()
.starts_with("Developer Mode is off on Test iPhone.")
);
}
#[test]
@@ -772,6 +904,82 @@ mod tests {
);
}
/// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT
/// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch.
#[cfg(unix)]
#[test]
fn device_launch_script_installs_launches_and_explains_a_failed_launch() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let stub = |tool: &str, then: &str| {
let path = dir.path().join(tool);
let body = format!(
"#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
);
fs::write(&path, body).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
};
stub("xcodebuild", "");
// `launch` writes its JSON result to the path after `--json-output` ($8), then either
// fails at once or runs until a SIGINT reaches it.
stub(
"xcrun",
"[ \"$4\" = launch ] || exit 0\n\
printf '{\"info\" : {\"outcome\" : \"%s\"}}' \"$OUTCOME\" > \"$8\"\n\
[ \"$OUTCOME\" = success ] || { echo 'ERROR: the device was not unlocked' >&2; exit 1; }\n\
trap 'echo terminated >> \"$LOG\"; exit 0' TERM\n\
while :; do sleep 0.05; done\n",
);
let build = ["-project".to_owned(), "App.xcodeproj".to_owned()];
let script =
device_launch_script(&build, "00008110-AAA", "Test iPhone", Path::new("/dd/My App.app"), "dev.example.App");
let run = |outcome: &str| {
let _ = fs::remove_file(&log);
std::process::Command::new("/bin/sh")
.args(["-c", &script, "xcode-run", "--greeting", "hi there"])
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
.env("LOG", &log)
.env("OUTCOME", outcome)
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap()
};
let failed = run("failed").wait_with_output().unwrap();
assert_eq!(failed.status.code(), Some(1));
assert_eq!(
String::from_utf8_lossy(&failed.stderr),
"ERROR: the device was not unlocked\n\
Could not launch the app on Test iPhone. If it is locked, unlock it and run again.\n"
);
let child = run("success");
let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !launched() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(20));
}
std::thread::sleep(std::time::Duration::from_millis(200));
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
let stopped = child.wait_with_output().unwrap();
assert!(stopped.status.success());
assert_eq!(String::from_utf8_lossy(&stopped.stderr), "");
let log = fs::read_to_string(&log).unwrap();
let json = log.split("[--json-output] [").nth(1).unwrap().split(']').next().unwrap().to_owned();
assert_eq!(
log,
format!(
"xcodebuild [-project] [App.xcodeproj] [-allowProvisioningUpdates] [build]\n\
xcrun [devicectl] [device] [install] [app] [--device] [00008110-AAA] [/dd/My App.app]\n\
xcrun [devicectl] [device] [process] [launch] [--console] [--terminate-existing] [--json-output] [{json}] \
[--device] [00008110-AAA] [dev.example.App] [--] [--greeting] [hi there]\n\
terminated\n"
)
);
assert!(!Path::new(&json).exists(), "the launch result file is removed");
}
/// A debug launch passes `--wait-for-debugger` and prints the pid of the suspended app (not of
/// a running copy, nor of a process outside its bundle) right away, while simctl keeps running.
#[cfg(unix)]
+41 -6
Переглянути файл
@@ -64,16 +64,25 @@ pub enum ComposerInstall {
Outdated,
}
/// The Composer project `file` belongs to (the nearest `composer.json` at or below `root`), and
/// whether its dependencies need `composer install`.
/// Whether the nearest enclosing Composer project needs `composer install`. A manifest inside
/// that project's vendor directory belongs to an installed package.
pub fn composer_install(file: &Path, root: &Path) -> Option<(PathBuf, ComposerInstall)> {
let dir = file.ancestors().filter(|d| d.starts_with(root)).find(|d| d.join("composer.json").is_file())?;
let composer: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).ok()?).ok()?;
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
let ancestors: Vec<_> = file.ancestors().take_while(|dir| dir.starts_with(root)).collect();
let mut project = None;
for dir in ancestors.into_iter().rev() {
let Some(composer) = read(dir.join("composer.json")) else { continue };
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
let in_vendor = file.starts_with(&vendor);
project = Some((dir, vendor));
if in_vendor {
break;
}
}
let (dir, vendor) = project?;
if !vendor.join("autoload.php").is_file() {
return Some((dir.to_path_buf(), ComposerInstall::Missing));
}
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
let lock = read(dir.join("composer.lock"))?;
let installed = read(vendor.join("composer/installed.json")).unwrap_or(Value::Null);
// Composer 2 writes `{"packages": [...], "dev": bool}`, Composer 1 the list itself.
@@ -352,6 +361,32 @@ mod tests {
assert_eq!(composer_install(&root.join("other.php"), root), None, "outside the Composer project");
}
#[test]
fn composer_install_checks_the_owning_project_for_vendor_files() {
for (vendor, manifest) in [("vendor", "{}"), ("deps", r#"{"config":{"vendor-dir":"deps"}}"#)] {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let vendor = root.join(vendor);
let package = vendor.join("symfony/console");
let nested = root.join("apps/console");
for dir in [&package, &nested, &vendor.join("composer")] {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(root.join("composer.json"), manifest).unwrap();
std::fs::write(package.join("composer.json"), "{}").unwrap();
std::fs::write(nested.join("composer.json"), "{}").unwrap();
let file = package.join("Application.php");
assert_eq!(composer_install(&file, root), Some((root.to_path_buf(), ComposerInstall::Missing)));
std::fs::write(vendor.join("autoload.php"), "<?php").unwrap();
let packages = r#"{"packages":[{"name":"symfony/console","version":"v7.4.0"}]}"#;
std::fs::write(root.join("composer.lock"), packages).unwrap();
std::fs::write(vendor.join("composer/installed.json"), packages).unwrap();
assert_eq!(composer_install(&file, root), None);
assert_eq!(composer_install(&nested.join("Command.php"), root), Some((nested, ComposerInstall::Missing)));
}
}
fn level(composer: Option<&str>, explicit: &str) -> Option<String> {
levels(composer, explicit).0.map(|l| l.version)
}
+3
Переглянути файл
@@ -383,6 +383,9 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
u.companion = true;
}
}
for (tool, lang) in registry::LANGUAGE_CLIS {
map.entry(tool.to_string()).or_default().languages.push(lang.to_string());
}
for (plugin, host) in registry::PLUGIN_HOSTS {
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
map.entry(plugin.to_string()).or_default().languages = languages;
+25
Переглянути файл
@@ -210,6 +210,28 @@ pub static TOOLS: &[ToolSpec] = &[
needs: &[],
homepage: "https://cli.github.com",
},
// Run by the IDE on Swift files below a `.swiftlint.yml` (not a language server).
ToolSpec {
name: "swiftlint",
display: "SwiftLint",
kind: Cli,
commands: &["swiftlint"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "realm/SwiftLint" },
assets: &[
any_arch(Mac, "portable_swiftlint.zip"),
rule(Linux, X64, "swiftlint_linux_amd64.zip"),
rule(Linux, Arm64, "swiftlint_linux_arm64.zip"),
rule(Windows, X64, "SwiftLint.amd64.zip"),
rule(Windows, Arm64, "SwiftLint.arm64.zip"),
],
locate: &["swiftlint"],
},
fallback: None,
version: ver("swiftlint"),
needs: &[],
homepage: "https://realm.github.io/SwiftLint/",
},
ToolSpec {
name: "oxfmt",
display: "oxfmt",
@@ -1410,6 +1432,9 @@ pub static TOOLS: &[ToolSpec] = &[
pub const PLUGIN_HOSTS: &[(&str, &str)] =
&[("lombok", "jdtls"), ("css-modules-kit", "vtsls"), ("typescript-styled-plugin", "vtsls")];
/// Command-line tools the IDE runs on one language's files, listed with that language.
pub const LANGUAGE_CLIS: &[(&str, &str)] = &[("swiftlint", "Swift")];
pub fn find(name: &str) -> Option<&'static ToolSpec> {
TOOLS.iter().find(|t| t.name == name)
}
+9
Переглянути файл
@@ -1458,6 +1458,15 @@ fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
}
#[test]
fn swiftlint_is_an_installable_tool_of_swift() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 0");
let tool = env.tools().info("swiftlint", &[]).unwrap();
assert_eq!((tool.kind, tool.status, tool.can_install), (ToolKind::Cli, ToolStatus::Missing, true));
assert_eq!(tool.languages, ["Swift"]);
}
#[test]
fn an_npm_tsserver_plugin_is_installed_at_its_pinned_version_only() {
let env = Env::new();
+7 -1
Переглянути файл
@@ -12,7 +12,9 @@ OpenIDEA supports C, C++, Objective-C and Objective-C++ through [clangd](https:/
| Objective-C | `.m` | clangd | lldb-dap |
| Objective-C++ | `.mm` | clangd | lldb-dap |
`.h` files open as C. To treat headers as C++, change the association in **Settings › Editor › File Types**.
`.h` files open as C. To treat headers as C++, or Objective-C headers as Objective-C so the outline shows their `@interface` and `@protocol` blocks, change the association in **Settings › Editor › File Types**.
The outline of Objective-C files lists `@interface`, `@implementation` and `@protocol` blocks, categories, methods by selector (`initWithName:age:`), properties, instance variables, C functions and `#pragma mark` labels. Objective-C++ files use the same grammar, so their C++ declarations outside Objective-C blocks (namespaces, classes) are not listed.
## Language server
@@ -32,6 +34,10 @@ clangd needs the flags each file is compiled with. Without them it guesses, and
clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each. If your build directory has another name (for example `cmake-build-debug` from a CMake profile), add a `.clangd` file with `CompileFlags: { CompilationDatabase: cmake-build-debug }` or copy or link the file to the project root.
</Tip>
### Xcode projects
In a folder with a `buildServer.json` (the build server config for Xcode projects, see [Swift › Xcode projects](/en/languages/swift#xcode-projects)), C, C++, Objective-C and Objective-C++ files use sourcekit-lsp instead of clangd. sourcekit-lsp gets each file's flags from the build server and passes them to its own clangd, so headers on the target's search paths and the generated `<Module>-Swift.h` resolve. Swift and C-family files of the project share one sourcekit-lsp. A build server config only under `.bsp/` is not used for this, because sbt, Mill and Bazel write that folder too. Without `buildServer.json`, or when sourcekit-lsp is not installed, clangd serves the files as described above.
### Header and source
**Switch Header/Source** (in Find Action; `F10`, `⌥O` / `Alt+O` in the VS Code keymaps) opens the counterpart of the current file: `Foo.m` or `Foo.cpp` from `Foo.h`, and back. It asks clangd first (`textDocument/switchSourceHeader`, which also finds a source file in another folder). When clangd is not running for the file or has no answer, it opens a project file with the same name and a counterpart extension, preferring the same folder. **Related Symbol…** (`⌃⌘↑` / `Ctrl+Alt+Home`) lists every match by name instead.
+4 -2
Переглянути файл
@@ -147,8 +147,8 @@ The table lists every built-in language definition. Server and debugger names in
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
| MDX | `mdx` | `.mdx` | Yes | Yes | **mdx-language-server** | — |
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
| Objective-C | `objective-c` | `.m` | Yes | Yes | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | Yes | Yes | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
@@ -170,6 +170,7 @@ The table lists every built-in language definition. Server and debugger names in
| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — |
| Strings | `strings` | `.strings` | Yes | — | — | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — |
@@ -178,6 +179,7 @@ The table lists every built-in language definition. Server and debugger names in
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| Xcode Config | `xcconfig` | `.xcconfig` | Yes | — | — | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** |
+13 -1
Переглянути файл
@@ -1,6 +1,6 @@
---
title: "Swift"
description: "Swift code intelligence with sourcekit-lsp for SwiftPM and Xcode projects, formatting, single-file runs and debugging with lldb-dap."
description: "Swift code intelligence with sourcekit-lsp for SwiftPM and Xcode projects, formatting, SwiftLint, single-file runs and debugging with lldb-dap."
---
OpenIDEA supports Swift through [sourcekit-lsp](https://github.com/swiftlang/sourcekit-lsp), the language server that ships with the Swift toolchain. Highlighting, folding and the outline work without any setup. Completion, navigation, diagnostics, refactorings and formatting come from sourcekit-lsp. For the other languages, see the [support matrix](/en/languages/index).
@@ -90,6 +90,17 @@ Everything the IDE starts in the project gets it as `DEVELOPER_DIR`: sourcekit-l
**Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses sourcekit-lsp, which formats with [swift-format](https://github.com/swiftlang/swift-format) from the same toolchain. swift-format reads its options from a `.swift-format` file in the file's folder or a parent folder.
## SwiftLint
In a project with a `.swiftlint.yml`, the IDE checks Swift files with [SwiftLint](https://realm.github.io/SwiftLint/) as you type and shows its findings as warnings and errors in the editor and in the **Problems** tool window, with the rule name (for example `line_length`) as the code.
- **Configuration**: SwiftLint runs in the folder of the `.swiftlint.yml` nearest to the file, up to the project folder, and uses that file. Swift files below no `.swiftlint.yml` in the project are not checked.
- **Saved and unsaved text**: an opened or saved file is checked by its path, so the configuration's `excluded` paths and nested configurations apply. Unsaved edits are sent to SwiftLint through stdin (`--use-stdin`), which checks them against the nearest configuration only; a file that `excluded` lists stays unchecked while you edit it.
- **Installing**: the IDE runs the `swiftlint` it finds on `PATH` or in its tools folder, and never installs it on its own. Install it with `brew install swiftlint`, or with **Install** next to SwiftLint (under Swift, **Command-Line Tools**) in **Settings › Languages & Frameworks › Language Servers**. When `swiftlint` is missing in a project that has a `.swiftlint.yml`, the IDE says so once.
- **Restricted Mode**: SwiftLint does not run in projects you have not trusted.
To fix what SwiftLint can correct, run `swiftlint --fix` in the terminal. The IDE does not offer SwiftLint quick fixes yet.
## Run and debug
### Single files
@@ -127,3 +138,4 @@ To debug another Swift executable, add a **Program** configuration with **Execut
- **Expand Macro** does nothing: sourcekit-lsp shows the expansion in a new document, which the IDE does not open yet.
- There is no SwiftUI Preview, Interface Builder, asset catalog editor or simulator integration. Use Xcode for those.
- sourcekit-lsp and lldb-dap are not installed by the IDE.
- SwiftLint findings have no quick fixes; run `swiftlint --fix` yourself.
+7 -1
Переглянути файл
@@ -12,7 +12,9 @@ OpenIDEA 通过 [clangd](https://clangd.llvm.org) 支持 C、C++、Objective-C
| Objective-C | `.m` | clangd | lldb-dap |
| Objective-C++ | `.mm` | clangd | lldb-dap |
`.h` 文件默认按 C 打开。如果希望头文件按 C++ 处理,在 **设置 › 编辑器 › 文件类型** 中修改关联。
`.h` 文件默认按 C 打开。如果希望头文件按 C++ 处理,或把 Objective-C 头文件按 Objective-C 处理(这样结构视图能列出其中的 `@interface` 和 `@protocol`),在 **设置 › 编辑器 › 文件类型** 中修改关联。
Objective-C 文件的结构视图列出 `@interface`、`@implementation`、`@protocol` 块、分类(category)、按选择器命名的方法(`initWithName:age:`)、属性、实例变量、C 函数和 `#pragma mark` 标记。Objective-C++ 文件使用同一个语法,因此 Objective-C 块之外的 C++ 声明(命名空间、类)不会列出。
## 语言服务器
@@ -32,6 +34,10 @@ clangd 需要知道每个文件的编译参数,否则只能猜测,常见的
clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`。如果构建目录叫别的名字(例如 CMake 配置生成的 `cmake-build-debug`),在项目根目录添加一个 `.clangd`,写上 `CompileFlags: { CompilationDatabase: cmake-build-debug }`,或者把该文件复制或链接到项目根目录。
</Tip>
### Xcode 项目
文件夹里有 `buildServer.json`(Xcode 项目的构建服务器配置,见 [Swift › Xcode 项目](/zh/languages/swift#xcode-项目))时,C、C++、Objective-C 和 Objective-C++ 文件改由 sourcekit-lsp 处理,不再用 clangd。sourcekit-lsp 从构建服务器拿到每个文件的编译参数,再交给它自带的 clangd,因此 target 搜索路径里的头文件和生成的 `<Module>-Swift.h` 都能找到。同一项目的 Swift 文件和 C 系文件共用一个 sourcekit-lsp。只放在 `.bsp/` 下的构建服务器配置不在此列,因为 sbt、Mill 和 Bazel 也会写这个文件夹。没有 `buildServer.json`,或者没有安装 sourcekit-lsp 时,仍由 clangd 处理,方式同上。
### 头文件与源文件
**切换头文件/源文件**(可在“查找操作”中运行;`F10`,VS Code 键位下为 `⌥O` / `Alt+O`)打开当前文件对应的另一半:在 `Foo.h` 中打开 `Foo.m` 或 `Foo.cpp`,反之亦然。它先询问 clangd(`textDocument/switchSourceHeader`,能找到放在其他文件夹里的源文件);clangd 没有为该文件运行或没有给出结果时,打开项目中同名、扩展名对应的文件,优先同一文件夹。**相关符号…**(`⌃⌘↑` / `Ctrl+Alt+Home`)则按名称列出所有匹配。
+4 -2
Переглянути файл
@@ -142,8 +142,8 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
| MDX | `mdx` | `.mdx` | 是 | 是 | **mdx-language-server** | — |
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
| Objective-C | `objective-c` | `.m` | 是 | 是 | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | 是 | 是 | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
@@ -165,6 +165,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — |
| Strings | `strings` | `.strings` | 是 | — | — | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — |
@@ -173,6 +174,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| Xcode Config | `xcconfig` | `.xcconfig` | 是 | — | — | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** |
+13 -1
Переглянути файл
@@ -1,6 +1,6 @@
---
title: "Swift"
description: "基于 sourcekit-lsp 的 Swift 代码智能(SwiftPM 与 Xcode 项目),代码格式化,单文件运行,以及用 lldb-dap 调试。"
description: "基于 sourcekit-lsp 的 Swift 代码智能(SwiftPM 与 Xcode 项目),代码格式化,SwiftLint,单文件运行,以及用 lldb-dap 调试。"
---
OpenIDEA 通过 Swift 工具链自带的语言服务器 [sourcekit-lsp](https://github.com/swiftlang/sourcekit-lsp) 支持 Swift。语法高亮、折叠和结构视图无需任何配置即可使用;补全、导航、诊断、重构和格式化由 sourcekit-lsp 提供。其他语言见[语言支持总览](/zh/languages/index)。
@@ -90,6 +90,17 @@ IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourc
**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)交给 sourcekit-lsp,它使用同一工具链中的 [swift-format](https://github.com/swiftlang/swift-format) 格式化。swift-format 从文件所在文件夹或上级文件夹中的 `.swift-format` 文件读取选项。
## SwiftLint
在有 `.swiftlint.yml` 的项目中,IDE 会在你输入时用 [SwiftLint](https://realm.github.io/SwiftLint/) 检查 Swift 文件,把结果作为警告和错误显示在编辑器和 **问题** 工具窗口中,并以规则名(例如 `line_length`)作为代码。
- **配置**:SwiftLint 在离文件最近的 `.swiftlint.yml` 所在文件夹中运行(最多向上找到项目文件夹),并使用这个文件。项目中不在任何 `.swiftlint.yml` 之下的 Swift 文件不检查。
- **已保存和未保存的文本**:打开或保存的文件按路径检查,因此配置中的 `excluded` 路径和嵌套配置会生效。未保存的编辑通过 stdin(`--use-stdin`)交给 SwiftLint,只按最近的配置检查;被 `excluded` 列出的文件在编辑时也不检查。
- **安装**:IDE 运行在 `PATH` 或自己的工具文件夹中找到的 `swiftlint`,不会自动安装。可以用 `brew install swiftlint` 安装,或在 **设置 › 语言和框架 › 语言服务器** 中 Swift 下的 **命令行工具** 里点 SwiftLint 旁的 **安装**。项目有 `.swiftlint.yml` 但找不到 `swiftlint` 时,IDE 会提示一次。
- **受限模式**:未信任的项目不运行 SwiftLint。
要修正 SwiftLint 能自动修正的问题,请在终端运行 `swiftlint --fix`。IDE 目前还不提供 SwiftLint 的快速修复。
## 运行和调试
### 单个文件
@@ -127,3 +138,4 @@ IDE 在项目中启动的所有进程都会以 `DEVELOPER_DIR` 得到它:sourc
- **Expand Macro** 不起作用:sourcekit-lsp 会在新文档中显示展开结果,而 IDE 目前还不会打开它。
- 没有 SwiftUI 预览、Interface Builder、资源目录编辑器和模拟器集成,这些请使用 Xcode。
- sourcekit-lsp 和 lldb-dap 不由 IDE 安装。
- SwiftLint 的结果没有快速修复,请自己运行 `swiftlint --fix`。
+65
Переглянути файл
@@ -0,0 +1,65 @@
import type { AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "composer-icons",
title: "Composer icons",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
for (const theme of ["light", "dark"] as const) {
test(`${theme}: Skills uses the same icon colour and size as peer composer actions`, async ({
workbench: page,
}, testInfo) => {
await page.evaluate(
async ({ task, theme }) => {
const storePath = "/src/features/agents/store.ts";
const themePath = "/src/workbench/theme.ts";
const store = await import(storePath);
await (await import(themePath)).setTheme(theme);
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, []]]),
sessionLocation: "editor",
});
store.openTask(task.id);
},
{ task, theme },
);
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
await page.getByRole("button", { name: "Add Context" }).click();
const menu = page.getByRole("menu", { name: "Add Context" });
const skills = menu.getByRole("menuitem", { name: "Skills…" });
const memory = menu.getByRole("menuitem", { name: "Memory…" });
const peerColour = await memory.locator("svg circle").evaluate((el) => getComputedStyle(el).stroke);
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
const peerSize = await memory.locator("svg").evaluate((el) => {
const { width, height } = getComputedStyle(el);
return { width, height };
});
await expect(skills.locator("svg")).toHaveCSS("width", peerSize.width);
await expect(skills.locator("svg")).toHaveCSS("height", peerSize.height);
await skills.hover();
await expect(skills.locator("svg path")).toHaveCSS("stroke", peerColour);
await menu.screenshot({ path: testInfo.outputPath("add-context.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await expect(menu).toBeHidden();
});
}
+78
Переглянути файл
@@ -284,6 +284,84 @@ async function expectNoSubmission(page: Page) {
expect(await ipcCalls(page, "agent_create")).toEqual([]);
}
test("effort descriptions share a column regardless of label and description length", async ({
workbench: page,
}, testInfo) => {
const values = [
["Low", "Fast responses with lighter reasoning"],
["Medium", "Balances speed and reasoning depth for everyday tasks"],
["High", "Greater reasoning depth for complex problems"],
["Extra high", "Extra high reasoning depth for complex problems"],
["Max", "Maximum reasoning depth for the hardest problems"],
["Ultra", "Maximum reasoning with automatic task delegation"],
];
const effort = {
...atlas,
current: "high",
values: values.map(([name, description]) => ({
value: name!.toLowerCase(),
name: name!,
description: description!,
})),
};
const fast = option(
"fast",
"model_config",
[
["false", "Off"],
["true", "On"],
],
"false",
);
fast.name = "Fast";
await seed(page, "editor", "task", "atlas", "ready", false, {
...provider,
thoughtLevels: { ...provider.thoughtLevels, atlas: [effort, fast] },
});
await effortLabel(page).click();
const dialog = page.getByRole("dialog", { name: "Model settings" });
const list = dialog.getByRole("listbox", { name: "Effort Level" });
await expect(list.getByRole("option")).toHaveCount(values.length);
await list.getByRole("option", { name: /^Low/ }).hover();
await dialog.screenshot({ path: testInfo.outputPath("effort-descriptions.png"), scale: "css" });
const columns = () =>
list.getByRole("option").evaluateAll((rows) =>
rows.map((row) => {
const label = row.querySelectorAll<HTMLElement>("[title]")[0]!.getBoundingClientRect();
const detail = row.querySelectorAll<HTMLElement>("[title]")[1]!.getBoundingClientRect();
return {
label: label.left,
labelWidth: label.width,
detail: detail.left,
detailRight: detail.right,
rowRight: row.getBoundingClientRect().right,
};
}),
);
const assertAligned = async () => {
const cells = await columns();
expect(cells).toHaveLength(values.length);
for (const cell of cells) {
expect(cell.label).toBeCloseTo(cells[0]!.label);
expect(cell.detail).toBeCloseTo(cells[0]!.detail);
expect(cell.detailRight).toBeLessThanOrEqual(cell.rowRight);
}
return cells[0]!.labelWidth;
};
const originalWidth = await assertAligned();
// The width is based on rendered text, not a hard-coded number of characters.
await dialog.evaluate((element) => {
element.style.fontSize = "18px";
});
await expect.poll(async () => (await columns())[0]!.labelWidth).toBeGreaterThan(originalWidth);
await assertAligned();
await dialog.evaluate((element) => {
element.style.width = "240px";
});
await expect.poll(async () => (await dialog.boundingBox())!.width).toBeCloseTo(240, 0);
await assertAligned();
});
for (const surface of ["new", "task"] as const) {
test(`${surface}: switch models from the list, then set effort and context from the settings chip`, async ({
workbench: page,
+167
Переглянути файл
@@ -0,0 +1,167 @@
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const base: AgentTask = {
id: "recovery-style",
title: "Recovery",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const question: AgentEntry = {
type: "question",
id: "question-style",
title: "Choose the implementation",
chosen: null,
questions: [
{
header: "Implementation",
question: "Which approach should I use?",
options: [
{
label: "Reuse existing controls (Recommended)",
description: "Keep the existing behavior and theme.",
preview: "Use shared Button and Input components.",
},
{
label: "Create a custom control",
description: "Requires additional maintenance.",
preview: "Introduce a new component.",
},
],
},
{
header: "Tests",
question: "Which tests should I run?",
multiSelect: true,
options: [
{ label: "Unit tests", description: "Run focused component tests." },
{ label: "Browser tests", description: "Verify the rendered workflow." },
],
},
],
};
for (const theme of ["light", "dark"] as const) {
test(`${theme}: agent recovery and question controls follow the workbench style`, async ({
workbench: page,
}, testInfo) => {
await page.evaluate(
async ({ base, question, theme }) => {
const storePath = "/src/features/agents/store.ts";
const themePath = "/src/workbench/theme.ts";
const store = await import(storePath);
await (await import(themePath)).setTheme(theme);
const recovery: AgentTask = { ...base, interrupted: { reason: "quit", atMs: Date.now() - 120_000 } };
const ask: AgentTask = { ...base, id: "ask-style", title: "Question" };
const entries: AgentEntry[] = [
{ type: "user", text: "Continue with the implementation.", attachments: [], recovery: "windowClose" },
{ type: "agent", text: "The implementation is ready to continue." },
];
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([
[recovery.id, recovery],
[ask.id, ask],
]),
entries: new Map([
[recovery.id, entries],
[ask.id, [question]],
]),
sessionLocation: "editor",
});
store.openTask(recovery.id);
},
{ base, question, theme },
);
const resume = page.getByRole("button", { name: "Resume", exact: true });
await expect(resume).toBeVisible();
const resumeColor = await resume.evaluate((el) => getComputedStyle(el).color);
await expect(resume.locator("svg path")).toHaveCSS("stroke", resumeColor);
const record = page.getByRole("separator").filter({ hasText: "Resumed after window close" });
const recordColor = await record.evaluate((el) => getComputedStyle(el).color);
await expect(record.locator("svg path")).toHaveCSS("stroke", recordColor);
await page
.getByRole("tabpanel", { name: "Recovery" })
.screenshot({ path: testInfo.outputPath("recovery.png"), animations: "disabled" });
await page.evaluate(async () => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
const tasks = new Map(useAgents.getState().tasks);
const current = tasks.get("recovery-style") as AgentTask;
tasks.set(current.id, {
...current,
status: "running",
interrupted: null,
retry: {
attempt: 1,
maxRetries: null,
retryAtMs: Date.now() + 30_000,
deadlineMs: Date.now() + 3_600_000,
error: "Connection lost",
},
});
useAgents.setState({ tasks });
});
const resumeNow = page.getByRole("button", { name: "Resume Now", exact: true });
await expect(resumeNow).toBeVisible();
await expect(resumeNow.locator("svg path")).toHaveCSS("stroke", resumeColor);
await page.evaluate(async () => {
const storePath = "/src/features/agents/store.ts";
(await import(storePath)).openTask("ask-style");
});
const card = page.getByRole("form", { name: "Choose the implementation" });
await expect(card).toBeVisible();
await expect(card.getByRole("button", { name: "Submit" })).toBeDisabled();
const buttonHeight = await card
.getByRole("button", { name: "Submit" })
.evaluate((el) => getComputedStyle(el).height);
await expect(card.getByRole("button", { name: "Next" })).toHaveCSS("height", buttonHeight);
await expect(card.getByRole("button", { name: "Previous" })).toHaveCSS("height", buttonHeight);
await expect(card.getByText("Implementation", { exact: true })).toHaveCount(1);
const choice = card.getByRole("radio", { name: /^Reuse existing controls/ });
const row = choice.locator("xpath=ancestor::label");
await expect(row).toHaveCSS("border-top-width", "0px");
await card.screenshot({ path: testInfo.outputPath("question.png"), animations: "disabled" });
await row.click();
await expect(card.getByRole("tab", { name: "Tests" })).toHaveAttribute("aria-selected", "true");
const checkbox = card.getByRole("checkbox", { name: /^Unit tests/ });
const checkboxRow = checkbox.locator("xpath=ancestor::label");
await checkboxRow.click();
await expect(checkbox).toBeChecked();
const selectionColor = await page.evaluate(() => {
const probe = document.createElement("span");
probe.style.backgroundColor = "var(--bg-tree-selected)";
document.body.append(probe);
const color = getComputedStyle(probe).backgroundColor;
probe.remove();
return color;
});
await expect(checkboxRow).toHaveCSS("background-color", selectionColor);
await expect(card.getByRole("button", { name: "Submit" })).toBeEnabled();
await card.screenshot({ path: testInfo.outputPath("question-selected.png"), animations: "disabled" });
await page.setViewportSize({ width: 900, height: 800 });
const composer = card.locator("xpath=following-sibling::div[1]").locator("[data-owns-file-drop]:visible");
const cardBounds = await card.boundingBox();
const composerBounds = await composer.boundingBox();
expect(cardBounds).not.toBeNull();
expect(composerBounds).not.toBeNull();
expect(Math.abs(cardBounds!.x - composerBounds!.x)).toBeLessThan(2);
expect(Math.abs(cardBounds!.width - composerBounds!.width)).toBeLessThan(2);
await card.screenshot({ path: testInfo.outputPath("question-narrow.png"), animations: "disabled" });
});
}
+8 -1
Переглянути файл
@@ -8,7 +8,7 @@ async function selectPage(page: Page, id: string) {
}, id);
}
test("Git settings expose fetch tag modes and the check-only mode", async ({ workbench: page }) => {
test("Git settings expose fetch tag modes and the check-only mode", async ({ workbench: page }, testInfo) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
@@ -20,6 +20,13 @@ test("Git settings expose fetch tag modes and the check-only mode", async ({ wor
for (const label of ["Auto", "Sync", "Always", "Never"]) {
await expect(choices.getByRole("option", { name: new RegExp(`^${label}`) })).toBeVisible();
}
const starts = await choices
.getByRole("option")
.evaluateAll((rows) =>
rows.map((row) => row.querySelectorAll<HTMLElement>("[title]")[1]!.getBoundingClientRect().left),
);
for (const start of starts) expect(start).toBeCloseTo(starts[0]!);
await choices.screenshot({ path: testInfo.outputPath("fetch-tags-descriptions.png") });
const sync = choices.getByRole("option", { name: /^Sync/ });
await expect(sync).toContainText("Delete local tags missing on remote");
await sync.click();
+12
Переглянути файл
@@ -0,0 +1,12 @@
import "../src/styles/tokens.css";
import { EditorView } from "@codemirror/view";
import { syntaxHighlighting } from "@codemirror/language";
import { openideaHighlightStyle } from "../src/editor/core/cm/highlight";
import { vueLanguage } from "../src/editor/core/cm/vue";
document.documentElement.dataset.theme = new URLSearchParams(location.search).get("theme") ?? "dark";
new EditorView({
parent: document.body,
doc: '<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n',
extensions: [vueLanguage(), syntaxHighlighting(openideaHighlightStyle)],
});
+9
Переглянути файл
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="./vueHighlight.fixture.ts"></script>
</body>
</html>
+14
Переглянути файл
@@ -0,0 +1,14 @@
import { expect, test } from "@playwright/test";
for (const [theme, custom, tag] of [
["dark", "rgb(47, 186, 163)", "rgb(213, 183, 120)"],
["light", "rgb(178, 29, 191)", "rgb(0, 51, 179)"],
] as const) {
test(`Vue component tags have the custom tag colour (${theme})`, async ({ page }) => {
await page.goto(`/e2e/vueHighlight.html?theme=${theme}`);
const line = page.locator(".cm-line").nth(1);
await expect(line.getByText("Icon", { exact: true })).toHaveCSS("color", custom);
await expect(line.getByText("el-input", { exact: true }).first()).toHaveCSS("color", custom);
await expect(line.getByText("div", { exact: true }).first()).toHaveCSS("color", tag);
});
}
+12
Переглянути файл
@@ -15,6 +15,18 @@ int main(void) {
}
'''
[[language-servers]]
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
# sourcekit-lsp reads them through the build server and serves C-family files with its
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
# `.bsp` directory also belongs to sbt, Mill and Bazel.
name = "sourcekit-lsp"
command = "sourcekit-lsp"
root-markers = ["buildServer.json"]
require-root-marker = true
replaces = ["clangd"]
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
[[language-servers]]
name = "clangd"
command = "clangd"
+12
Переглянути файл
@@ -19,6 +19,18 @@ int main() {
[rainbow-brackets]
angle = ["TemplateArgumentList", "TemplateParameterList"]
[[language-servers]]
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
# sourcekit-lsp reads them through the build server and serves C-family files with its
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
# `.bsp` directory also belongs to sbt, Mill and Bazel.
name = "sourcekit-lsp"
command = "sourcekit-lsp"
root-markers = ["buildServer.json"]
require-root-marker = true
replaces = ["clangd"]
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
[[language-servers]]
name = "clangd"
command = "clangd"
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
id = "json"
name = "JSON"
formatter = { tool = "prettier", parser = "json", range = true }
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"]
extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin", "xcstrings"]
filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "JSON"
+13
Переглянути файл
@@ -5,6 +5,19 @@ line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = true }
ui-mode = "Objective-C"
tree-sitter = "objc"
[[language-servers]]
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
# sourcekit-lsp reads them through the build server and serves C-family files with its
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
# `.bsp` directory also belongs to sbt, Mill and Bazel.
name = "sourcekit-lsp"
command = "sourcekit-lsp"
root-markers = ["buildServer.json"]
require-root-marker = true
replaces = ["clangd"]
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
[[language-servers]]
name = "clangd"
+13
Переглянути файл
@@ -5,6 +5,19 @@ line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = true }
ui-mode = "Objective-C++"
tree-sitter = "objc"
[[language-servers]]
# Xcode projects with a BSP config: plain clangd finds no compile flags there, while
# sourcekit-lsp reads them through the build server and serves C-family files with its
# own clangd. Only `buildServer.json` (xcode-build-server, sourcekit-xcode-bsp): a bare
# `.bsp` directory also belongs to sbt, Mill and Bazel.
name = "sourcekit-lsp"
command = "sourcekit-lsp"
root-markers = ["buildServer.json"]
require-root-marker = true
replaces = ["clangd"]
install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); https://www.swift.org/install"
[[language-servers]]
name = "clangd"
+8
Переглянути файл
@@ -0,0 +1,8 @@
id = "strings"
name = "Strings"
extensions = ["strings"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = true }
# Apple `.strings`: `"key" = "value";` with C comments, so the C mode colours it.
ui-mode = "C"
+7
Переглянути файл
@@ -0,0 +1,7 @@
id = "xcconfig"
name = "Xcode Config"
extensions = ["xcconfig"]
line-comment = "//"
indent = { tab-size = 4, insert-spaces = true }
# C-like: `//` comments, `#include` directives and quoted values.
ui-mode = "C"
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
id = "xml"
name = "XML"
extensions = ["xml", "xsd", "xsl", "xslt", "svg", "plist", "csproj", "fsproj", "vbproj", "props", "targets", "nuspec", "xaml", "resx", "wsdl", "fxml", "iml", "jnlp", "rss", "atom", "xliff", "xlf", "storyboard", "xib", "tld", "pom"]
extensions = ["xml", "xsd", "xsl", "xslt", "svg", "plist", "entitlements", "xcprivacy", "csproj", "fsproj", "vbproj", "props", "targets", "nuspec", "xaml", "resx", "wsdl", "fxml", "iml", "jnlp", "rss", "atom", "xliff", "xlf", "storyboard", "xib", "tld", "pom"]
filenames = ["NuGet.Config", "Directory.Build.targets", "web.config", "app.config"]
first-line = "^<\\?xml\\b"
block-comment = ["<!--", "-->"]
+1
Переглянути файл
@@ -60,6 +60,7 @@
"--syn-escape": "#7fd1c4",
"--syn-regexp": "#7fd1c4",
"--syn-tag": "#e0a46e",
"--syn-custom-tag": "#8fd4c9",
"--syn-attribute": "#9fc0e8",
"--syn-todo": "#7fd1c4",
"--syn-link": "#6fc3df",
+2
Переглянути файл
@@ -138,6 +138,8 @@
"--bg-search-match": "#ba9752",
"--bg-search-match-current": "#f2c55c",
"--fg-search-match": "#14171c",
"--bg-list-match": "#ba9752",
"--fg-list-match": "#14171c",
"--bg-dialog": "#14171c",
"--bg-popup-inline": "#1f252e",
"--bg-popup-advertiser": "#1f252e",
+4 -1
Переглянути файл
@@ -333,7 +333,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
272 themeable tokens: 126 in the UI theme file, 146 in the editor colour scheme file.
275 themeable tokens: 128 in the UI theme file, 147 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -482,6 +482,7 @@ a token.
| `--syn-escape` | `#cf8e6d` | `#0037a6` |
| `--syn-regexp` | `#42c3d4` | `#264eff` |
| `--syn-tag` | `#d5b778` | `#0033b3` |
| `--syn-custom-tag` | `#2fbaa3` | `#b21dbf` |
| `--syn-attribute` | `#bcbec4` | `#174ad4` |
| `--syn-todo` | `#8bb33d` | `#008dde` |
| `--syn-link` | `#548af7` | `#006dcc` |
@@ -662,6 +663,8 @@ a token.
| `--bg-search-match` | `#ba9752` | `#fee6b1` |
| `--bg-search-match-current` | `#f2c55c` | `#fcd47e` |
| `--fg-search-match` | `#191a1c` | `#000000` |
| `--bg-list-match` | `#ba9752` | `#fee6b1` |
| `--fg-list-match` | `#191a1c` | `#000000` |
| `--bg-dialog` | `#191a1c` | `#f7f8f9` |
| `--bg-popup-inline` | `#26282c` | `#f7f8f9` |
| `--bg-popup-advertiser` | `#26282c` | `#f7f8f9` |
+13 -5
Переглянути файл
@@ -973,9 +973,9 @@ export const commands = {
iosSimulatorOpenApp: () => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_open_app")),
iosSimulatorShutdown: (udid: string) => typedError<null, IdeError>(__TAURI_INVOKE("ios_simulator_shutdown", { udid })),
/**
* The available iOS simulators, booted first; `None` outside macOS or when the project has no
* Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
* no change feed, and one listing takes a fraction of a second.
* The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
* macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
* the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
*/
iosSimulators: () => typedError<IosSimulator[] | null, IdeError>(__TAURI_INVOKE("ios_simulators")),
/** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */
@@ -10044,14 +10044,22 @@ export type InvalidateCachesOptions = {
buildCaches?: boolean,
};
/** One simulator `simctl list devices available` reports. */
/**
* One simulator `simctl list devices available` reports, or one physical device
* `devicectl list devices` knows.
*/
export type IosSimulator = {
udid: string,
name: string,
/** The runtime, as Xcode shows it: `iOS 27.0`. */
runtime: string,
/** `Booted`, `Shutdown`, `Booting`, `Shutting Down`. */
/**
* `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
* [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
*/
state: string,
/** An iPhone or iPad rather than a simulator. */
physical: boolean,
};
/** A binary argument or result of an IPC command. */
+3 -2
Переглянути файл
@@ -543,9 +543,10 @@ export type ContributedFormatter = (
state: EditorState,
range: { from: number; to: number } | null,
) => Array<{ from: number; to: number; insert: string }>;
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. May be async when
* the answer needs a lookup; `false` hands the position back to the language server. */
export interface ContributedDefinition {
(view: EditorView, pos: number): boolean;
(view: EditorView, pos: number): boolean | Promise<boolean>;
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
canHandle?(state: EditorState, pos: number): boolean;
}
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { isCustomTagName } from "./customTags";
import { vueLanguage } from "./vue";
describe("Vue custom tag names", () => {
it("are PascalCase or hyphenated names", () => {
expect(["Icon", "el-input", "router-view", "MyButton"].map(isCustomTagName)).toEqual([true, true, true, true]);
expect(["div", "template", "span", "slot"].map(isCustomTagName)).toEqual([false, false, false, false]);
});
it("get their own colour in templates, opening and closing tags alike", () => {
const doc = `<template>\n <div><Icon /><el-input v-model="x"></el-input></div>\n</template>\n<script setup>\nconst a = 1 < 2\n</script>\n`;
const view = new EditorView({
state: EditorState.create({ doc, extensions: vueLanguage() }),
parent: document.body,
});
ensureSyntaxTree(view.state, doc.length, 5000);
view.dispatch({}); // let the plugin see the finished tree
const marked = [...view.dom.querySelectorAll(".cm-customTagName")].map((el) => el.textContent);
view.destroy();
expect(marked).toEqual(["Icon", "el-input", "el-input"]);
});
});
+52
Переглянути файл
@@ -0,0 +1,52 @@
/**
* WebStorm's "Custom tag name" colour: component tags in Vue templates (`<Icon>`, `<el-input>`)
* stand apart from HTML elements (`--syn-custom-tag`, the tag colour when a theme has none).
*/
import { syntaxTree } from "@codemirror/language";
import { RangeSetBuilder } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
const customTag = Decoration.mark({ class: "cm-customTagName" });
/** A component, not an HTML element: PascalCase (`Icon`), or a custom-element name with a hyphen. */
export function isCustomTagName(name: string): boolean {
return /^[A-Z]/.test(name) || name.includes("-");
}
function decorations(view: EditorView): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
const tree = syntaxTree(view.state);
for (const { from, to } of view.visibleRanges) {
tree.iterate({
from,
to,
enter: (node) => {
if (node.name !== "TagName") return;
if (isCustomTagName(view.state.sliceDoc(node.from, node.to))) builder.add(node.from, node.to, customTag);
},
});
}
return builder.finish();
}
const plugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = decorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged || syntaxTree(update.state) !== syntaxTree(update.startState))
this.decorations = decorations(update.view);
}
},
{ decorations: (p) => p.decorations },
);
/** Colours component tag names in a template (the syntax highlighting's tag span inside included). */
export const customTagNames = [
plugin,
EditorView.baseTheme({
".cm-customTagName, .cm-customTagName *": { color: "var(--syn-custom-tag, var(--syn-tag))" },
}),
];
+3 -1
Переглянути файл
@@ -9,6 +9,7 @@ import { html } from "@codemirror/lang-html";
import { lessLanguage } from "@codemirror/lang-less";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
import { customTagNames } from "./customTags";
import { VERSIONED_SCRIPT_TYPES } from "./htmlScripts";
/**
@@ -41,5 +42,6 @@ export function vueLanguage(): LanguageSupport {
],
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
return vue({ base: new LanguageSupport(language, base.support) });
const support = vue({ base: new LanguageSupport(language, base.support) });
return new LanguageSupport(support.language, [support.support, customTagNames]);
}
+5 -1
Переглянути файл
@@ -514,7 +514,11 @@ async function gotoResolved(
// positions they do not own, so try every one instead of letting the first false
// result hide the real target.
const own = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
if (own.some((definition) => definition(view, offset))) return;
const anyHandled = async (index: number): Promise<boolean> => {
if (index >= own.length) return false;
return (await own[index]!(view, offset)) || anyHandled(index + 1);
};
if (await anyHandled(0)) return;
if (showPhpConstructDocumentation(view, offset)) return;
const before = view.state.doc;
const plugin = await contributedNavigation(view, offset).catch(() => null);
+11
Переглянути файл
@@ -87,6 +87,17 @@ describe("syntax errors without a language server", () => {
expect(last()).toBeUndefined();
});
it.each([
["objective-c", "/p/Person.m"],
["objective-cpp", "/p/Bridge.mm"],
])("skips %s, whose Apple macros and C++ the grammar misreads", async (language, path) => {
vi.useFakeTimers();
servers = [{ status: "missing", languages: [language] }];
open({ ...ctx, path, language });
await settle();
expect(last()).toBeUndefined();
});
it("leaves them to a running server, and checks again when the server stops", async () => {
vi.useFakeTimers();
servers = [{ status: "ready", languages: ["php"] }];
+12 -2
Переглянути файл
@@ -17,9 +17,19 @@ import { docOf } from "./lsp";
const INSPECT_DELAY = 500;
/**
* Dialects the grammar doesn't follow: the database support checks SQL, and Django and Jinja templates
* borrow the HTML grammar, which reads `{% if a > b %}` as broken markup.
* borrow the HTML grammar, which reads `{% if a > b %}` as broken markup. The Objective-C grammar
* misreads Apple's macros (`NS_ASSUME_NONNULL_BEGIN`, `typedef NS_ENUM(...)`) and, for Objective-C++,
* all C++.
*/
const SKIPPED = new Set(["sql", "plaintext", "django-html", "jinja-html", "helm-template"]);
const SKIPPED = new Set([
"sql",
"plaintext",
"django-html",
"jinja-html",
"helm-template",
"objective-c",
"objective-cpp",
]);
const RUNNING: ReadonlySet<ServerStatus> = new Set<ServerStatus>(["starting", "ready", "busy"]);
let checked: Promise<ReadonlySet<string>> | null = null;
+1
Переглянути файл
@@ -1542,6 +1542,7 @@ function AgentDefaults({
<div className={styles.select}>
<Select
id={`agent-default-${agent.id}-${o.id}`}
alignDetails
value={currentChoice}
options={[
{ value: "", label: defaultLabel },
+30
Переглянути файл
@@ -658,6 +658,36 @@ describe("Agents pinned and grouped tasks", () => {
}
};
it("keeps Pinned and active status groups stable when activity timestamps change", () => {
const tasks = new Map(
[
{ ...task("pin-first"), createdMs: 10, updatedMs: 10 },
{ ...task("pin-second"), createdMs: 20, updatedMs: 20 },
{ ...task("ready-new"), createdMs: 40, updatedMs: 40 },
{ ...task("ready-old"), createdMs: 30, updatedMs: 30 },
].map((t) => [t.id, t]),
);
useAgents.setState({ tasks, organize: { groups: [], groupOf: {}, pinned: ["pin-first", "pin-second"] } });
setup();
const visibleIds = () =>
Array.from(document.querySelectorAll<HTMLElement>("[data-tree-key]"))
.map((el) => el.dataset.treeKey)
.filter((k) => k && !k.startsWith("g:") && k !== "pinned");
expect(visibleIds()).toEqual(["pin-first", "pin-second", "ready-new", "ready-old"]);
// Activity updates on older/later-pinned tasks do not reshuffle either section.
act(() => {
const next = new Map(useAgents.getState().tasks);
next.set("pin-second", { ...next.get("pin-second")!, updatedMs: 999 });
next.set("ready-old", { ...next.get("ready-old")!, updatedMs: 999 });
useAgents.setState({ tasks: next });
});
expect(visibleIds()).toEqual(["pin-first", "pin-second", "ready-new", "ready-old"]);
});
it("reorders tasks within a section by dragging before or after a sibling", () => {
const tasks = new Map(
[
+2 -2
Переглянути файл
@@ -458,7 +458,7 @@ export function AgentsView() {
}
return [];
};
const rowButton = (label: string, icon: "pin" | "archive" | "resume", run: () => void) => (
const rowButton = (label: string, icon: "pin" | "archive" | "agent-resume", run: () => void) => (
<button
type="button"
className={styles.rowAction}
@@ -645,7 +645,7 @@ export function AgentsView() {
)}
<span className={styles.rowActions}>
{(interrupted || isWaitingForNetwork(n.task)) &&
rowButton("Resume", "resume", () => void executeAction("agents.resumeTasks", [n.task.id]))}
rowButton("Resume", "agent-resume", () => void executeAction("agents.resumeTasks", [n.task.id]))}
{pinned.has(n.task.id)
? rowButton("Unpin", "pin", () => pinTasks([n.task.id], false))
: rowButton("Pin", "pin", () => pinTasks([n.task.id], true))}
+3
Переглянути файл
@@ -450,6 +450,7 @@ function ConfigPicker({
? modeIcon(opt.value)
: undefined,
}))}
alignDetails
searchable={option.category === "model"}
onChange={(v) => onChange(option.id, v)}
renderValue={
@@ -583,6 +584,7 @@ function ModelPicker({
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
alignDetails
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
@@ -661,6 +663,7 @@ function ModelSettings({
</span>
<SelectListbox
aria-label={label}
alignDetails
value={currentValue}
options={o.values.map((v) => agentValueOption(v))}
onChoose={(v) => {
+2 -1
Переглянути файл
@@ -224,7 +224,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", run: openSkills },
{ id: "skills", label: "Skills…", icon: "skills", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", run: openMemory },
]
: undefined
@@ -335,6 +335,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
<Select
variant="ghost"
aria-label="Isolation"
alignDetails
value={isolation}
options={[
{
+1
Переглянути файл
@@ -37,6 +37,7 @@ export function ImagePreview({ image, onClose }: { image: AgentImage | null; onC
src={imageSrc(image)}
alt={image.name ?? tx("Image")}
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
showContextMenu(event, [{ kind: "action", action: copyImageAction.id, arg: target }]);
}}
+2 -2
Переглянути файл
@@ -21,7 +21,7 @@ afterEach(() => {
it("offers Copy Image on thumbnail right-click without opening the preview", () => {
render(<ImageStrip images={[image]} />);
fireEvent.contextMenu(screen.getByRole("img"));
expect(fireEvent.contextMenu(screen.getByRole("img"))).toBe(false);
expect(mocks.menu).toHaveBeenCalledWith(expect.anything(), [
{ kind: "action", action: "agents.copyImage", arg: { image } },
]);
@@ -47,7 +47,7 @@ it("copies from the full preview and confirms success without closing it", async
expect(dialog).toBeInTheDocument();
act(() => vi.advanceTimersByTime(2000));
expect(screen.getByRole("button", { name: "Copy Image" })).toBeInTheDocument();
fireEvent.contextMenu(dialog.querySelector("img")!);
expect(fireEvent.contextMenu(dialog.querySelector("img")!)).toBe(false);
expect(mocks.menu).toHaveBeenCalledWith(expect.anything(), [
expect.objectContaining({ action: "agents.copyImage", arg: expect.objectContaining({ image }) }),
]);
+1
Переглянути файл
@@ -29,6 +29,7 @@ export function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemov
setOpen(img);
}}
onContextMenu={(event) => {
event.preventDefault();
event.stopPropagation();
showContextMenu(event, [{ kind: "action", action: copyImageAction.id, arg: { image: img } }]);
}}
+164 -44
Переглянути файл
@@ -28,9 +28,15 @@
.fitWidth .stream > * {
width: 100%;
}
.fitWidth .userMessage > .user {
.fitWidth .userMessage > .user,
.fitWidth .userMessage > .editCard,
.fitWidth .userMessage > .editNote,
.fitWidth .userMessage > .editError {
max-width: var(--session-card-width);
}
.fitWidth .userMessage > .editCard {
width: var(--edit-width, var(--session-card-width));
}
.fitWidth .composerArea {
max-width: none;
}
@@ -149,19 +155,24 @@
color: var(--fg-subtle);
}
/* The archived / interrupted / waiting-for-network notice above the conversation. */
/* Inset session notices share the composer and permission card geometry. */
.banner {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
min-height: 36px;
padding: 9px 12px;
min-height: calc(var(--h-control) + var(--space-2) * 2);
padding: var(--space-1-5) var(--space-2);
background: var(--bg-feedback-warning);
border-bottom: 1px solid var(--border-feedback-warning);
border: 1px solid var(--border-feedback-warning);
border-radius: var(--radius-control);
color: var(--fg-strong);
}
.bannerNeutral {
background: var(--bg-elev);
border-color: var(--border-strong);
}
.bannerIcon {
flex: none;
color: var(--warning);
@@ -179,7 +190,9 @@
font-size: var(--fs-small);
}
.bannerActions {
flex: none;
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -206,9 +219,7 @@
align-items: center;
gap: var(--space-1-5);
padding: 2px var(--space-2);
border: 1px solid var(--border);
border-radius: var(--radius-small);
background: var(--bg-elev);
--icon-color: currentColor;
}
/* The conversation with its find bar. */
@@ -338,6 +349,15 @@
width: fit-content;
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .editCard {
width: var(--edit-width, min(var(--session-card-width), 720px));
min-width: min(100%, 220px);
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .editNote,
.userMessage > .editError {
max-width: min(var(--session-card-width), 720px);
}
.userMessage > .messageHead {
justify-content: flex-end;
}
@@ -518,33 +538,131 @@
overflow-wrap: anywhere;
}
/* In-place bubble editor: matches the Islands composer frame and keeps the text origin fixed. */
.editCard {
box-sizing: border-box;
display: flex;
flex-direction: column;
border-radius: var(--radius-tab);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
transition:
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.editCard:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
@media (prefers-reduced-motion: reduce) {
.editCard {
transition: none;
}
}
.editField {
display: grid;
grid-template-columns: minmax(0, 1fr);
min-width: 0;
max-height: 280px;
}
.editMirror,
.editMessage {
grid-area: 1 / 1;
min-width: 0;
margin: 0;
padding: 6px 10px 4px;
border: 0;
font: inherit;
line-height: 1.4;
white-space: pre-wrap;
overflow-wrap: anywhere;
box-sizing: border-box;
}
.editMirror {
visibility: hidden;
pointer-events: none;
max-height: 280px;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
}
.editMessage {
width: 100%;
box-sizing: border-box;
padding: 6px 8px;
resize: vertical;
font: inherit;
height: 100%;
min-height: 0;
overflow-y: auto;
resize: none;
background: transparent;
color: var(--fg-strong);
background: var(--bg-input);
border: 1px solid var(--accent);
border-radius: var(--radius-control);
caret-color: var(--fg-strong);
outline: none;
}
.editBar {
.editImages {
padding: 0 10px 4px;
}
.editImages .images {
margin-top: 0;
}
.editFooter {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
margin-top: 6px;
font-size: var(--fs-small);
padding: 2px 6px 6px 10px;
cursor: default;
}
.editHint {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
color: var(--fg-faint);
font-size: var(--fs-tiny, 11px);
-webkit-user-select: none;
user-select: none;
}
.editHint kbd {
display: inline-grid;
place-items: center;
min-width: 16px;
height: 16px;
padding: 0 3px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-family: var(--font-keys, inherit);
font-size: var(--fs-tiny, 11px);
}
.editButtons {
display: flex;
gap: var(--space-1-5);
display: inline-flex;
align-items: center;
gap: var(--space-1);
margin-left: auto;
}
.editError {
margin-top: var(--space-1-5);
font-size: var(--fs-small);
}
.editNote {
margin-top: var(--space-1);
color: var(--fg-subtle);
font-size: var(--fs-small);
line-height: 1.35;
text-align: right;
}
.markdown {
line-height: 1.4;
overflow-wrap: anywhere;
@@ -1620,12 +1738,12 @@
text-overflow: ellipsis;
}
/* An open AskUserQuestion: every question with its options, answered at once in the conversation. */
/* Questions and forms use the same inset selection rows as the workbench lists. */
.questionCard {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 12px;
padding: var(--space-3);
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
background: var(--bg-elev);
@@ -1639,12 +1757,11 @@
min-height: 0;
max-height: 50vh;
overflow-y: auto;
width: 100%;
width: calc(100% - var(--space-3) * 2);
max-width: var(--session-content-width);
margin: 0 auto 8px;
}
.fitWidth .questionCardPinned {
width: calc(100% - var(--space-3) * 2);
max-width: none;
}
.questionTabCheck {
@@ -1679,43 +1796,43 @@
border: 0;
}
.questionText {
margin-bottom: 6px;
margin-bottom: var(--space-1-5);
padding: 0;
color: var(--fg-strong);
font-weight: 600;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.questionTag {
margin: 0 8px 0 0;
padding: 1px 6px;
margin: 0 var(--space-2) 0 0;
padding: 1px var(--space-1-5);
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
font-weight: 400;
}
.questionLabel .questionTag {
margin: 0 0 0 8px;
margin: 0 0 0 var(--space-2);
}
.question .questionOption {
display: flex;
align-items: flex-start;
padding: 8px 10px;
border-radius: var(--radius-row);
min-height: var(--h-list-row);
padding: var(--space-1-5) var(--space-2);
border-radius: var(--radius-selection);
}
/* Each option is a card of its own: separate targets, not one list with hairlines. */
.question .questionChoices > * {
border: 1px solid var(--border);
border-radius: var(--radius-row);
.question .questionOption:not(:has(input:disabled)):hover {
background: var(--bg-tree-hover);
}
.question .questionChoices > *:hover {
border-color: var(--border-strong);
.question .questionOption:has(input:checked) {
background: var(--bg-tree-selected);
}
.question .questionChoices > *:has(input:checked) {
border-color: var(--accent);
background: var(--bg-hover);
.question .questionOption:has(input:checked):hover {
background: var(--bg-tree-selected);
}
.question .questionOption:hover {
background: var(--bg-hover);
.question .questionOption:has(input:disabled) {
opacity: 0.6;
}
.questionOption > :first-child {
margin-top: 1px;
@@ -1751,8 +1868,11 @@
color: var(--fg-subtle);
font-size: var(--agent-fs-small, var(--fs-small));
}
.questionOption:has(input:checked) :is(.questionDescription, .questionKey) {
color: var(--fg);
}
.questionOther {
margin: 2px 0 0 30px;
margin: var(--space-0-5) 0 0 calc(16px + var(--space-2) * 2);
}
.questionBody {
display: flex;
@@ -1779,7 +1899,7 @@
.questionPreview {
display: grid;
min-width: 0;
margin: 0 0 0 30px;
margin: 0 0 0 calc(16px + var(--space-2) * 2);
}
.questionPreviewItem {
display: flex;
+1
Переглянути файл
@@ -52,6 +52,7 @@ describe("SkillsPicker", () => {
const trigger = screen.getByRole("button", { name: "Skills" });
expect(trigger).toHaveTextContent("Skills3/4");
expect(trigger.querySelector("svg path")).toHaveAttribute("stroke", "currentColor");
fireEvent.click(trigger);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@ export function SkillsPicker({
return (
<SessionPicker
icon="bulb"
icon="skills"
brand="Skills"
triggerTitles={{
plain: tx("Skills ({active}/{total} active)"),
+11 -8
Переглянути файл
@@ -57,7 +57,7 @@ import {
} from "./model";
import { markdownHtml } from "./Markdown";
function task(id: string, status: AgentStatus, updatedMs: number): AgentTask {
function task(id: string, status: AgentStatus, createdMs: number, updatedMs = createdMs): AgentTask {
return {
id,
title: id,
@@ -70,7 +70,7 @@ function task(id: string, status: AgentStatus, updatedMs: number): AgentTask {
base: "main",
baseCommit: "abc",
error: null,
createdMs: 0,
createdMs,
updatedMs,
config: [],
commands: [],
@@ -634,18 +634,21 @@ describe("usage meters", () => {
});
describe("agents model", () => {
it("groups tasks by what they need, newest first", () => {
it("groups tasks by what they need, keeping active groups in creation order and archived by last update", () => {
const groups = groupTasks([
task("a", "ready", 1),
task("b", "needsInput", 2),
task("c", "running", 3),
task("d", "starting", 4),
task("e", "ready", 5),
task("a", "ready", 1, 90),
task("b", "needsInput", 2, 2),
task("c", "running", 3, 100),
task("d", "starting", 4, 4),
task("e", "ready", 5, 5),
task("arch-old-created-recent-archived", "archived", 1, 200),
task("arch-new-created-older-archived", "archived", 50, 100),
]);
expect(groups.map((g) => [g.status, g.tasks.map((t) => t.id)])).toEqual([
["needsInput", ["b"]],
["running", ["d", "c"]],
["ready", ["e", "a"]],
["archived", ["arch-old-created-recent-archived", "arch-new-created-older-archived"]],
]);
});
+11
Переглянути файл
@@ -221,6 +221,17 @@ describe("New Task composer commands", () => {
expect(agentSkillsList).toHaveBeenCalledOnce();
});
it("uses a theme-coloured Skills icon in the Add Context menu", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Add Context" }));
const item = await screen.findByRole("menuitem", { name: "Skills…" });
expect(item.querySelector("svg path")).toHaveAttribute("stroke", "currentColor");
expect(item.querySelector("svg")!.innerHTML).not.toMatch(/#[0-9a-f]{6}/i);
fireEvent.click(item);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
});
it("names the icon-only Start action and disables it while starting", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
let finish!: (value: unknown) => void;
+28
Переглянути файл
@@ -44,6 +44,7 @@ vi.mock("@tauri-apps/api/webview", () => ({
}));
import { SessionEditor } from "./SessionEditor";
import styles from "./Session.module.css";
import { textOf, typeIn } from "./composerTesting";
import { registerActions } from "@/platform/actions";
import { composerDraft, rollBackTo, rerunFrom, sendMessage, updateComposer, useAgents } from "./store";
@@ -463,6 +464,33 @@ describe("editing a sent agent message", () => {
expect(textOf(screen.getAllByRole("textbox", { name: "Message" })[0]!)).toBe("Original message");
},
);
it("edits in place inside the user message header and preserves the bubble width", async () => {
const { container } = render(
<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
);
const user = userEvent.setup();
const editButton = await screen.findByRole("button", { name: "Edit" });
const bubble = container.querySelector<HTMLElement>(`.${styles.user}`)!;
vi.spyOn(bubble, "getBoundingClientRect").mockReturnValue(new DOMRect(100, 50, 272, 32));
const focusSpy = vi.spyOn(HTMLTextAreaElement.prototype, "focus");
try {
await user.click(editButton);
const message = container.querySelector(`.${styles.userMessage}`)!;
expect(message).toBeInTheDocument();
expect(message.querySelector(`.${styles.messageHead}`)).toBeInTheDocument();
expect(message.querySelector(`.${styles.role}`)).toHaveTextContent("You");
const card = message.querySelector<HTMLElement>(`.${styles.editCard}`)!;
expect(card).toBeInTheDocument();
expect(card.style.getPropertyValue("--edit-width")).toBe("272px");
const box = screen.getAllByRole("textbox", { name: "Message" })[0] as HTMLTextAreaElement;
expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
expect(box.selectionStart).toBe("Original message".length);
expect(box.selectionEnd).toBe("Original message".length);
} finally {
focusSpy.mockRestore();
}
});
});
describe("session composer submission", () => {
+12 -2
Переглянути файл
@@ -120,12 +120,22 @@ export const taskGroupStatus = (task: Pick<AgentTask, "status" | "interrupted">)
export const taskAttentionRank = (task: Pick<AgentTask, "status" | "interrupted">): number =>
GROUP_RANK.get(taskGroupStatus(task)) ?? GROUPS.length;
/** Active sections sort by creation time (newest first) so turns don't reshuffle rows. */
export const compareTaskCreated = (a: AgentTask, b: AgentTask): number =>
(b.createdMs ?? b.updatedMs ?? 0) - (a.createdMs ?? a.updatedMs ?? 0) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0);
/** Archived tasks sort by last update (newest first) so a just-archived task appears at the top. */
export const compareTaskUpdated = (a: AgentTask, b: AgentTask): number =>
(b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0);
export function groupTasks(tasks: Iterable<AgentTask>): TaskGroup[] {
const sorted = [...tasks].sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const list = [...tasks];
return GROUPS.map(([status, label]) => ({
status,
label,
tasks: sorted.filter((t) => taskGroupStatus(t) === status),
tasks: list
.filter((t) => taskGroupStatus(t) === status)
.sort(status === "archived" ? compareTaskUpdated : compareTaskCreated),
})).filter((g) => g.tasks.length > 0);
}
+21 -11
Переглянути файл
@@ -18,7 +18,7 @@ import {
ungroupedMembers,
} from "./organize";
function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0): AgentTask {
function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0, createdMs = updatedMs): AgentTask {
return {
id,
title: id,
@@ -31,7 +31,7 @@ function task(id: string, status: AgentTask["status"] = "ready", updatedMs = 0):
base: null,
baseCommit: null,
error: null,
createdMs: 0,
createdMs,
updatedMs,
config: [],
commands: [],
@@ -72,25 +72,35 @@ describe("task organize", () => {
expect(pruneOrganize(clean, [task("a")])).toBe(clean);
});
it("orders a group by what needs attention, then by activity, leaving pinned tasks out", () => {
it("orders a group by what needs attention, then by creation order for active tasks and activity for archived", () => {
const tasks = [
task("slow", "running", 30),
task("ask", "needsInput", 10),
task("pinned", "ready", 99),
task("done", "ready", 20),
task("slow", "running", 30, 30),
task("ask", "needsInput", 10, 10),
task("pinned", "ready", 99, 99),
task("done-old", "ready", 500, 10),
task("done-new", "ready", 20, 20),
task("arch-just", "archived", 600, 5),
task("arch-earlier", "archived", 40, 40),
];
const organize = {
groups: [{ id: "g1", name: "Docs" }],
groupOf: Object.fromEntries(tasks.map((t) => [t.id, "g1"])),
pinned: ["pinned"],
};
expect(groupMembers(tasks, organize, "g1").map((t) => t.id)).toEqual(["ask", "slow", "done"]);
expect(groupMembers(tasks, organize, "g1").map((t) => t.id)).toEqual([
"ask",
"slow",
"done-new",
"done-old",
"arch-just",
"arch-earlier",
]);
});
it("shows pinned tasks by activity, and the others under the status groups", () => {
const tasks = [task("a", "ready", 10), task("b", "running", 30), task("c", "ready", 20)];
it("keeps pinned tasks in pinned order regardless of activity, and puts others under status groups", () => {
const tasks = [task("a", "ready", 10, 10), task("b", "running", 999, 30), task("c", "ready", 20, 20)];
const organize = { groups: [{ id: "g1", name: "Docs" }], groupOf: { c: "g1" }, pinned: ["a", "b"] };
expect(pinnedMembers(tasks, organize).map((t) => t.id)).toEqual(["b", "a"]);
expect(pinnedMembers(tasks, organize).map((t) => t.id)).toEqual(["a", "b"]);
expect(ungroupedMembers(tasks, organize).map((t) => t.id)).toEqual([]);
expect(ungroupedMembers([...tasks, task("d")], organize).map((t) => t.id)).toEqual(["d"]);
});
+26 -7
Переглянути файл
@@ -6,7 +6,14 @@
import type { AgentTask } from "@/bindings";
import { tx } from "@/platform/i18n";
import { parseRemoteLocation } from "@/platform/remote";
import { groupTasks, taskAttentionRank, taskGroupStatus, type TaskGroup } from "./model";
import {
compareTaskCreated,
compareTaskUpdated,
groupTasks,
taskAttentionRank,
taskGroupStatus,
type TaskGroup,
} from "./model";
/** Section key of the pinned group, above every other group. */
export const PINNED_SECTION = "pinned";
@@ -208,12 +215,16 @@ export function applyOrder(defaultSorted: AgentTask[], manual: readonly string[]
return [...fresh, ...ordered];
}
/** The tasks of `group`, what waits for the user first, then the most recently active (or manual order). */
/** The tasks of `group`, what waits for the user first, then creation order for active tasks (or manual order). */
export function groupMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize, group: string): AgentTask[] {
const pinned = new Set(organize.pinned);
const sorted = [...tasks]
.filter((t) => organize.groupOf[t.id] === group && !pinned.has(t.id))
.sort((a, b) => taskAttentionRank(a) - taskAttentionRank(b) || (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
.sort(
(a, b) =>
taskAttentionRank(a) - taskAttentionRank(b) ||
(taskGroupStatus(a) === "archived" ? compareTaskUpdated(a, b) : compareTaskCreated(a, b)),
);
return applyOrder(sorted, organize.order?.[customSection(group)]);
}
@@ -236,11 +247,19 @@ export function statusGroups(tasks: Iterable<AgentTask>, organize: TaskOrganize)
}));
}
/** The pinned tasks, most recently active first (or manual order). */
/** The pinned tasks, in pinned order (or manual order when rearranged). */
export function pinnedMembers(tasks: Iterable<AgentTask>, organize: TaskOrganize): AgentTask[] {
const pinned = new Set(organize.pinned);
const sorted = [...tasks].filter((t) => pinned.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
return applyOrder(sorted, organize.order?.[PINNED_SECTION]);
const byId = new Map<string, AgentTask>();
for (const task of tasks) byId.set(task.id, task);
const seen = new Set<string>();
const ordered: AgentTask[] = [];
for (const id of organize.pinned) {
if (seen.has(id)) continue;
seen.add(id);
const task = byId.get(id);
if (task) ordered.push(task);
}
return applyOrder(ordered, organize.order?.[PINNED_SECTION]);
}
function placeId(
+21 -19
Переглянути файл
@@ -286,7 +286,7 @@ export function QuestionForm({
);
const chooseByNumber = (number: number) => {
const answer = answers[position];
if (!answer) return;
if (!answer?.question.options.length) return;
const option = answer.question.options[number - 1];
if (option) choose(answer, option.label, !answer.picked.includes(option.label));
else if (number === answer.question.options.length + 1) chooseOther(answer, answer.other === null);
@@ -362,16 +362,20 @@ export function QuestionForm({
</span>
),
})),
{
key: group,
checked: item.other !== null,
onChange: (checked: boolean) => chooseOther(item, checked),
label: (
<span className={styles.questionLabel}>
<T>Other</T>
</span>
),
},
...(item.question.options.length
? [
{
key: group,
checked: item.other !== null,
onChange: (checked: boolean) => chooseOther(item, checked),
label: (
<span className={styles.questionLabel}>
<T>Other</T>
</span>
),
},
]
: []),
];
return (
<div
@@ -387,7 +391,9 @@ export function QuestionForm({
>
<fieldset className={styles.question} disabled={busy}>
<legend className={styles.questionText}>
{item.question.header && <span className={styles.questionTag}>{item.question.header}</span>}
{!multiple && item.question.header && (
<span className={styles.questionTag}>{item.question.header}</span>
)}
{item.question.question}
</legend>
<div className={clsx(styles.questionBody, hasPreviews && styles.questionBodyWithPreview)}>
@@ -427,7 +433,7 @@ export function QuestionForm({
{item.other !== null && (
<Input
autoFocus={entry.type === "permission" || item.question.options.length > 0}
className={styles.questionOther}
className={clsx(item.question.options.length > 0 && styles.questionOther)}
value={item.other}
placeholder="Type your answer"
onChange={(event) => update(item, { ...item, other: event.target.value })}
@@ -482,17 +488,13 @@ export function QuestionForm({
</Button>
{multiple && (
<div className={styles.questionPager}>
<Button size="small" disabled={busy || position === 0} onClick={() => goTo(position - 1, true)}>
<Button disabled={busy || position === 0} onClick={() => goTo(position - 1, true)}>
Previous
</Button>
<span className={styles.questionPage}>
{position + 1} / {answers.length}
</span>
<Button
size="small"
disabled={busy || position === answers.length - 1}
onClick={() => goTo(position + 1, true)}
>
<Button disabled={busy || position === answers.length - 1} onClick={() => goTo(position + 1, true)}>
Next
</Button>
</div>
+4 -4
Переглянути файл
@@ -95,7 +95,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
<Button
size="small"
variant="primary"
icon="resume"
icon="agent-resume"
disabled={resuming}
onClick={() => {
setResuming(true);
@@ -142,7 +142,7 @@ function WaitingForNetworkBanner({ task }: { task: AgentTask }) {
<Button
size="small"
variant="primary"
icon="resume"
icon="agent-resume"
onClick={() =>
void resumeTask(task.id).catch((e: unknown) =>
notifications().notify({
@@ -387,7 +387,7 @@ export function SessionComposer({
return (
<div className={styles.composerArea}>
{task.status === "archived" && (
<div className={styles.banner}>
<div className={clsx(styles.banner, styles.bannerNeutral)}>
<span className={styles.bannerText}>
<T>This task is archived. Unarchive it to continue the conversation.</T>
</span>
@@ -433,7 +433,7 @@ export function SessionComposer({
disabled={task.status === "archived"}
addMenu={[
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", disabled: task.status === "archived", run: openSkills },
{ id: "skills", label: "Skills…", icon: "skills", disabled: task.status === "archived", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", disabled: task.status === "archived", run: openMemory },
]}
toolbar={
+164 -116
Переглянути файл
@@ -2,11 +2,12 @@ import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri } from "@/platform/ipc";
import { isMacHost } from "@/platform/keymap";
import { basename } from "@/platform/project";
import { Button, copyText, fileIconName, Icon, IconButton, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { memo, useLayoutEffect, useRef, useState, type CSSProperties, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
import { ImageStrip } from "../ImageStrip";
@@ -287,12 +288,14 @@ function UserMessage({
}) {
const tx = useTx();
const [editing, setEditing] = useState(false);
const [editWidth, setEditWidth] = useState<number | null>(null);
const bubbleRef = useRef<HTMLDivElement>(null);
if (entry.recovery) {
return (
<div className={styles.recoveryDivider} role="separator">
<span className={styles.recoveryRule} aria-hidden="true" />
<span className={styles.recoveryPill}>
<Icon name="resume" size={12} />
<Icon name="agent-resume" size={12} />
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
</span>
@@ -310,20 +313,12 @@ function UserMessage({
// A copy up to an earlier turn drops the later ones from the copied session.
const canFork = idle && fork && (rollback || turn === turnCount - 1);
const text = userMessageText(entry.text);
if (editing && turn !== null) {
return (
<MessageEditor
initial={text}
initialImages={entry.images ?? []}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={async (text, images) => {
if (await rerunFrom(task.id, turn, text, images)) setEditing(false);
}}
/>
);
}
const images = entry.images ?? [];
const startEditing = () => {
const width = bubbleRef.current?.getBoundingClientRect().width ?? 0;
setEditWidth(width > 0 ? width : null);
setEditing(true);
};
// Images are listed after the files in `attachments` and shown as thumbnails instead.
// Files mentioned in the text are chips there already.
const mentioned = new Set(
@@ -337,67 +332,80 @@ function UserMessage({
<div className={clsx(styles.message, styles.userMessage)}>
{/* Actions and the time sit beside the author on hover: the reply under it has the turn's duration. */}
<div className={styles.messageHead}>
<MessageActions>
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(text)} />
{inPlace && entry.text && (
<IconButton size="small" icon="edit" title="Edit" onClick={() => setEditing(true)} />
)}
{inPlace && (
<IconButton
size="small"
icon="diff-revert"
iconSize={14}
title="Roll Back to Here"
action="agents.rollBackToMessage"
actionArg={{ task: task.id, turn }}
/>
)}
{!archived && entry.text && entry.attachments.length === 0 && (
<IconButton
size="small"
icon="refresh"
title={inPlace ? "Run Again From Here" : "Send Again"}
onClick={() =>
void (
inPlace
? rerunFrom(task.id, turn, entry.text, images, {
title: "Run Again From Here",
later: turn < turnCount - 1,
})
: resendMessage(task.id, entry.text)
).catch(fail)
}
/>
)}
{canFork && (
<IconButton
size="small"
icon="branch"
title="Fork"
onClick={() => void forkTask(task.id, turn + 1).catch(failed("Couldn't fork the task"))}
/>
)}
</MessageActions>
{!(editing && turn !== null) && (
<MessageActions>
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(text)} />
{inPlace && entry.text && <IconButton size="small" icon="edit" title="Edit" onClick={startEditing} />}
{inPlace && (
<IconButton
size="small"
icon="diff-revert"
iconSize={14}
title="Roll Back to Here"
action="agents.rollBackToMessage"
actionArg={{ task: task.id, turn }}
/>
)}
{!archived && entry.text && entry.attachments.length === 0 && (
<IconButton
size="small"
icon="refresh"
title={inPlace ? "Run Again From Here" : "Send Again"}
onClick={() =>
void (
inPlace
? rerunFrom(task.id, turn, entry.text, images, {
title: "Run Again From Here",
later: turn < turnCount - 1,
})
: resendMessage(task.id, entry.text)
).catch(fail)
}
/>
)}
{canFork && (
<IconButton
size="small"
icon="branch"
title="Fork"
onClick={() => void forkTask(task.id, turn + 1).catch(failed("Couldn't fork the task"))}
/>
)}
</MessageActions>
)}
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
<span className={styles.role}>
<T>You</T>
</span>
</div>
<div className={styles.user}>
<ReferencedText text={text} cwd={task.cwd} />
<ImageStrip images={images} />
{files.length > 0 && (
<div className={styles.attachments}>
{files.map((a, i) => (
// oxlint-disable-next-line react/no-array-index-key -- attachments from different directories can share a basename
<span key={i} className={styles.attachment}>
<Icon name={fileIconName(a)} size={12} />
{a}
</span>
))}
</div>
)}
</div>
{editing && turn !== null ? (
<MessageEditor
initial={text}
initialImages={images}
initialWidth={editWidth}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={async (nextText, nextImages) => {
if (await rerunFrom(task.id, turn, nextText, nextImages)) setEditing(false);
}}
/>
) : (
<div ref={bubbleRef} className={styles.user}>
<ReferencedText text={text} cwd={task.cwd} />
<ImageStrip images={images} />
{files.length > 0 && (
<div className={styles.attachments}>
{files.map((a, i) => (
// oxlint-disable-next-line react/no-array-index-key -- attachments from different directories can share a basename
<span key={i} className={styles.attachment}>
<Icon name={fileIconName(a)} size={12} />
{a}
</span>
))}
</div>
)}
</div>
)}
</div>
);
}
@@ -406,12 +414,15 @@ function UserMessage({
function MessageEditor({
initial,
initialImages,
initialWidth,
later,
onCancel,
onSend,
}: {
initial: string;
initialImages: AgentImage[];
/** Measured width of the bubble being replaced, so editing starts in place without jumping. */
initialWidth: number | null;
/** Turns follow it (they are dropped on send). */
later: boolean;
onCancel: () => void;
@@ -423,6 +434,25 @@ function MessageEditor({
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const pending = useRef(false);
const cardRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => {
const box = textareaRef.current;
if (!box) return;
// Avoid native autoFocus scroll jumps; only nudge if the expanded footer sits past the bottom edge.
box.focus({ preventScroll: true });
box.setSelectionRange(box.value.length, box.value.length);
const card = cardRef.current;
const scroller = card?.closest(`.${styles.stream}`);
if (card && scroller instanceof HTMLElement) {
const view = scroller.getBoundingClientRect();
const rect = card.getBoundingClientRect();
if (rect.bottom > view.bottom) {
const nudge = Math.min(rect.bottom - view.bottom + 8, Math.max(0, rect.top - view.top));
if (nudge > 0) scroller.scrollTop += nudge;
}
}
}, []);
const send = async () => {
if ((!text.trim() && images.length === 0) || pending.current) return;
pending.current = true;
@@ -442,59 +472,77 @@ function MessageEditor({
setSending(false);
}
};
const cardStyle = initialWidth ? ({ "--edit-width": `${initialWidth}px` } as CSSProperties) : undefined;
return (
<div className={styles.message}>
<textarea
className={styles.editMessage}
value={text}
rows={Math.min(Math.max(text.split("\n").length, 2), 12)}
autoFocus
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onFocus={(e) => e.currentTarget.setSelectionRange(text.length, text.length)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void send();
}
}}
/>
<ImageStrip images={images} onRemove={sending ? undefined : (i) => setImages(images.filter((_, j) => j !== i))} />
<>
<div ref={cardRef} className={styles.editCard} style={cardStyle}>
<div className={styles.editField}>
<div className={styles.editMirror} aria-hidden="true">
{text.endsWith("\n") ? `${text}\u200b` : text || "\u200b"}
</div>
<textarea
ref={textareaRef}
className={styles.editMessage}
value={text}
rows={1}
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void send();
}
}}
/>
</div>
{images.length > 0 && (
<div className={styles.editImages}>
<ImageStrip
images={images}
onRemove={sending ? undefined : (i) => setImages(images.filter((_, j) => j !== i))}
/>
</div>
)}
<div className={styles.editFooter}>
<span className={styles.editHint} aria-hidden="true">
<kbd>{isMacHost() ? "⌘" : "Ctrl"}</kbd>
<kbd>↵</kbd>
</span>
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={(!text.trim() && images.length === 0) || sending}
onClick={() => void send()}
/>
</span>
</div>
</div>
{error && (
<div className={styles.error} role="alert">
<div className={clsx(styles.error, styles.editError)} role="alert">
<Icon name="error" size={14} />
<span>
<T>Couldn't send the message</T>: {error}
</span>
</div>
)}
<div className={styles.editBar}>
<span className={styles.muted}>
{later ? (
<T>
The messages after this one are replaced, and the files the agent changed since go back to how they were
before this message was sent.
</T>
) : (
<T>The files the agent changed since go back to how they were before this message was sent.</T>
)}
</span>
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={(!text.trim() && images.length === 0) || sending}
onClick={() => void send()}
/>
</span>
<div className={styles.editNote}>
{later ? (
<T>
The messages after this one are replaced, and the files the agent changed since go back to how they were
before this message was sent.
</T>
) : (
<T>The files the agent changed since go back to how they were before this message was sent.</T>
)}
</div>
</div>
</>
);
}
+16
Переглянути файл
@@ -1348,6 +1348,7 @@ describe("an asynchronous Codex question", () => {
it("accepts a typed answer without suggested choices", async () => {
const answerKey = freeQuestion();
const card = await screen.findByRole("form", { name: "What deadline?" });
expect(within(card).queryByRole("radio")).toBeNull();
const submit = within(card).getByRole("button", { name: "Submit" });
expect(submit).toBeDisabled();
fireEvent.change(within(card).getByPlaceholderText("Type your answer"), { target: { value: "Tomorrow" } });
@@ -1373,6 +1374,21 @@ describe("an asynchronous Codex question", () => {
expect(await screen.findByRole("form", { name: "Blocking question" })).not.toHaveClass(styles.questionCardPinned!);
});
it("uses the same pinned container for ACP forms as asynchronous questions", async () => {
const entry: AgentEntry = {
type: "permission",
id: 101,
title: "Project details",
options: [],
chosen: null,
form: { fields: [{ name: "project", title: "Project name", kind: "text", required: true }] },
};
backend.entries.set("A", [entry]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
expect(await screen.findByRole("form", { name: "Project details" })).toHaveClass(styles.questionCardPinned!);
});
it("skips without submitting an answer", async () => {
freeQuestion();
const card = await screen.findByRole("form", { name: "What deadline?" });
+2 -2
Переглянути файл
@@ -353,7 +353,7 @@ export const taskActions: Action[] = [
id: "agents.resumeAllInterrupted",
title: "Resume All Interrupted Tasks",
category: "Agents",
icon: "resume",
icon: "agent-resume",
when: "projectOpen",
keywords: ["resume", "continue", "interrupted", "recover"],
run: async () => {
@@ -497,7 +497,7 @@ export function taskMenu(tasks: AgentTask[], below: AgentTask[] = []): MenuItem[
kind: "action",
action: "agents.resumeTasks",
label: multiple ? tx`Resume (${interrupted.length})` : "Resume",
icon: "resume",
icon: "agent-resume",
arg: interrupted.map((t) => t.id),
},
{
+35
Переглянути файл
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { ensureSyntaxTree } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import { expressionAt } from "../editor/valueTooltip";
/** The expression around the `|` in `line`. */
@@ -35,3 +37,36 @@ describe("expression at the mouse for Quick Evaluate (#4772)", () => {
expect(at("a.getB().c|()", false)).toBe("c");
});
});
/** The expression around the `|` in a Java statement. */
function inJava(statement: string, calls: boolean) {
const prefix = "class A { void f() { ";
const doc = `${prefix}${statement} } }`;
const pos = doc.indexOf("|");
const view = new EditorView({ state: EditorState.create({ doc: doc.replace("|", ""), extensions: java() }) });
ensureSyntaxTree(view.state, view.state.doc.length, 1000);
const text = expressionAt(view, pos, { calls })?.text ?? null;
view.destroy();
return text;
}
describe("expression of an operator (#7000)", () => {
it("takes the expression the operator belongs to, as IDEA does", () => {
for (const calls of [false, true]) {
expect(inJava("if (a > 1 |&& !flag) {}", calls)).toBe("a > 1 && !flag");
expect(inJava("if (a |> 1 && !flag) {}", calls)).toBe("a > 1");
expect(inJava("if (a > 1 && |!flag) {}", calls)).toBe("!flag");
expect(inJava("x = c |? 1 : 2;", calls)).toBe("c ? 1 : 2");
// An identifier is still just the identifier.
expect(inJava("if (|a > 1 && !flag) {}", calls)).toBe("a");
}
});
it("leaves calls, increments and assignments to Quick Evaluate", () => {
expect(inJava("if (s.length() |> 0) {}", false)).toBeNull();
expect(inJava("if (s.length() |> 0) {}", true)).toBe("s.length() > 0");
expect(inJava("if (a |!= b) {}", false)).toBe("a != b");
expect(inJava("x = a |+ i++;", false)).toBeNull();
expect(inJava("x |= 1;", true)).toBeNull();
});
});
+24 -2
Переглянути файл
@@ -3,6 +3,7 @@
* while suspended, hovering an expression (or the selection under the mouse)
* evaluates it in the selected frame.
*/
import { syntaxTree } from "@codemirror/language";
import type { EditorState, Extension } from "@codemirror/state";
import type { DebugSessionId, Variable } from "@/bindings";
import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
@@ -49,10 +50,29 @@ function openOf(t: string, i: number): number {
return -1;
}
/** Syntax nodes of an operator's expression (Lezer's Java, JS, Python, C++, Rust, Go grammars). */
const OPERATOR_EXPRESSION = /^(Binary|Unary|Ternary|Conditional)Expr(ession)?$/;
/** A call, an increment or an assignment: a plain hover doesn't evaluate those. */
const SIDE_EFFECTS = /[\p{L}\p{N}_$)\]]\s*\(|\+\+|--|(^|[^=!<>])=(?!=)/u;
/**
* As in IDEA, on an operator the expression it belongs to: `&&` gives `a > 1 && !flag`, `>` gives
* `a > 1`, `!` gives `!flag`. Without `calls` (a hover), not when evaluating it could change state.
*/
function operatorExpressionAt(state: EditorState, pos: number, calls: boolean) {
const token = syntaxTree(state).resolveInner(pos, 1);
const parent = token.parent;
if (token.firstChild || !parent || !OPERATOR_EXPRESSION.test(parent.name)) return null;
const text = state.sliceDoc(parent.from, parent.to);
if (text.includes("\n") || (!calls && SIDE_EFFECTS.test(text))) return null;
return { from: parent.from, to: parent.to, text };
}
/**
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`).
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`). On an operator,
* the expression it belongs to.
*/
export function expressionAt(
view: EditorView,
@@ -69,7 +89,9 @@ export function expressionAt(
const t = line.text;
let start = pos - line.from;
let end = start;
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) return null;
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) {
return /\s/.test(t[end] ?? " ") ? null : operatorExpressionAt(state, pos, calls);
}
while (end < t.length && IDENT.test(t[end]!)) end++;
for (;;) {
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
+2
Переглянути файл
@@ -50,6 +50,7 @@ import { activate as cucumber } from "./cucumber";
import { activate as pytest } from "./pytest";
import { activate as rails } from "./rails";
import { activate as thymeleaf } from "./thymeleaf";
import { activate as jni } from "./jni";
import { activate as database } from "./database";
import { activate as graphql } from "./graphql";
import { activate as deployment } from "./deployment";
@@ -110,6 +111,7 @@ const features: Array<[string, Activate]> = [
["pytest", pytest],
["rails", rails],
["thymeleaf", thymeleaf],
["jni", jni],
["database", database],
["graphql", graphql],
["deployment", deployment],
+134
Переглянути файл
@@ -0,0 +1,134 @@
/** Java `native` methods ↔ C++ JNI implementations. Ctrl+B on either
* declaration jumps to the other side; the navigation provider does the same
* for names that are not a declaration (C++ references, hover/⌘-click). */
import { EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { Tree } from "@lezer/common";
import {
CONTRIBUTED_DEFINITION,
registerEditorContribution,
registerNavigationProvider,
type ContributedDefinition,
} from "@/editor/api";
import { locationItems, navigateTo } from "@/editor/lsp/navigation";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { docOf } from "@/editor/lsp/lsp";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
import { gitRevisionOf } from "@/platform/virtualDocs";
import {
javaNativeAt,
jniSymbolAt,
mangleJni,
parseJava,
scanJniSymbols,
unmangleJni,
type JniSymbolHit,
} from "./names";
import { findCppTargets, findJavaTargets, invalidateJniCache, type JniTarget } from "./search";
const CPP_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]);
/** Language-data probes hit many positions and alternate between open editors.
* Cache per immutable Text, not in module-wide single slots. */
interface DocCache {
text: string;
java: boolean;
cpp: boolean;
tree?: Tree;
symbols?: JniSymbolHit[];
}
const docCaches = new WeakMap<EditorState["doc"], DocCache>();
function cacheOf(state: EditorState): DocCache {
let cache = docCaches.get(state.doc);
if (!cache) {
const text = state.doc.toString();
cache = { text, java: text.includes("native"), cpp: text.includes("Java_") };
docCaches.set(state.doc, cache);
}
return cache;
}
interface Hit {
from: number;
to: number;
targets: () => Promise<JniTarget[]>;
}
function detect(language: string, state: EditorState, offset: number): Hit | null {
const cache = cacheOf(state);
if (language === "java") {
if (!cache.java) return null;
const tree = (cache.tree ??= parseJava(cache.text));
const method = javaNativeAt(cache.text, offset, tree);
if (!method) return null;
const symbol = mangleJni(method.fqn);
return { from: method.from, to: method.to, targets: () => findCppTargets(symbol) };
}
if (CPP_LANGUAGES.has(language)) {
if (!cache.cpp) return null;
const symbols = (cache.symbols ??= scanJniSymbols(cache.text));
const symbol = jniSymbolAt(cache.text, offset, symbols);
if (!symbol) return null;
const decoded = unmangleJni(symbol.symbol);
if (!decoded) return null;
return {
from: symbol.from,
to: symbol.to,
targets: () => findJavaTargets(decoded.fqn, decoded.method),
};
}
return null;
}
async function showTargets(view: EditorView, offset: number, targets: JniTarget[]) {
if (targets.length === 1) {
await navigateTo(targets[0]!);
return;
}
const items = await locationItems(targets);
openPopup({
kind: "list",
anchor: caretAnchor(view, offset),
title: tx`Choose Declaration`,
items,
});
}
export function activate(): () => void {
const offProvider = registerNavigationProvider(async (view, offset) => {
const doc = docOf(view);
if (!doc || doc.virtual || gitRevisionOf(doc.path)) return null;
const hit = detect(doc.language, view.state, offset);
if (!hit) return null;
const targets = await hit.targets();
return targets.length ? { from: hit.from, to: hit.to, targets } : null;
});
const offContribution = registerEditorContribution({
id: "jni.navigation",
extensions: (ctx) => {
if (ctx.virtual || (ctx.language !== "java" && !CPP_LANGUAGES.has(ctx.language))) return [];
const canHandle = (state: EditorState, pos: number) => detect(ctx.language, state, pos) !== null;
const definition: ContributedDefinition = async (view, pos) => {
const hit = detect(ctx.language, view.state, pos);
if (!hit) return false;
const targets = await hit.targets();
if (!targets.length) return false;
await showTargets(view, pos, targets);
return true;
};
definition.canHandle = canHandle;
return EditorState.languageData.of((state, pos) =>
canHandle(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
);
},
});
const offEvents = onIdeEvent("fsChanged", () => invalidateJniCache());
return () => {
offProvider();
offContribution();
offEvents();
};
}
+76
Переглянути файл
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { javaNativeAt, jniSymbolAt, mangleJni, unmangleJni } from "./names";
const FQN = "org.example.native_demo.NativeBridge.setPort";
const SYMBOL = "Java_org_example_native_1demo_NativeBridge_setPort";
const JAVA = `package org.example.native_demo;
public class NativeBridge {
public static native void setPort(int port);
public static int computePort() { return 42; }
}
`;
const CPP = `JNIEXPORT void JNICALL
${SYMBOL}(JNIEnv *env, jclass clazz, jint port) {
return;
}
`;
describe("JNI name mangling", () => {
it("escapes underscores in package names", () => {
expect(mangleJni(FQN)).toBe(SYMBOL);
});
it("mangles nested classes and unicode", () => {
expect(mangleJni("a.b.Outer$Inner.方法")).toBe("Java_a_b_Outer_00024Inner__065b9_06cd5");
});
it("unmangles a symbol and drops an overload signature", () => {
expect(unmangleJni(SYMBOL)).toEqual({
fqn: "org.example.native_demo.NativeBridge",
method: "setPort",
});
expect(unmangleJni("Java_a_b_Foo_bar__II")).toEqual({ fqn: "a.b.Foo", method: "bar" });
expect(unmangleJni("not_a_symbol")).toBeNull();
});
it("does not mistake a unicode escape for an overload suffix", () => {
expect(unmangleJni(mangleJni("a.b.Outer$Inner.方法"))).toEqual({
fqn: "a.b.Outer$Inner",
method: "方法",
});
});
it("round-trips a fully qualified name", () => {
expect(unmangleJni(mangleJni(FQN))).toEqual({
fqn: "org.example.native_demo.NativeBridge",
method: "setPort",
});
});
});
describe("caret detection", () => {
it("finds a native method declaration in Java", () => {
const offset = JAVA.indexOf("setPort") + 3;
expect(javaNativeAt(JAVA, offset)).toEqual({
name: "setPort",
from: JAVA.indexOf("setPort"),
to: JAVA.indexOf("setPort") + "setPort".length,
fqn: FQN,
});
});
it("ignores non-native methods", () => {
expect(javaNativeAt(JAVA, JAVA.indexOf("computePort") + 2)).toBeNull();
});
it("finds a JNI function definition in C++", () => {
const offset = CPP.indexOf("setPort(") + 3;
expect(jniSymbolAt(CPP, offset)).toEqual({
symbol: SYMBOL,
from: CPP.indexOf("Java_org_example"),
to: CPP.indexOf("Java_org_example") + SYMBOL.length,
});
});
});
+144
Переглянути файл
@@ -0,0 +1,144 @@
/** JNI name mangling and caret detection for Java `native` methods and their
* `Java_<mangled-name>` C/C++ implementations. No IDE/IPC dependencies here so
* the rules can be tested directly. */
import { javaLanguage } from "@codemirror/lang-java";
import type { SyntaxNode, Tree } from "@lezer/common";
const TYPE_DECLARATIONS = new Set([
"ClassDeclaration",
"InterfaceDeclaration",
"EnumDeclaration",
"RecordDeclaration",
"AnnotationTypeDeclaration",
]);
export interface NativeMethodHit {
name: string;
from: number;
to: number;
/** Fully qualified Java name; nested classes are joined with `$`. */
fqn: string;
}
export interface JniSymbolHit {
symbol: string;
from: number;
to: number;
}
/** `Java_pkg_Class_method`, with `_` → `_1`, `;` → `_2`, `[` → `_3`,
* `$` (nested class) → `_00024` and non-ASCII → `_0xxxx`. */
export function mangleJni(fqn: string): string {
let out = "";
for (const ch of fqn) {
if (ch === "." || ch === "/") out += "_";
else if (ch === "_") out += "_1";
else if (ch === ";") out += "_2";
else if (ch === "[") out += "_3";
else if (ch === "$") out += "_00024";
else if (ch.charCodeAt(0) > 127) out += `_0${ch.charCodeAt(0).toString(16).padStart(4, "0")}`;
else out += ch;
}
return `Java_${out}`;
}
/** Reverse of {@link mangleJni}; drops the overload signature suffix (`__...`). */
export function unmangleJni(symbol: string): { fqn: string; method: string } | null {
if (!symbol.startsWith("Java_")) return null;
let rest = symbol.slice("Java_".length);
// `__` also appears where a name starts with a unicode escape (`_0xxxx`),
// e.g. `Class__065b9`. A real overload suffix is `__` followed by a mangled
// argument signature, which starts with an uppercase letter or `[`→`_3`.
for (let at = rest.indexOf("__"); at >= 0; at = rest.indexOf("__", at + 1)) {
const next = rest[at + 2];
if (next && (/[A-Z]/.test(next) || next === "_")) {
rest = rest.slice(0, at);
break;
}
}
let out = "";
for (let i = 0; i < rest.length; i++) {
const ch = rest[i]!;
if (ch !== "_") {
out += ch;
continue;
}
const escape = rest[i + 1];
if (escape === "1" || escape === "2" || escape === "3") {
out += escape === "1" ? "_" : escape === "2" ? ";" : "[";
i++;
} else if (escape === "0") {
const hex = rest.slice(i + 2, i + 6);
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
out += String.fromCharCode(Number.parseInt(hex, 16));
i += 5;
} else {
out += ".";
}
}
const split = out.lastIndexOf(".");
if (split <= 0 || split === out.length - 1) return null;
return { fqn: out.slice(0, split), method: out.slice(split + 1) };
}
/** Callers that keep several editors open should cache this per immutable Text. */
export function parseJava(text: string): Tree {
return javaLanguage.parser.parse(text);
}
function containsKind(node: SyntaxNode | null, name: string): boolean {
for (let at = node; at; at = at.parent) if (at.name === name) return true;
return false;
}
function declaredName(text: string, node: SyntaxNode): string {
const name = node.getChild("Definition") ?? node.getChild("Identifier");
return name ? text.slice(name.from, name.to).replace(/\s+/g, "") : "";
}
/** The `native` method declaration covering `offset`, if the caret is on its name. */
export function javaNativeAt(text: string, offset: number, tree?: Tree): NativeMethodHit | null {
const parsed = tree ?? parseJava(text);
let node: SyntaxNode | null = parsed.resolveInner(offset, -1);
if (!containsKind(node, "MethodDeclaration")) node = parsed.resolveInner(offset, 1);
while (node && node.name !== "MethodDeclaration") node = node.parent;
if (!node || !node.getChild("Modifiers")?.getChild("native")) return null;
const name = node.getChild("Definition");
if (!name || offset < name.from || offset > name.to) return null;
const types: string[] = [];
for (let at: SyntaxNode | null = node.parent; at; at = at.parent) {
if (TYPE_DECLARATIONS.has(at.name)) {
const type = declaredName(text, at);
if (type) types.unshift(type);
}
}
if (!types.length) return null;
const pkgNode = parsed.topNode.getChild("PackageDeclaration");
const pkgName = pkgNode ? (pkgNode.getChild("ScopedIdentifier") ?? pkgNode.getChild("Identifier")) : null;
const pkg = pkgName ? text.slice(pkgName.from, pkgName.to).replace(/\s+/g, "") : "";
const method = text.slice(name.from, name.to);
return {
name: method,
from: name.from,
to: name.to,
fqn: [pkg, types.join("$"), method].filter(Boolean).join("."),
};
}
/** All `Java_...` names in a document that start a function call/definition. */
export function scanJniSymbols(text: string): JniSymbolHit[] {
const out: JniSymbolHit[] = [];
for (const match of text.matchAll(/Java_[A-Za-z0-9_]+/g)) {
const from = match.index ?? 0;
const to = from + match[0].length;
if (text.slice(to).replace(/^\s+/, "").startsWith("(")) {
out.push({ symbol: match[0], from, to });
}
}
return out;
}
/** The `Java_...` function name covering `offset`, only when it starts a function. */
export function jniSymbolAt(text: string, offset: number, symbols?: readonly JniSymbolHit[]): JniSymbolHit | null {
return (symbols ?? scanJniSymbols(text)).find((hit) => offset >= hit.from && offset < hit.to) ?? null;
}
+102
Переглянути файл
@@ -0,0 +1,102 @@
/** Resolves a JNI symbol to a location in the opposite language. The IDE's
* symbol index is tried first; a literal/regex text search is the fallback,
* because mangled `Java_...` names are scored badly by fuzzy symbol search. */
import type { FileMatches } from "@/bindings";
import { call, commands, nextRequestId, type Location } from "@/platform/ipc";
import { streamSearch } from "@/platform/textSearch";
const CPP_FILE = /\.(?:c|cc|cpp|cxx|h|hh|hpp|hxx)$/i;
const JAVA_FILE = /\.java$/i;
const CPP_INCLUDE = ["*.c", "*.cc", "*.cpp", "*.cxx", "*.h", "*.hh", "*.hpp", "*.hxx"];
export interface JniTarget extends Location {
name?: string;
}
const cache = new Map<string, JniTarget[]>();
function cached(key: string, find: () => Promise<JniTarget[]>): Promise<JniTarget[]> {
const hit = cache.get(key);
if (hit) return Promise.resolve(hit);
return find().then((targets) => {
if (cache.size > 256) cache.clear();
cache.set(key, targets);
return targets;
});
}
export function invalidateJniCache() {
cache.clear();
}
async function fromSymbols(query: string, files: RegExp, exact: string | null, limit: number): Promise<JniTarget[]> {
const matches = await call(commands.findSymbols(query, "all", limit)).catch(() => []);
return matches
.filter((match) => files.test(match.path) && (!exact || match.name === exact))
.slice(0, limit)
.map((match) => ({ path: match.path, range: match.range, name: match.name }));
}
async function fromText(
pattern: string,
isRegex: boolean,
include: string[],
limit: number,
accept?: (path: string) => boolean,
): Promise<JniTarget[]> {
const found: FileMatches[] = [];
await streamSearch(
nextRequestId(),
{
pattern,
isRegex,
caseSensitive: true,
wholeWord: false,
include,
exclude: [],
scope: { kind: "project" },
maxMatches: limit,
},
(file) => found.push(file),
).catch(() => null);
const out: JniTarget[] = [];
for (const file of found) {
if (accept && !accept(file.path)) continue;
for (const match of file.matches) {
for (const range of match.ranges) {
out.push({
path: file.path,
range: {
start: { line: match.line, col: match.textOffset + range[0] },
end: { line: match.line, col: match.textOffset + range[1] },
},
});
if (out.length >= limit) return out;
}
}
}
return out;
}
/** Java `native` method → its `Java_...` implementation in C/C++. */
export function findCppTargets(symbol: string): Promise<JniTarget[]> {
return cached(`cpp:${symbol}`, async () => {
const fromIndex = await fromSymbols(symbol, CPP_FILE, symbol, 100);
if (fromIndex.length) return fromIndex;
return fromText(symbol, false, CPP_INCLUDE, 50);
});
}
/** `Java_pkg_Class_method` → the Java `native` declaration. */
export function findJavaTargets(fqn: string, method: string): Promise<JniTarget[]> {
return cached(`java:${fqn}.${method}`, async () => {
const parts = fqn.split(".");
const outerType = parts.at(-1)!.split("$")[0]!;
const suffix = `/${outerType}.java`;
const inClass = (path: string) => path.replace(/\\/g, "/").endsWith(suffix);
const fromIndex = (await fromSymbols(method, JAVA_FILE, method, 300)).filter((target) => inClass(target.path));
if (fromIndex.length) return fromIndex;
const name = method.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return fromText(`\\bnative\\b[^\\n;{}]*\\b${name}\\s*\\(`, true, ["*.java"], 100, inClass);
});
}
+27
Переглянути файл
@@ -0,0 +1,27 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { useEditorRegistry } from "@/editor/api";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { trackActivationEvents } from "../bridge";
afterEach(() => {
setPluginsBackend(null);
useEditorRegistry.setState({ active: null });
});
describe("activation events", () => {
it("fires on-language when the open file's language is recognized later", () => {
const backend = createMemoryPluginsBackend();
const activationEvent = vi.spyOn(backend, "activationEvent");
setPluginsBackend(backend);
const ctx = (language: string) => ({ active: { ctx: { path: "/p/page.twig", language } } }) as never;
useEditorRegistry.setState(ctx("plaintext"));
const stop = trackActivationEvents();
// A remote server redetects the file once it has the plugin's language.
useEditorRegistry.setState(ctx("twig"));
stop();
expect(activationEvent.mock.calls.filter(([kind]) => kind === "language").map(([, arg]) => arg)).toEqual([
"plaintext",
"twig",
]);
});
});
+5 -2
Переглянути файл
@@ -130,7 +130,7 @@ function scheduleRefresh() {
* Fires `on-language:<id>` and `on-file:<project-relative path>` for files
* opened in the editor; the backend activates the plugins waiting for them.
*/
function trackActivationEvents(): () => void {
export function trackActivationEvents(): () => void {
const seenLanguages = new Set<string>();
const report = (ctx: { path: string | null; language: string } | undefined) => {
if (!ctx?.path) return;
@@ -148,8 +148,11 @@ function trackActivationEvents(): () => void {
}
};
report(useEditorRegistry.getState().active?.ctx);
// Also when the open file's language changes: a remote project learns plugin languages after the
// window restored its tabs, so a `.twig` file is plain text until the server redetects it.
return useEditorRegistry.subscribe((s, prev) => {
if (s.active?.ctx.path !== prev.active?.ctx.path) report(s.active?.ctx);
if (s.active?.ctx.path !== prev.active?.ctx.path || s.active?.ctx.language !== prev.active?.ctx.language)
report(s.active?.ctx);
});
}
+1
Переглянути файл
@@ -76,6 +76,7 @@ export const UI_KEYS: Record<string, string[]> = {
"--bg-counter": ["Counter.background"],
"--fg-counter": ["Counter.foreground"],
"--bg-search-match": ["SearchMatch.startBackground", "SearchMatch.endBackground"],
"--bg-list-match": ["SearchMatch.startBackground", "SearchMatch.endBackground"],
"--fg-completion-match": ["CompletionPopup.matchForeground"],
"--bg-toggle-on": ["ToggleButton.onBackground"],
"--fg-toggle-on": ["ToggleButton.onForeground"],
+25 -5
Переглянути файл
@@ -15,7 +15,7 @@ import {
} from "@/workbench/iosSimulators";
import styles from "./Run.module.css";
/** Title bar: the simulator Xcode launches use, in projects with an Xcode project on macOS. */
/** Title bar: the simulator or device Xcode launches use, in projects with an Xcode project on macOS. */
export function IosSimulatorChooser() {
const root = useProject((s) => s.project?.root);
useEffect(() => (root ? watchIosSimulators(root) : undefined), [root]);
@@ -23,7 +23,7 @@ export function IosSimulatorChooser() {
return shown ? <Chooser /> : null;
}
const booted = (s: IosSimulator) => s.state === "Booted";
const booted = (s: IosSimulator) => !s.physical && s.state === "Booted";
function Chooser() {
const tx = useTx();
@@ -48,11 +48,31 @@ function Chooser() {
: { label: tx("Boot"), disabled: !!busy || s.state !== "Shutdown", run: () => void bootIosSimulator(s) },
],
});
// A device's row is selectable in any state: the run explains what to do when it is not ready.
const device = (s: IosSimulator): MenuItem => {
const unready =
s.state === "Unavailable"
? tx("Not connected")
: s.state === "Developer Mode Off"
? tx("Developer Mode off")
: null;
return {
id: s.udid,
label: unready ? `${s.name} · ${s.runtime} · ${unready}` : `${s.name} · ${s.runtime}`,
verbatim: true,
checked: s.udid === current?.udid,
hint: s.udid,
performOnSelect: true,
run: () => selectIosSimulator(s.udid),
};
};
const running = (list ?? []).filter(booted);
const idle = (list ?? []).filter((s) => !booted(s));
const idle = (list ?? []).filter((s) => !s.physical && !booted(s));
const devices = (list ?? []).filter((s) => s.physical);
const items: MenuItem[] = [
...(running.length ? [{ kind: "header", label: tx("Booted") } as const, ...running.map(row)] : []),
...(idle.length ? [{ kind: "header", label: tx("Available") } as const, ...idle.map(row)] : []),
...(devices.length ? [{ kind: "header", label: tx("Devices") } as const, ...devices.map(device)] : []),
...(error ? [{ label: error, verbatim: true, disabled: true }] : []),
...(list && !list.length ? [{ label: tx("No simulators available"), disabled: true }] : []),
{ kind: "separator" },
@@ -66,8 +86,8 @@ function Chooser() {
variant="title"
className={styles.widgetDevice}
data-toolbar-icon-dropdown=""
tooltip={tx("iOS Simulator")}
aria-label={tx`iOS Simulator: ${label}`}
tooltip={tx("Run Destination")}
aria-label={tx`Run Destination: ${label}`}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => {
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ describe("Xcode run configurations", () => {
kind: "xcode",
params: { container: "App.xcodeproj", scheme: "App", ...(simulator ? { simulator } : {}) },
}) as unknown as RunConfig;
const sim = (udid: string) => ({ udid, name: udid, runtime: "iOS 27.0", state: "Shutdown" });
const sim = (udid: string) => ({ udid, name: udid, runtime: "iOS 27.0", state: "Shutdown", physical: false });
it("runs an unpinned configuration on the toolbar's simulator", async () => {
useIosSimulators.setState({ list: [sim("A"), sim("B")], preferred: "B" });
+4 -4
Переглянути файл
@@ -1,5 +1,5 @@
/**
* Xcode schemes run on the iOS Simulator, or on the Mac for a macOS app. The host builds, installs and launches the app at
* Xcode schemes run on the iOS Simulator or a connected iPhone or iPad, or on the Mac for a macOS app. The host builds, installs and launches the app at
* launch (`ide_run::xcode::prepare`); the command line here names what is built.
*/
import type { RunConfigTypeContribution } from "@/workbench/contributions";
@@ -9,7 +9,7 @@ export const xcodeType: RunConfigTypeContribution = {
id: "xcode",
label: "Xcode App",
icon: "file-swift",
description: "Build an Xcode scheme and run it on the iOS Simulator or the Mac",
description: "Build an Xcode scheme and run it on the iOS Simulator, a connected device or the Mac",
// Debug launches the app suspended and attaches lldb-dap to it (`debugXcodeApp`).
debugAdapter: "lldb-dap",
fields: [
@@ -25,10 +25,10 @@ export const xcodeType: RunConfigTypeContribution = {
{ key: "configuration", label: "Build configuration", placeholder: "The scheme's" },
{
key: "simulator",
label: "Simulator",
label: "Simulator or device",
mono: true,
placeholder: "A booted simulator, else the newest iPhone",
hint: "A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there",
hint: "A simulator or device UDID (xcrun simctl list devices, xcrun devicectl list devices) pins this configuration to it; macos runs an app that also supports the Mac there",
},
{ key: "arguments", label: "Launch arguments", mono: true },
],
+23
Переглянути файл
@@ -225,4 +225,27 @@ describe("bookmark gutter", () => {
expect(view.dom.querySelector(".cm-openidea-bookmarkMnemonic")?.textContent).toBe("Q");
view.destroy();
});
it("renders an IntelliJ-style bookmark and shows its label in the hover tooltip", () => {
set([
{ path: "/p/a", line: 0, text: "const answer = 42;", created: 1 },
{ path: "/p/a", line: 1, text: "return answer;", created: 2, mnemonic: "Q", description: "Main result" },
{ path: "/p/a", line: 2, text: "", created: 3 },
]);
const view = new EditorView({
parent: document.body,
state: EditorState.create({
doc: "const answer = 42;\nreturn answer;\n\nlast",
extensions: bookmarkGutter("/p/a", () => {}),
}),
});
const icon = view.dom.querySelector(".cm-openidea-bookmark");
expect(icon?.tagName.toLowerCase()).toBe("svg");
expect(icon?.getAttribute("width")).toBe("13");
expect(view.dom.querySelector(".cm-openidea-bookmarkMarker")?.getAttribute("title")).toBe("const answer = 42;");
expect(view.dom.querySelector(".cm-openidea-bookmarkMnemonic")?.getAttribute("title")).toBe("Main result");
expect(view.dom.querySelectorAll("[title='(empty line)']")).toHaveLength(1);
view.destroy();
});
});
+22 -24
Переглянути файл
@@ -9,35 +9,37 @@ import { RangeSet, StateEffect, StateField, type Extension, type Text, type Tran
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import { emptyGutterSpacer } from "@/editor/api";
import { hasPrimaryModifier } from "@/platform/keymap";
import { sortBookmarks, updateBookmarks, useBookmarks, type Bookmark } from "./store";
import { tx } from "@/platform/i18n";
import { iconMarkup } from "@/ui";
import { bookmarkLabel, sortBookmarks, updateBookmarks, useBookmarks, type Bookmark } from "./store";
const SVG_NS = "http://www.w3.org/2000/svg";
const ICON_SIZE = 13;
class BookmarkMarker extends GutterMarker {
constructor(readonly mnemonic: string | null) {
constructor(
readonly mnemonic: string | null,
readonly label: string,
) {
super();
}
override eq(other: GutterMarker): boolean {
return other instanceof BookmarkMarker && other.mnemonic === this.mnemonic;
return other instanceof BookmarkMarker && other.mnemonic === this.mnemonic && other.label === this.label;
}
override toDOM() {
if (this.mnemonic) {
const el = document.createElement("span");
el.className = "cm-openidea-bookmarkMnemonic";
el.textContent = this.mnemonic;
el.setAttribute("aria-label", `Bookmark ${this.mnemonic}`);
el.setAttribute("aria-label", tx`Bookmark ${this.mnemonic}: ${this.label}`);
el.title = this.label;
return el;
}
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "11");
svg.setAttribute("height", "11");
svg.setAttribute("aria-hidden", "true");
svg.classList.add("cm-openidea-bookmark");
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", "M7 4h10v16l-5-4-5 4z");
svg.appendChild(path);
return svg;
const el = document.createElement("span");
el.className = "cm-openidea-bookmarkMarker";
el.setAttribute("aria-label", tx`Bookmark: ${this.label}`);
el.title = this.label;
el.innerHTML = iconMarkup("bookmark", ICON_SIZE, "cm-openidea-bookmark") ?? "";
return el;
}
}
@@ -45,12 +47,11 @@ class SpacerMarker extends GutterMarker {
override toDOM() {
const el = document.createElement("span");
el.style.display = "inline-block";
el.style.width = "11px";
el.style.width = `${ICON_SIZE}px`;
return el;
}
}
const plain = new BookmarkMarker(null);
const spacer = new SpacerMarker();
const setMarks = StateEffect.define<readonly Bookmark[]>();
@@ -60,7 +61,9 @@ function build(doc: Text, bookmarks: readonly Bookmark[]) {
const ranges = bookmarks
.filter((m) => m.line >= 0 && m.line < doc.lines && !seen.has(m.line) && seen.add(m.line))
.sort((a, b) => a.line - b.line)
.map((m) => (m.mnemonic ? new BookmarkMarker(m.mnemonic) : plain).range(doc.line(m.line + 1).from));
.map((m) =>
new BookmarkMarker(m.mnemonic ?? null, bookmarkLabel(m) || tx("(empty line)")).range(doc.line(m.line + 1).from),
);
return { bookmarks, markers: RangeSet.of(ranges) };
}
@@ -209,12 +212,7 @@ const theme = EditorView.baseTheme({
},
// Not on the empty spacer, so the column collapses fully in files without bookmarks.
".cm-openidea-bookmarks .cm-gutterElement:not(:empty)": { padding: "0 2px" },
".cm-openidea-bookmark": {
fill: "none",
stroke: "var(--accent)",
strokeWidth: "2",
strokeLinejoin: "round",
},
".cm-openidea-bookmarkMarker": { display: "inline-flex", alignItems: "center" },
".cm-openidea-bookmarkMnemonic": {
display: "inline-flex",
alignItems: "center",
+10 -1
Переглянути файл
@@ -274,8 +274,17 @@ export function activate(): void | (() => void) {
if (!path || line == null) return [];
const on = hasBookmark(useBookmarks.getState().items, path, line);
return [
...(on
? [
{
label: "Rename Bookmark…",
run: () => useBookmarkPopups.setState({ editing: { path, line } }),
},
]
: []),
{
label: on ? "Remove Bookmark" : "Add Bookmark",
label: on ? "Delete Bookmark" : "Add Bookmark",
...(on ? {} : { icon: "bookmark" as const }),
shortcut: shortcutLabel("navigate.toggleBookmark"),
run: () => void executeAction("navigate.toggleBookmark", { path, line }),
},
+13 -1
Переглянути файл
@@ -219,6 +219,7 @@ export interface SelectProps<V extends string> {
onChange: (value: V) => void;
disabled?: boolean;
onPreview?: (value: V | null) => void;
alignDetails?: boolean;
className?: string;
"aria-label"?: string;
}
@@ -229,6 +230,7 @@ export function Select<V extends string>({
onChange,
disabled,
onPreview,
alignDetails,
className,
...aria
}: SelectProps<V>) {
@@ -239,6 +241,7 @@ export function Select<V extends string>({
onChange={onChange}
disabled={disabled}
onPreview={onPreview}
alignDetails={alignDetails}
className={clsx(styles.select, className)}
aria-label={aria["aria-label"]}
/>
@@ -577,17 +580,26 @@ export function SettingSelect<V extends string>({
hint,
options,
disabled,
alignDetails,
}: {
k: string;
label: string;
hint?: ReactNode;
options: readonly SelectOption<V>[];
disabled?: boolean;
alignDetails?: boolean;
}) {
const [value, set] = useSetting<V>(k);
return (
<Row label={label} hint={hint} disabled={disabled}>
<Select<V> value={value} options={options} onChange={set} disabled={disabled} aria-label={label} />
<Select<V>
alignDetails={alignDetails}
value={value}
options={options}
onChange={set}
disabled={disabled}
aria-label={label}
/>
</Row>
);
}
+3 -1
Переглянути файл
@@ -1133,7 +1133,9 @@ export const VCS_PAGES: PageSpec[] = [
kind: "custom",
label: "Fetch tags",
keywords: ["Auto", "Sync", "Always", "Never", "prune"],
component: () => <SettingSelect k="vcs.git.fetchTagsMode" label="Fetch tags" options={FETCH_TAGS} />,
component: () => (
<SettingSelect k="vcs.git.fetchTagsMode" label="Fetch tags" options={FETCH_TAGS} alignDetails />
),
},
],
},
+5 -2
Переглянути файл
@@ -2373,8 +2373,11 @@
"Booted": "Booted",
"No simulators available": "No simulators available",
"Open Simulator": "Open Simulator",
"iOS Simulator": "iOS Simulator",
"iOS Simulator: {label}": "iOS Simulator: {label}",
"Run Destination": "Run Destination",
"Run Destination: {label}": "Run Destination: {label}",
"Devices": "Devices",
"Not connected": "Not connected",
"Developer Mode off": "Developer Mode off",
"Could not boot {name}": "Could not boot {name}",
"Could not shut down {name}": "Could not shut down {name}",
"Could not open Simulator": "Could not open Simulator",
+3
Переглянути файл
@@ -2714,7 +2714,10 @@
"Rename Bookmark List": "Renombrar lista de marcadores",
"Delete Bookmark List": "Eliminar lista de marcadores",
"Add Bookmark": "Agregar marcador",
"Rename Bookmark…": "Renombrar marcador…",
"Remove Bookmark": "Quitar marcador",
"Bookmark: {label}": "Marcador: {label}",
"Bookmark {mnemonic}: {label}": "Marcador {mnemonic}: {label}",
"Interfaces": "Interfaces",
"Structs": "Structs",
"Enums": "Enums",
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more