дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-15 22:25:48 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
21338d557c |
No files matched your search
@@ -98,10 +98,10 @@ jobs:
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
# nextest ran export_bindings, which rewrites src/bindings.ts and the command snapshot.
|
||||
- name: Bindings and command snapshot are up to date
|
||||
# nextest ran export_bindings, which rewrites src/bindings.ts.
|
||||
- name: Bindings are up to date
|
||||
if: runner.os == 'Linux'
|
||||
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
|
||||
run: git diff --exit-code src/bindings.ts
|
||||
|
||||
# The remote development server ships as a static Linux binary (release-build.yml):
|
||||
# keep that build working.
|
||||
|
||||
Створено
@@ -4578,7 +4578,6 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-extension",
|
||||
"ide-text",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
@@ -4799,7 +4798,6 @@ name = "ide-sdk"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"flate2",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-run",
|
||||
@@ -4809,7 +4807,6 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
@@ -4966,7 +4963,6 @@ dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"gix",
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4977,7 +4973,6 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"trash",
|
||||
|
||||
@@ -90,8 +90,6 @@ dunce = "1"
|
||||
dirs = "6"
|
||||
memmap2 = "0.9"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
flate2 = "1"
|
||||
tar = "0.4"
|
||||
|
||||
# search, index, language
|
||||
grep-searcher = "0.1"
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
|
||||
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Bildiğin IDE, Rust ile yeniden yazıldı.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>İndir</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Belgeler</a>
|
||||
·
|
||||
<a href="#performans-karşılaştırması">Performans</a>
|
||||
·
|
||||
<a href="#eklentiler">Eklentiler</a>
|
||||
·
|
||||
<a href="#topluluk">Topluluk</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA, IntelliJ IDEA'nın çalışma biçimini (kısayol tuşlarını, araç pencerelerini,
|
||||
her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir uygulamaya taşır.
|
||||
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
önbellekler hazırken açma, 5 çalıştırmanın ortancası:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------- | --------------------- | ---------------------- |
|
||||
| Projeyle pencerenin açılması | **0,9 sn** | 3,1 sn |
|
||||
| Hazır (CPU sakinleşti) | **1,1 sn** | 13,2 sn |
|
||||
| Bellek (USS, tüm işlemler) | **169 MB** | 2011 MB |
|
||||
| Hazır olana kadar CPU süresi | **2,4 sn** | 47,9 sn |
|
||||
| Boştayken CPU | Bir çekirdeğin **%4**'ü | Bir çekirdeğin %7'si |
|
||||
| Kapanma | **0,3 sn** | 5,9 sn |
|
||||
|
||||
`main` dalından derlenmiş bir OpenIDEA sürümü ve varsayılan ayar ve eklentilerle IDEA;
|
||||
Windows 11, 32 çekirdekli AMD, 62 GB RAM.
|
||||
IDEA, Python'u daha derinlemesine analiz eder; yani "hazır" iki tarafta aynı işi ifade etmez.
|
||||
İkisi de dışarıdan, aynı yöntemle ölçüldü: kendi makinende ve projelerinde denemek için
|
||||
[`perf/compare`](perf/compare) klasörüne bak.
|
||||
|
||||
## Eklentiler
|
||||
|
||||
Eklentiler; eylemler, kod tamamlama, hızlı düzeltmeler, araç pencereleri, özel editörler,
|
||||
temalar, dosya simgeleri ve diller ekler. Korumalı (sandbox) WebAssembly bileşenleri olarak çalışırlar;
|
||||
temalar, simge temaları ve diller için hiç kod yazmak gerekmez.
|
||||
|
||||
Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya da
|
||||
`openidea-plugin new` ile kendininkini başlat. Ayrıntılar için [OpenIDEA eklentisi yazmak](https://openidea.sh/en/plugins) sayfasına ve
|
||||
[resmi eklentilere](plugins/official) bak. Eklenti API'si hâlâ önizleme aşamasında.
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Lisans
|
||||
|
||||
[Apache 2.0](LICENSE). Pakete dahil üçüncü taraf varlıklar [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) dosyasında listelenir.
|
||||
|
||||
<sub>JetBrains ile bağlantılı değildir. IntelliJ IDEA, JetBrains s.r.o.'nun ticari markasıdır.</sub>
|
||||
@@ -42,8 +42,6 @@ pub struct Settings {
|
||||
pub terminal: TerminalSettings,
|
||||
pub actions_on_save: ActionsOnSaveSettings,
|
||||
pub external_tools: Vec<ExternalTool>,
|
||||
/// Tools › Diff & Merge › External Diff Tools.
|
||||
pub external_diff: ExternalDiffSettings,
|
||||
/// Language servers / debug adapters at a user-chosen location, by the
|
||||
/// command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
pub tools: BTreeMap<String, ToolSettings>,
|
||||
@@ -90,16 +88,6 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// While the agent works, playful words fill the pauses in what it reports.
|
||||
pub playful_status: bool,
|
||||
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
/// from the start.
|
||||
pub playful_after_seconds: u32,
|
||||
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
/// the built-in ones of that activity; an empty list keeps its status factual.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, Vec<String>>)]
|
||||
pub playful_words: BTreeMap<String, Vec<String>>,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -142,9 +130,6 @@ impl Default for AgentSettings {
|
||||
fold_turns: true,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
playful_status: false,
|
||||
playful_after_seconds: 0,
|
||||
playful_words: BTreeMap::new(),
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -484,7 +469,6 @@ impl Default for Settings {
|
||||
debugger: DebuggerSettings::default(),
|
||||
run: RunSettings::default(),
|
||||
terminal: TerminalSettings::default(),
|
||||
external_diff: ExternalDiffSettings::default(),
|
||||
actions_on_save: ActionsOnSaveSettings::default(),
|
||||
external_tools: Vec::new(),
|
||||
tools: BTreeMap::new(),
|
||||
@@ -989,7 +973,6 @@ pub struct LanguagesSettings {
|
||||
pub ruby: RubySettings,
|
||||
pub markdown: MarkdownSettings,
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1012,7 +995,6 @@ impl Default for LanguagesSettings {
|
||||
ruby: RubySettings::default(),
|
||||
markdown: MarkdownSettings::default(),
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1224,13 +1206,6 @@ impl Default for RustSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ZigSettings {
|
||||
/// Directory holding the `zig` executable; empty = the one on `PATH`.
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GoSettings {
|
||||
|
||||
@@ -175,24 +175,6 @@ impl Default for VcsConfirmationSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalDiffSettings {
|
||||
/// Offer Show Diff in External Tool in diff viewers.
|
||||
pub enabled: bool,
|
||||
/// The program to start.
|
||||
pub path: String,
|
||||
/// Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title.
|
||||
pub parameters: String,
|
||||
}
|
||||
|
||||
impl Default for ExternalDiffSettings {
|
||||
fn default() -> Self {
|
||||
Self { enabled: false, path: String::new(), parameters: "%1 %2 %3".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Version Control › Shelf.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -345,8 +327,6 @@ pub struct RunSettings {
|
||||
/// Ask before closing a Run tab whose process is still running.
|
||||
pub confirm_terminate: bool,
|
||||
pub show_on_start: bool,
|
||||
/// New Run/Debug tabs start pinned: a later run doesn't take their place once finished.
|
||||
pub pin_tabs: bool,
|
||||
/// Grace period between interrupt and kill when stopping a process.
|
||||
pub termination_timeout_ms: u32,
|
||||
}
|
||||
@@ -358,7 +338,6 @@ impl Default for RunSettings {
|
||||
confirm_rerun: true,
|
||||
confirm_terminate: true,
|
||||
show_on_start: true,
|
||||
pin_tabs: false,
|
||||
termination_timeout_ms: 3000,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,20 +325,6 @@ pub fn migrate(data: &Path, local: &Path) {
|
||||
if cfg!(target_os = "windows") && data != local {
|
||||
migrate_entries(data, local);
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
relative_tool_shims(&local.join("tools"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrappers written before they named their tool relative to themselves hold its absolute
|
||||
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
|
||||
fn relative_tool_shims(tools: &Path) {
|
||||
let Ok(entries) = fs::read_dir(tools) else { return };
|
||||
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
|
||||
if let Err(error) = relocate_shims(&dir, &dir) {
|
||||
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate_entries(data: &Path, local: &Path) {
|
||||
@@ -665,22 +651,6 @@ mod tests {
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_tool_wrappers_become_relative() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tools = tmp.path().join("tools");
|
||||
let tool = tools.join("taplo");
|
||||
fs::create_dir_all(tool.join("bin")).unwrap();
|
||||
let shim = tool.join("bin/taplo.cmd");
|
||||
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
|
||||
// A wrapper the user re-saved in another encoding is left alone.
|
||||
fs::create_dir_all(tools.join("other/bin")).unwrap();
|
||||
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
|
||||
relative_tool_shims(&tools);
|
||||
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
|
||||
relative_tool_shims(&tmp.path().join("missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
|
||||
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
|
||||
|
||||
@@ -251,12 +251,18 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let (text, notify) = match other {
|
||||
Ok(Ok(outcome)) => failed_build(&outcome),
|
||||
Ok(Err(error)) => (error.message, true),
|
||||
Err(error) => (error.to_string(), true),
|
||||
let text = match other {
|
||||
Ok(Ok(outcome)) => outcome
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|m| m.severity == Severity::Error)
|
||||
.map(|m| m.text.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
Ok(Err(error)) => error.message,
|
||||
Err(error) => error.to_string(),
|
||||
};
|
||||
self.report(text, notify, &mut diagnostics, &mut last_failure);
|
||||
self.failure(text, &mut diagnostics, &mut last_failure);
|
||||
remove_directory(directory).await;
|
||||
}
|
||||
}
|
||||
@@ -270,12 +276,6 @@ impl KotlinBridge {
|
||||
}
|
||||
|
||||
fn failure(&self, text: String, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
|
||||
self.report(text, true, paths, previous);
|
||||
}
|
||||
|
||||
/// Publishes a failed build in Problems (on `pom.xml`) and, when `notify`, as a
|
||||
/// notification once per distinct message.
|
||||
fn report(&self, text: String, notify: bool, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
|
||||
let text = if text.is_empty() { "Kotlin compilation failed".to_owned() } else { text };
|
||||
let text = format!("{text}\nJava temporarily uses the last successfully compiled Kotlin API.");
|
||||
self.clear_diagnostics(paths);
|
||||
@@ -295,7 +295,7 @@ impl KotlinBridge {
|
||||
deprecated: false,
|
||||
}],
|
||||
});
|
||||
if notify && previous != &text {
|
||||
if previous != &text {
|
||||
self.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Error,
|
||||
title: "Kotlin editor compilation failed".into(),
|
||||
@@ -306,15 +306,6 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
|
||||
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
|
||||
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
|
||||
fn failed_build(outcome: &Outcome) -> (String, bool) {
|
||||
let errors: Vec<_> = outcome.messages.iter().filter(|m| m.severity == Severity::Error).collect();
|
||||
let text = errors.iter().map(|m| m.text.as_str()).collect::<Vec<_>>().join("\n");
|
||||
(text, !errors.iter().any(|m| m.path.is_some()))
|
||||
}
|
||||
|
||||
fn relevant_change(root: &Path, path: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
let input = path.extension().is_some_and(|e| e == "kt")
|
||||
|| path.file_name().is_some_and(|n| n == "pom.xml" || n == "mvnw" || n == "mvnw.cmd")
|
||||
@@ -392,23 +383,6 @@ mod tests {
|
||||
assert!(!relevant_change(dir.path(), &dir.path().join("module/src/build/pkg"), &Default::default()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_errors_stay_out_of_notifications() {
|
||||
let message = |text: &str, path: Option<&str>| ide_build::compile::BuildMessage {
|
||||
severity: Severity::Error,
|
||||
text: text.into(),
|
||||
path: path.map(|p| PathBuf::from(p).into()),
|
||||
range: None,
|
||||
code: None,
|
||||
};
|
||||
let outcome = |messages| Outcome { projects: Vec::new(), messages, success: false };
|
||||
let (text, notify) = failed_build(&outcome(vec![message("No value passed", Some("/p/src/A.kt"))]));
|
||||
assert_eq!((text.as_str(), notify), ("No value passed", false));
|
||||
let (text, notify) = failed_build(&outcome(vec![message("Plugin not found", None)]));
|
||||
assert_eq!((text.as_str(), notify), ("Plugin not found", true));
|
||||
assert!(failed_build(&outcome(Vec::new())).1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensionless_root_file_does_not_trigger() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -296,144 +296,39 @@ impl crate::Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands allowed in Restricted Mode, by exact name: those which only inspect/edit source or
|
||||
/// operate user-owned application state. A new command is denied until deliberately listed here.
|
||||
/// Commands which only inspect/edit source or operate user-owned application state.
|
||||
/// New execution commands are denied until deliberately classified here.
|
||||
pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
if [
|
||||
"fs_",
|
||||
"doc_",
|
||||
"syntax_",
|
||||
"search_",
|
||||
"nav_",
|
||||
"history_",
|
||||
"spell_",
|
||||
"analysis_",
|
||||
"structural_",
|
||||
"refactor_",
|
||||
"bytes_",
|
||||
"window_",
|
||||
"window_group_",
|
||||
"term_",
|
||||
"settings_",
|
||||
"project_trust_",
|
||||
// New Project writes only where the user chose and runs no code of an open project.
|
||||
"scaffold_",
|
||||
"ssh_",
|
||||
"git_credential",
|
||||
]
|
||||
.iter()
|
||||
.any(|p| cmd.starts_with(p))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
cmd,
|
||||
"fs_compare_directories"
|
||||
| "fs_copy"
|
||||
| "fs_copy_merge"
|
||||
| "fs_create_dir"
|
||||
| "fs_create_file"
|
||||
| "fs_create_file_bytes"
|
||||
| "fs_delete"
|
||||
| "fs_entry_kind"
|
||||
| "fs_open_with_system"
|
||||
// The user's own diff program (global settings) on the diff's two sides.
|
||||
| "diff_external_tool"
|
||||
| "fs_probe"
|
||||
| "fs_read_dir"
|
||||
| "fs_read_image"
|
||||
| "fs_read_range"
|
||||
| "fs_read_text"
|
||||
| "fs_rename"
|
||||
| "fs_resolve_reference"
|
||||
| "fs_set_writable"
|
||||
| "doc_close"
|
||||
| "doc_edit"
|
||||
| "doc_folding"
|
||||
| "doc_highlights"
|
||||
| "doc_open"
|
||||
| "doc_open_untitled"
|
||||
| "doc_open_virtual"
|
||||
| "doc_outline"
|
||||
| "doc_python_facts"
|
||||
| "doc_save"
|
||||
| "doc_save_as"
|
||||
| "doc_save_all"
|
||||
| "doc_selection_ranges"
|
||||
| "doc_set_bom"
|
||||
| "doc_set_encoding"
|
||||
| "doc_set_line_ending"
|
||||
| "doc_snapshot"
|
||||
| "doc_sync_from_disk"
|
||||
| "doc_ui_mode"
|
||||
| "syntax_errors"
|
||||
| "syntax_expression_at"
|
||||
| "syntax_identifiers"
|
||||
| "syntax_identifiers_in_files"
|
||||
| "syntax_locals"
|
||||
| "syntax_node_at"
|
||||
| "syntax_structural_ranges"
|
||||
| "syntax_support"
|
||||
| "search_start"
|
||||
| "search_validate"
|
||||
| "nav_index_definitions"
|
||||
| "nav_inheritance"
|
||||
| "nav_resolve_module"
|
||||
| "history_content"
|
||||
| "history_list"
|
||||
| "history_list_dir"
|
||||
| "history_put_label"
|
||||
| "history_restore"
|
||||
| "spell_check"
|
||||
| "spell_suggest"
|
||||
| "analysis_locate_duplicates"
|
||||
| "structural_languages"
|
||||
| "structural_search"
|
||||
| "structural_validate"
|
||||
| "refactor_can_undo_file_move"
|
||||
| "refactor_file_move_edits"
|
||||
| "refactor_file_move_text_edits"
|
||||
| "refactor_move_files"
|
||||
| "refactor_undo_file_move"
|
||||
| "window_close_context"
|
||||
| "window_complete_launch"
|
||||
| "window_cycle"
|
||||
| "window_flash_taskbar"
|
||||
| "window_group_cancel_close"
|
||||
| "window_group_close"
|
||||
| "window_group_close_tabs"
|
||||
| "window_group_current"
|
||||
| "window_group_detach"
|
||||
| "window_group_merge"
|
||||
| "window_group_reorder"
|
||||
| "window_group_restore"
|
||||
| "window_group_select"
|
||||
| "window_is_fullscreen"
|
||||
| "window_new"
|
||||
| "window_open_comparison"
|
||||
| "window_open_deployment"
|
||||
| "window_open_diff"
|
||||
| "window_open_file_in_new_window"
|
||||
| "window_open_files"
|
||||
| "window_open_project"
|
||||
| "window_open_projects"
|
||||
| "window_open_remote"
|
||||
| "window_open_settings"
|
||||
| "window_set_titlebar_height"
|
||||
| "window_start_drag"
|
||||
| "window_take_launch"
|
||||
| "window_toggle_fullscreen"
|
||||
| "window_toggle_zoom"
|
||||
| "term_available_shells"
|
||||
| "term_default_shell"
|
||||
| "term_is_busy"
|
||||
| "term_kill"
|
||||
| "term_resize"
|
||||
| "term_spawn"
|
||||
| "term_store_image"
|
||||
| "term_write"
|
||||
| "settings_export"
|
||||
| "settings_get"
|
||||
| "settings_get_global"
|
||||
| "settings_import"
|
||||
| "settings_list_jetbrains_ides"
|
||||
| "settings_read_jetbrains"
|
||||
| "settings_set"
|
||||
| "project_trust_add_location"
|
||||
| "project_trust_list"
|
||||
| "project_trust_remove_location"
|
||||
| "project_trust_set"
|
||||
| "project_trust_status"
|
||||
// New Project writes only where the user chose and runs no code of an open project.
|
||||
| "scaffold_catalog"
|
||||
| "scaffold_create"
|
||||
| "scaffold_options"
|
||||
| "scaffold_requirements"
|
||||
| "ssh_askpass_answer"
|
||||
| "ssh_connected"
|
||||
| "ssh_disconnect"
|
||||
| "ssh_needs_secret"
|
||||
| "ssh_open_terminal"
|
||||
| "ssh_password_saved"
|
||||
| "ssh_set_secret"
|
||||
| "ssh_test"
|
||||
| "ssh_trust_host"
|
||||
| "git_credential_forget"
|
||||
| "git_credentials"
|
||||
| "app_info"
|
||||
"app_info"
|
||||
| "app_build_info"
|
||||
| "app_cli_install"
|
||||
| "app_cli_uninstall"
|
||||
@@ -678,14 +573,6 @@ mod tests {
|
||||
assert!(super::restricted_command_allowed("clipboard_write_text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_mode_denies_new_commands_whatever_their_name() {
|
||||
for cmd in ["fs_new_command", "term_new_command", "ssh_new_command", "settings_new_command", "git_credential_x"]
|
||||
{
|
||||
assert!(!super::restricted_command_allowed(cmd), "{cmd} is allowed without being listed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_project_decisions_are_kept_on_this_machine() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,7 +16,6 @@ toml.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
memchr = "2"
|
||||
regex-lite = "0.1"
|
||||
blake3.workspace = true
|
||||
tree-sitter-language = "0.1"
|
||||
|
||||
@@ -79,16 +79,11 @@ impl<'a> LineIndex<'a> {
|
||||
}
|
||||
|
||||
fn memchr_newlines(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
|
||||
memchr::memchr_iter(b'\n', bytes).map(|i| i + 1)
|
||||
bytes.iter().enumerate().filter(|&(_, &b)| b == b'\n').map(|(i, _)| i + 1)
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_len(s: &str) -> u32 {
|
||||
if s.is_ascii() {
|
||||
return s.len() as u32;
|
||||
}
|
||||
// One unit per char (each starts with a non-continuation byte), two for
|
||||
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
|
||||
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
|
||||
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
|
||||
}
|
||||
|
||||
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
|
||||
|
||||
@@ -12,7 +12,6 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(src) = read(&dir.join("build.zig")) else { return };
|
||||
let src = code_only(&src);
|
||||
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
|
||||
let roots = test_roots(&src);
|
||||
for step in steps(&src) {
|
||||
// `install` is what plain `zig build` runs.
|
||||
if step == "install" || step == "uninstall" {
|
||||
@@ -21,9 +20,6 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
|
||||
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
|
||||
c = c.test();
|
||||
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
|
||||
c.extras.params.insert("testRoot".into(), root.clone());
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
@@ -165,137 +161,6 @@ fn executables(src: &str) -> Vec<Executable> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The call's argument text: from just after its `(` to the matching `)`.
|
||||
fn call_body(src: &str, start: usize) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
for (i, c) in src[start..].char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return &src[start..start + i];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
src
|
||||
}
|
||||
|
||||
/// The first `.root_source_file = <receiver>.path("…")` in `body`.
|
||||
fn root_source_file(body: &str) -> Option<String> {
|
||||
for (i, _) in body.match_indices(".root_source_file") {
|
||||
let Some(v) = body[i + ".root_source_file".len()..].trim_start().strip_prefix('=') else { continue };
|
||||
let v = v.trim_start();
|
||||
if let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
return string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The identifier assigned just before `at`: `const mod = b.addModule(…` → `mod`.
|
||||
fn assigned_var(src: &str, at: usize) -> Option<&str> {
|
||||
let before = src[..at].trim_end();
|
||||
let before = before.strip_suffix('.')?.trim_end();
|
||||
// Drop the receiver (`b`) that sits between the `=` and the call.
|
||||
let receiver =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
let before = before[..receiver].trim_end();
|
||||
let before = before.strip_suffix('=')?.trim_end();
|
||||
let start =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
Some(&before[start..])
|
||||
}
|
||||
|
||||
/// The test root behind each test-named step (`zig build <step>`): the step's `dependOn` runs
|
||||
/// an `addTest` artifact — a variable (`const tests = b.addTest(…)`) or an inline call — whose
|
||||
/// module's `root_source_file` this resolves (through `addModule`/`createModule` variables).
|
||||
/// `zig build` forwards no args to the test binary, so rerunning a single failed test goes
|
||||
/// through a standalone `zig test <root> --test-filter …` on the step's own test module.
|
||||
fn test_roots(src: &str) -> Vec<(String, String)> {
|
||||
let mut modules: Vec<(String, String)> = Vec::new();
|
||||
for key in ["addModule(", "createModule("] {
|
||||
for (i, _) in src.match_indices(key) {
|
||||
let Some(root) = root_source_file(call_body(src, i + key.len())) else { continue };
|
||||
if let Some(var) = assigned_var(src, i)
|
||||
&& !modules.iter().any(|(m, _)| *m == var)
|
||||
{
|
||||
modules.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
}
|
||||
let module_root = |body: &str| -> Option<String> {
|
||||
root_source_file(body).or_else(|| {
|
||||
let at = body.find(".root_module")?;
|
||||
let v = body[at + ".root_module".len()..].trim_start().strip_prefix('=')?.trim_start();
|
||||
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
modules.iter().find(|(m, _)| *m == var).map(|(_, root)| root.clone())
|
||||
})
|
||||
};
|
||||
let mut tests: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices("addTest(") {
|
||||
let Some(root) = module_root(call_body(src, i + "addTest(".len())) else { continue };
|
||||
if let Some(var) = assigned_var(src, i)
|
||||
&& !tests.iter().any(|(v, _)| *v == var)
|
||||
{
|
||||
tests.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
// The match includes the dot, so the assignment ends one character earlier.
|
||||
if let Some(var) = assigned_var(src, i + 1) {
|
||||
steps.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step) = receiver_var(src, i + 1) else { continue };
|
||||
let Some((_, name)) = steps.iter().find(|(v, _)| v == step) else { continue };
|
||||
let after = &src[i + ".dependOn(&".len()..];
|
||||
let artifact = if let Some(at) = after.find("addRunArtifact(") {
|
||||
let v = &after[at + "addRunArtifact(".len()..];
|
||||
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
tests.iter().find(|(v, _)| *v == var).map(|(_, root)| root.clone())
|
||||
} else if let Some(at) = after.find("addTest(") {
|
||||
module_root(call_body(after, at + "addTest(".len()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(root) = artifact
|
||||
&& name.starts_with("test")
|
||||
&& !out.iter().any(|(n, _)| n == name)
|
||||
{
|
||||
out.push((name.clone(), root));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The identifier a method is called on just before `at`: `test_step.dependOn(…` → `test_step`.
|
||||
fn receiver_var(src: &str, at: usize) -> Option<&str> {
|
||||
let before = src[..at].trim_end();
|
||||
let before = before.strip_suffix('.')?;
|
||||
let start =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
Some(&before[start..])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -325,9 +190,7 @@ pub fn build(b: *std.Build) void {
|
||||
}) });
|
||||
_ = tool;
|
||||
const run_step = b.step("run", "Run the app");
|
||||
const tests = b.addTest(.{ .root_module = mod });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
const docs = b.step("docs", "Generate docs // not a comment");
|
||||
_ = .{ run_step, test_step, docs };
|
||||
}
|
||||
@@ -365,39 +228,5 @@ pub fn build(b: *std.Build) void {
|
||||
assert_eq!(app.extras.before_launch[0].kind, "run");
|
||||
assert_eq!(app.extras.before_launch[0].target, BUILD_ID);
|
||||
assert_eq!(app.extras.params.get("source").map(String::as_str), Some("src/main.zig"));
|
||||
assert_eq!(test.extras.params.get("testRoot").map(String::as_str), Some("src/root.zig"));
|
||||
}
|
||||
|
||||
const TEST_ROOTS: &str = r#"const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const tally = b.addModule("tally", .{ .root_source_file = b.path("src/tally.zig") });
|
||||
const unit = b.addTest(.{ .root_module = tally });
|
||||
const test_step = b.step("test", "Run the unit tests");
|
||||
test_step.dependOn(&b.addRunArtifact(unit).step);
|
||||
const failing = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/failing.zig"),
|
||||
}) });
|
||||
const test_failing_step = b.step("test-failing", "Run the failing tests");
|
||||
test_failing_step.dependOn(&b.addRunArtifact(failing).step);
|
||||
const direct = b.addTest(.{ .root_source_file = b.path("src/direct.zig") });
|
||||
const test_direct_step = b.step("test-direct", "Run the direct tests");
|
||||
test_direct_step.dependOn(&b.addRunArtifact(direct).step);
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&b.addRunArtifact(unit).step);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn test_roots_come_from_the_step_s_own_artifact() {
|
||||
let src = code_only(TEST_ROOTS);
|
||||
assert_eq!(
|
||||
test_roots(&src),
|
||||
[
|
||||
("test".to_owned(), "src/tally.zig".to_owned()),
|
||||
("test-failing".to_owned(), "src/failing.zig".to_owned()),
|
||||
("test-direct".to_owned(), "src/direct.zig".to_owned()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,3 @@ toml.workspace = true
|
||||
tracing.workspace = true
|
||||
url = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
flate2.workspace = true
|
||||
tar.workspace = true
|
||||
@@ -141,12 +141,6 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
|
||||
}
|
||||
|
||||
/// The directory of the configured Zig install (holding `zig`), else `None` for `PATH`.
|
||||
pub(crate) fn zig_bin(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.zig.zig)
|
||||
.map(|p| if p.is_file() { p.parent().map(Path::to_path_buf).unwrap_or(p) } else { p })
|
||||
}
|
||||
|
||||
/// Runtime choices for package-manager based IDE tool installs.
|
||||
#[derive(Default)]
|
||||
pub struct ToolInstallEnvironment {
|
||||
|
||||
@@ -26,7 +26,6 @@ pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod vue;
|
||||
mod zig;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
//! Project view): the folders holding the sources of the project's SDKs and
|
||||
//! dependencies — the Python interpreter's standard library and site-packages,
|
||||
//! the JDK, `node_modules` packages, Cargo crates and the Rust standard
|
||||
//! library, GOROOT and the Go module cache, the Zig standard library and the
|
||||
//! fetched packages of `build.zig.zon`.
|
||||
//! library, GOROOT and the Go module cache.
|
||||
//!
|
||||
//! Ecosystems are detected in the project and its modules. SDK and graph probes
|
||||
//! are cached until manifests or settings change; Node packages are read on refresh.
|
||||
@@ -29,7 +28,7 @@ use std::time::{Duration, SystemTime};
|
||||
pub struct LibraryGroup {
|
||||
/// Display name, e.g. `Python 3.12 (.venv)`.
|
||||
pub name: String,
|
||||
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`.
|
||||
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
|
||||
pub kind: String,
|
||||
pub roots: Vec<LibraryRoot>,
|
||||
}
|
||||
@@ -57,7 +56,6 @@ const JAVA_MANIFESTS: &[&str] =
|
||||
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
|
||||
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
|
||||
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
|
||||
const ZIG_MANIFESTS: &[&str] = &["build.zig.zon", "build.zig"];
|
||||
|
||||
/// A Maven / Gradle dependency of the project, from the build model.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -85,7 +83,7 @@ pub fn project_libraries_stream(
|
||||
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
|
||||
) -> Vec<LibraryGroup> {
|
||||
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
|
||||
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
|
||||
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups];
|
||||
let roots = library_project_roots(root, cancel);
|
||||
let settings = module_settings(root, settings);
|
||||
std::thread::scope(|s| {
|
||||
@@ -195,8 +193,6 @@ fn library_project_roots(root: &Path, cancel: &CancellationToken) -> Vec<PathBuf
|
||||
"setup.py",
|
||||
"requirements.txt",
|
||||
".python-version",
|
||||
"build.zig",
|
||||
"build.zig.zon",
|
||||
".tool-versions",
|
||||
"mise.toml",
|
||||
]
|
||||
@@ -256,7 +252,6 @@ fn module_settings(root: &Path, settings: &Settings) -> Settings {
|
||||
&mut l.rust.stdlib,
|
||||
&mut l.go.goroot,
|
||||
&mut l.go.gopath,
|
||||
&mut l.zig.zig,
|
||||
&mut l.java.jdk,
|
||||
] {
|
||||
// `target:<id>` names a run target, not a path.
|
||||
@@ -1003,80 +998,6 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ zig
|
||||
|
||||
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
|
||||
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
|
||||
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
|
||||
let Some(env) = query_in_cancellable(&zig, &["env"], root, &[], QUERY_TIMEOUT, cancel)
|
||||
.as_deref()
|
||||
.and_then(crate::zig::parse_zig_env)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let version =
|
||||
env.version.clone().or_else(|| query_in_cancellable(&zig, &["version"], root, &[], QUERY_TIMEOUT, cancel));
|
||||
let name = match version.as_deref().map(str::trim) {
|
||||
Some(v) if !v.is_empty() => format!("Zig {v}"),
|
||||
_ => "Zig".into(),
|
||||
};
|
||||
out.extend(env.std_sources().and_then(|std| group(name, "zig", library_roots(vec![std]))));
|
||||
if let Some(cache) = env.global_cache_dir.as_deref() {
|
||||
let zon = std::fs::read_to_string(root.join("build.zig.zon")).unwrap_or_default();
|
||||
let deps = crate::zig::zon_dependencies(&zon);
|
||||
out.extend(group("Zig packages", "zigPackages", zig_package_roots(cache, &deps)));
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// The fetched sources of a `build.zig.zon`'s dependencies: `p/<hash>` folders
|
||||
/// (Zig ≤ 0.14 unpacks them) or the package root inside `p/<hash>.tar.gz` (Zig
|
||||
/// ≥ 0.15 keeps packages as blobs, browsed through the archive VFS). Path
|
||||
/// dependencies stay in the project tree; unfetched packages are simply absent —
|
||||
/// listing libraries never downloads.
|
||||
fn zig_package_roots(cache: &Path, deps: &[crate::zig::ZonDependency]) -> Vec<LibraryRoot> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
deps.iter()
|
||||
.filter_map(|d| {
|
||||
let hash = d.hash.as_deref()?;
|
||||
let dir = cache.join("p").join(hash);
|
||||
if dir.is_dir() {
|
||||
let zon = std::fs::read_to_string(dir.join("build.zig.zon")).unwrap_or_default();
|
||||
let name =
|
||||
match (crate::zig::zon_string_field(&zon, "name"), crate::zig::zon_string_field(&zon, "version")) {
|
||||
(Some(name), Some(version)) => format!("{name} {version}"),
|
||||
(Some(name), None) => name,
|
||||
_ => hash.to_owned(),
|
||||
};
|
||||
return Some((name, dir));
|
||||
}
|
||||
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
|
||||
blob.is_file().then_some(hash).map(|hash| {
|
||||
// The blob's only top-level folder is the package (`<hash>/`); fall back to
|
||||
// the archive root should that layout ever change.
|
||||
let entry = if ide_vfs::read_archive_dir(&blob, hash).is_ok() { hash } else { "" };
|
||||
(package_label(d, hash), ide_vfs::archive_entry_path(&blob, entry))
|
||||
})
|
||||
})
|
||||
.filter(|(_, path)| seen.insert(path.to_string_lossy().into_owned()))
|
||||
.map(|(name, path)| LibraryRoot { name, path: path.into() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `probe_pkg 0.1.0` from a Zig ≥ 0.15 package hash (`name-version-<hash>`).
|
||||
fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
|
||||
let Some((rest, _)) = hash.rsplit_once('-') else { return dep.name.clone() };
|
||||
let mut parts: Vec<&str> = rest.split('-').collect();
|
||||
let version = parts.pop().unwrap_or_default();
|
||||
match parts.is_empty() || !version.starts_with(|c: char| c.is_ascii_digit()) || !version.contains('.') {
|
||||
true => dep.name.clone(),
|
||||
false => format!("{} {version}", parts.join("-")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod go_cache_tests {
|
||||
use super::*;
|
||||
@@ -1466,127 +1387,3 @@ mod idea_project_tests {
|
||||
assert!(idea_java_project(root));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod zig_tests {
|
||||
use super::*;
|
||||
use crate::zig::ZonDependency;
|
||||
|
||||
/// Writes a Zig package blob (`p/<hash>.tar.gz`) with a `<hash>/` root folder.
|
||||
fn write_package_blob(cache: &Path, hash: &str, files: &[(&str, &str)]) {
|
||||
use flate2::write::GzEncoder;
|
||||
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
|
||||
std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
|
||||
let enc = GzEncoder::new(std::fs::File::create(blob).unwrap(), flate2::Compression::default());
|
||||
let mut tar = tar::Builder::new(enc);
|
||||
for (name, text) in files {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(text.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
tar.append_data(&mut header, name, text.as_bytes()).unwrap();
|
||||
}
|
||||
tar.into_inner().unwrap().finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zig_packages_come_from_the_global_cache_without_fetching() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cache = tmp.path();
|
||||
let (hash, old) = ("zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8", "1220b7c0");
|
||||
write_package_blob(cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
|
||||
let unpacked = cache.join("p").join(old);
|
||||
std::fs::create_dir_all(&unpacked).unwrap();
|
||||
std::fs::write(unpacked.join("build.zig.zon"), r#".{ .name = .old_pkg, .version = "0.2.0" }"#).unwrap();
|
||||
let deps = [
|
||||
ZonDependency { name: "zap".into(), hash: Some(hash.into()), path: None, lazy: false },
|
||||
ZonDependency { name: "shared".into(), hash: None, path: Some("../shared".into()), lazy: false },
|
||||
ZonDependency { name: "gone".into(), hash: Some("gone-1.0.0-BBBBBBBBBB".into()), path: None, lazy: true },
|
||||
ZonDependency { name: "old".into(), hash: Some(old.into()), path: None, lazy: false },
|
||||
];
|
||||
let roots = zig_package_roots(cache, &deps);
|
||||
let summary: Vec<(String, String)> =
|
||||
roots.iter().map(|r| (r.name.clone(), r.path.to_string_lossy().into_owned())).collect();
|
||||
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
|
||||
assert_eq!(
|
||||
summary,
|
||||
[
|
||||
("zap 0.1.0".into(), format!("{}!/{hash}", blob.display())),
|
||||
("old_pkg 0.2.0".into(), unpacked.to_string_lossy().into_owned())
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zig_package_labels_parse_from_the_hash() {
|
||||
let dep = |name: &str| ZonDependency { name: name.into(), hash: None, path: None, lazy: false };
|
||||
assert_eq!(package_label(&dep("zap"), "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8"), "zap 0.1.0");
|
||||
assert_eq!(
|
||||
package_label(&dep("diffz"), "diffz-0.0.1-G2tlISvOAQDORzPTSxDgiKwlHuADKeJMdJrw4kRfLufj"),
|
||||
"diffz 0.0.1"
|
||||
);
|
||||
assert_eq!(
|
||||
package_label(&dep("zig-anytype"), "zig-anytype-0.1.0-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
|
||||
"zig-anytype 0.1.0"
|
||||
);
|
||||
assert_eq!(package_label(&dep("old"), "1220b7c0"), "old");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn zig_libraries_list_the_stdlib_and_fetched_packages() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let stdlib = root.join("stdlib");
|
||||
std::fs::create_dir_all(&stdlib).unwrap();
|
||||
std::fs::write(root.join("build.zig"), "").unwrap();
|
||||
let hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
|
||||
let cache = root.join("zig-cache");
|
||||
write_package_blob(&cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
|
||||
std::fs::write(
|
||||
root.join("build.zig.zon"),
|
||||
r#".{
|
||||
.name = .app,
|
||||
.dependencies = .{
|
||||
// the package cache holds this one
|
||||
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8" },
|
||||
.local = .{ .path = "../shared" },
|
||||
.gone = .{ .url = "https://example.com/gone.tar.gz", .hash = "gone-1.0.0-BBBBBBBBBB" },
|
||||
},
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let bin = root.join("tools");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
let zig = bin.join("zig");
|
||||
std::fs::write(
|
||||
&zig,
|
||||
format!(
|
||||
"#!/bin/sh\ncase \"$1\" in\n env) printf '%s\\n' '.{{\n .zig_exe = \"{}\",\n .std_dir = \"{}\",\n .global_cache_dir = \"{}\",\n .version = \"0.16.0\",\n}}' ;;\n version) echo 0.16.0 ;;\nesac\n",
|
||||
zig.display(),
|
||||
stdlib.display(),
|
||||
cache.display(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.zig.zig = "tools".into();
|
||||
let groups = zig_groups(root, &settings, &CancellationToken::new());
|
||||
let summary: Vec<(&str, &str, Vec<&str>)> = groups
|
||||
.iter()
|
||||
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
[("Zig 0.16.0", "zig", vec!["stdlib"]), ("Zig packages", "zigPackages", vec!["zap 0.1.0"])]
|
||||
);
|
||||
let packages = groups.iter().find(|g| g.kind == "zigPackages").unwrap();
|
||||
assert_eq!(
|
||||
packages.roots[0].path.to_string_lossy(),
|
||||
format!("{}!/{hash}", cache.join("p").join(format!("{hash}.tar.gz")).display())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1589,85 +1589,6 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_zig_zon_dependencies_are_parsed() {
|
||||
let zon = r#"// the manifest is a Zig struct literal
|
||||
.{
|
||||
.name = .app,
|
||||
.version = "0.1.0",
|
||||
.fingerprint = 0x348e9ddfb4b9e03c,
|
||||
.dependencies = .{
|
||||
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-AAA" },
|
||||
.@"weird name" = .{
|
||||
.url = "https://example.com/w.tar.gz",
|
||||
.hash = "weird-2.0.0-BBB",
|
||||
.lazy = true,
|
||||
},
|
||||
.shared = .{ .path = "../shared" },
|
||||
},
|
||||
.paths = .{ "build.zig", "src" },
|
||||
}
|
||||
"#;
|
||||
assert_eq!(
|
||||
crate::zig::zon_dependencies(zon),
|
||||
[
|
||||
crate::zig::ZonDependency {
|
||||
name: "zap".into(),
|
||||
hash: Some("zap-0.1.0-AAA".into()),
|
||||
path: None,
|
||||
lazy: false
|
||||
},
|
||||
crate::zig::ZonDependency {
|
||||
name: "weird name".into(),
|
||||
hash: Some("weird-2.0.0-BBB".into()),
|
||||
path: None,
|
||||
lazy: true
|
||||
},
|
||||
crate::zig::ZonDependency {
|
||||
name: "shared".into(),
|
||||
hash: None,
|
||||
path: Some("../shared".into()),
|
||||
lazy: false
|
||||
},
|
||||
]
|
||||
);
|
||||
assert!(crate::zig::zon_dependencies(".{ .name = .app, .dependencies = .{} }").is_empty());
|
||||
assert!(crate::zig::zon_dependencies(".{ .name = .app }").is_empty());
|
||||
assert!(crate::zig::zon_dependencies("{ broken").is_empty());
|
||||
assert_eq!(
|
||||
crate::zig::zon_string_field(".{ .name = .probe_pkg, .version = \"0.1.0\" }", "name").as_deref(),
|
||||
Some("probe_pkg")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zig_env_is_parsed_from_json_and_struct_literals() {
|
||||
let env = crate::zig::parse_zig_env(
|
||||
r#"{"zig_exe":"/opt/zig/zig","lib_dir":"/opt/zig/lib","std_dir":"/opt/zig/lib/std","global_cache_dir":"/home/u/.cache/zig","version":"0.14.1"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
|
||||
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
|
||||
|
||||
// Zig ≥ 0.15 prints a struct literal; a relative std_dir resolves against the install dir.
|
||||
let env = crate::zig::parse_zig_env(
|
||||
r#".{
|
||||
.zig_exe = "/opt/zig/zig",
|
||||
.lib_dir = "/opt/zig/lib",
|
||||
.std_dir = "lib/std",
|
||||
.global_cache_dir = "/home/u/.cache/zig",
|
||||
.version = "0.16.0",
|
||||
.target = "aarch64-macos",
|
||||
.env = .{ .ZIG_GLOBAL_CACHE_DIR = null, .HOME = "/home/u" },
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
|
||||
assert_eq!(env.version.as_deref(), Some("0.16.0"));
|
||||
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
|
||||
assert!(crate::zig::parse_zig_env("error: nothing").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdk_library_is_the_jdk_home() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
//! Reading Zig's own text formats for External Libraries, without running Zig:
|
||||
//! the package manifest (`build.zig.zon`) and the `zig env` output. Both are
|
||||
//! Zig struct literals; `zig env` printed JSON before Zig 0.15.
|
||||
|
||||
use serde::Deserialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// One `.dependencies` entry of a `build.zig.zon`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ZonDependency {
|
||||
pub name: String,
|
||||
/// Package hash: its sources are fetched into the global cache as `p/<hash>`
|
||||
/// (Zig ≤ 0.14 unpacks them, Zig ≥ 0.15 keeps `p/<hash>.tar.gz` blobs).
|
||||
pub hash: Option<String>,
|
||||
/// A path dependency, part of the project tree rather than the package cache.
|
||||
pub path: Option<String>,
|
||||
/// Fetched only when the build actually references it.
|
||||
pub lazy: bool,
|
||||
}
|
||||
|
||||
/// The `.dependencies` entries of a `build.zig.zon`, in order. Tolerant of
|
||||
/// partially edited files: whatever does not parse is skipped.
|
||||
pub(crate) fn zon_dependencies(zon: &str) -> Vec<ZonDependency> {
|
||||
let src = code_only(zon);
|
||||
let Some(top) = struct_body(&src) else { return Vec::new() };
|
||||
let Some((_, value)) = fields(top).into_iter().find(|(name, _)| *name == "dependencies") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(deps) = struct_body(value) else { return Vec::new() };
|
||||
fields(deps)
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
let entry = struct_body(value).map(|body| fields(body)).unwrap_or_default();
|
||||
ZonDependency {
|
||||
name: name.to_owned(),
|
||||
hash: field(&entry, "hash"),
|
||||
path: field(&entry, "path"),
|
||||
lazy: entry.iter().any(|(n, v)| *n == "lazy" && v.trim() == "true"),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A top-level string (or enum-literal, `.name`) field of a Zig struct literal.
|
||||
pub(crate) fn zon_string_field(text: &str, name: &str) -> Option<String> {
|
||||
let src = code_only(text);
|
||||
let top = struct_body(&src)?;
|
||||
field(&fields(top), name)
|
||||
}
|
||||
|
||||
/// What `zig env` reports that External Libraries needs.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct ZigEnv {
|
||||
pub zig_exe: Option<PathBuf>,
|
||||
pub lib_dir: Option<PathBuf>,
|
||||
pub std_dir: Option<PathBuf>,
|
||||
pub global_cache_dir: Option<PathBuf>,
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
impl ZigEnv {
|
||||
/// The standard library sources: `std_dir`, else `lib_dir/std`. A relative
|
||||
/// path resolves against the zig install dir (stage builds print relative paths).
|
||||
pub(crate) fn std_sources(&self) -> Option<PathBuf> {
|
||||
let resolve = |p: &Path| match (p.is_relative(), self.zig_exe.as_ref().and_then(|e| e.parent())) {
|
||||
(true, Some(install)) => install.join(p),
|
||||
_ => p.to_path_buf(),
|
||||
};
|
||||
self.std_dir
|
||||
.as_deref()
|
||||
.map(Path::new)
|
||||
.map(resolve)
|
||||
.or_else(|| self.lib_dir.as_deref().map(Path::new).map(|dir| resolve(dir).join("std")))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `zig env` output: JSON (older Zig) or a struct literal (Zig ≥ 0.15).
|
||||
pub(crate) fn parse_zig_env(out: &str) -> Option<ZigEnv> {
|
||||
#[derive(Deserialize)]
|
||||
struct Json {
|
||||
zig_exe: Option<PathBuf>,
|
||||
lib_dir: Option<PathBuf>,
|
||||
std_dir: Option<PathBuf>,
|
||||
global_cache_dir: Option<PathBuf>,
|
||||
version: Option<String>,
|
||||
}
|
||||
if let Ok(json) = serde_json::from_str::<Json>(out.trim()) {
|
||||
return Some(ZigEnv {
|
||||
zig_exe: json.zig_exe,
|
||||
lib_dir: json.lib_dir,
|
||||
std_dir: json.std_dir,
|
||||
global_cache_dir: json.global_cache_dir,
|
||||
version: json.version,
|
||||
});
|
||||
}
|
||||
let src = code_only(out);
|
||||
let top = struct_body(&src)?;
|
||||
let f = fields(top);
|
||||
Some(ZigEnv {
|
||||
zig_exe: field(&f, "zig_exe").map(PathBuf::from),
|
||||
lib_dir: field(&f, "lib_dir").map(PathBuf::from),
|
||||
std_dir: field(&f, "std_dir").map(PathBuf::from),
|
||||
global_cache_dir: field(&f, "global_cache_dir").map(PathBuf::from),
|
||||
version: field(&f, "version"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The string (or enum-literal, `.foo`) value of a field of a struct body.
|
||||
fn field<'a>(entry: &[(&'a str, &'a str)], name: &str) -> Option<String> {
|
||||
let value = entry.iter().find(|(n, _)| *n == name)?.1;
|
||||
if let Some(string) = string_value(value) {
|
||||
return Some(string);
|
||||
}
|
||||
value
|
||||
.strip_prefix('.')
|
||||
.filter(|v| v.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The contents of the string literal starting at `value`, `\"` unescaped.
|
||||
fn string_value(value: &str) -> Option<String> {
|
||||
let rest = value.trim_start().strip_prefix('"')?;
|
||||
let mut out = String::new();
|
||||
let mut chars = rest.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'"' => return Some(out),
|
||||
'\\' => out.push(chars.next()?),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `src` with comments blanked out and string contents kept.
|
||||
fn code_only(src: &str) -> String {
|
||||
let mut out = String::with_capacity(src.len());
|
||||
for line in src.lines() {
|
||||
let bytes = line.as_bytes();
|
||||
let mut in_string = false;
|
||||
let mut escaped = false;
|
||||
let mut end = line.len();
|
||||
for (i, &b) in bytes.iter().enumerate() {
|
||||
if in_string {
|
||||
match b {
|
||||
_ if escaped => escaped = false,
|
||||
b'\\' => escaped = true,
|
||||
b'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
} else if b == b'"' {
|
||||
in_string = true;
|
||||
} else if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.push_str(&line[..end]);
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The inside of the first `{ … }` of `text`, strings respected.
|
||||
fn struct_body(text: &str) -> Option<&str> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut start = 0;
|
||||
while start < bytes.len() {
|
||||
match bytes[start] {
|
||||
b'"' => start = skip_string(text, start),
|
||||
b'{' => break,
|
||||
_ => start += 1,
|
||||
}
|
||||
}
|
||||
let mut depth = 0;
|
||||
let mut i = start;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'"' => i = skip_string(text, i),
|
||||
b'{' => {
|
||||
depth += 1;
|
||||
i += 1;
|
||||
}
|
||||
b'}' => {
|
||||
if depth == 1 {
|
||||
return Some(&text[start + 1..i]);
|
||||
}
|
||||
depth -= 1;
|
||||
i += 1;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The index just past the string literal starting at `i` (an opening `"`).
|
||||
fn skip_string(text: &str, i: usize) -> usize {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = i + 1;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\\' => i += 2,
|
||||
b'"' => return i + 1,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// The `.name = value` fields of a struct literal body, in order: `name` is the
|
||||
/// identifier (or `@"…"` unquoted), `value` trimmed and may itself be `.{ … }`.
|
||||
fn fields(body: &str) -> Vec<(&str, &str)> {
|
||||
let bytes = body.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut depth = 0;
|
||||
let mut field: Option<usize> = None;
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'"' => i = skip_string(body, i),
|
||||
b'{' | b'[' | b'(' => {
|
||||
depth += 1;
|
||||
i += 1;
|
||||
}
|
||||
b'}' | b']' | b')' => {
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
depth -= 1;
|
||||
i += 1;
|
||||
}
|
||||
b',' if depth == 0 => {
|
||||
if let Some(start) = field.take() {
|
||||
push_field(&mut out, body, start, i);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
b'.' if depth == 0 && field.is_none() => {
|
||||
if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'@') {
|
||||
field = Some(i + 1);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
if let Some(start) = field {
|
||||
push_field(&mut out, body, start, bytes.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn push_field<'a>(out: &mut Vec<(&'a str, &'a str)>, body: &'a str, start: usize, end: usize) {
|
||||
let text = &body[start..end];
|
||||
let Some(eq) = text.find('=') else { return };
|
||||
let name = text[..eq].trim().trim_start_matches('@').trim_matches('"');
|
||||
if !name.is_empty() {
|
||||
out.push((name, text[eq + 1..].trim()));
|
||||
}
|
||||
}
|
||||
@@ -56,12 +56,7 @@ impl<'a> Lines<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_len(s: &str) -> u32 {
|
||||
if s.is_ascii() {
|
||||
return s.len() as u32;
|
||||
}
|
||||
// One unit per char (each starts with a non-continuation byte), two for
|
||||
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
|
||||
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
|
||||
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
|
||||
}
|
||||
|
||||
fn utf16_to_byte(s: &str, offset: usize) -> usize {
|
||||
|
||||
@@ -39,10 +39,6 @@ impl LineEnding {
|
||||
/// The dominant line ending of `text`; ties and text without any line
|
||||
/// break resolve to [`LineEnding::Lf`].
|
||||
pub fn detect(text: &str) -> Self {
|
||||
// Without `\r` both other counts are zero and `Lf` wins outright.
|
||||
if !text.contains('\r') {
|
||||
return Self::Lf;
|
||||
}
|
||||
let (mut lf, mut crlf, mut cr) = (0usize, 0usize, 0usize);
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
@@ -76,20 +72,13 @@ const DIFF_BUDGET: Duration = Duration::from_millis(50);
|
||||
|
||||
type LineRange = std::ops::Range<usize>;
|
||||
|
||||
/// Byte lengths of the common prefix and suffix; they never overlap. Compared
|
||||
/// byte-wise (equal bytes imply equal chars) so the scan vectorizes, with the
|
||||
/// ends backed off to char boundaries.
|
||||
/// Byte lengths of the common prefix and suffix; they never overlap.
|
||||
fn common_ends(a: &str, b: &str) -> (usize, usize) {
|
||||
let (ab, bb) = (a.as_bytes(), b.as_bytes());
|
||||
let mut prefix = ab.iter().zip(bb).take_while(|(x, y)| x == y).count();
|
||||
while !a.is_char_boundary(prefix) {
|
||||
prefix -= 1;
|
||||
}
|
||||
let limit = ab.len().min(bb.len()) - prefix;
|
||||
let mut suffix = ab.iter().rev().zip(bb.iter().rev()).take(limit).take_while(|(x, y)| x == y).count();
|
||||
while suffix > 0 && !a.is_char_boundary(a.len() - suffix) {
|
||||
suffix -= 1;
|
||||
}
|
||||
let shared = |a: &mut dyn Iterator<Item = char>, b: &mut dyn Iterator<Item = char>| -> usize {
|
||||
a.zip(b).take_while(|(x, y)| x == y).map(|(x, _)| x.len_utf8()).sum()
|
||||
};
|
||||
let prefix = shared(&mut a.chars(), &mut b.chars());
|
||||
let suffix = shared(&mut a[prefix..].chars().rev(), &mut b[prefix..].chars().rev());
|
||||
(prefix, suffix)
|
||||
}
|
||||
|
||||
@@ -105,13 +94,7 @@ fn line_starts(lines: &[&str]) -> Vec<usize> {
|
||||
}
|
||||
|
||||
fn utf16_len(text: &str) -> u32 {
|
||||
let bytes = text.as_bytes();
|
||||
if bytes.is_ascii() {
|
||||
return bytes.len() as u32;
|
||||
}
|
||||
// One unit per char (each starts with a non-continuation byte), two for
|
||||
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
|
||||
bytes.iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
|
||||
text.chars().map(|c| c.len_utf16() as u32).sum()
|
||||
}
|
||||
|
||||
/// Converts `\r\n` and lone `\r` to `\n`. Borrows when there is nothing to do.
|
||||
@@ -175,12 +158,8 @@ pub struct Document {
|
||||
impl Document {
|
||||
/// Builds a document from text with any line endings; detects and normalizes them.
|
||||
pub fn new(text: &str) -> Self {
|
||||
// One `\r` scan decides both: LF text needs no normalization pass.
|
||||
let (line_ending, rope) = if text.contains('\r') {
|
||||
(LineEnding::detect(text), ropey::Rope::from_str(&normalize_line_endings(text)))
|
||||
} else {
|
||||
(LineEnding::Lf, ropey::Rope::from_str(text))
|
||||
};
|
||||
let line_ending = LineEnding::detect(text);
|
||||
let rope = ropey::Rope::from_str(&normalize_line_endings(text));
|
||||
Self { rope, version: 0, line_ending }
|
||||
}
|
||||
|
||||
|
||||
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
@@ -357,25 +357,11 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
|
||||
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
|
||||
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
|
||||
#[cfg_attr(unix, allow(dead_code))]
|
||||
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
|
||||
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
|
||||
Some(rest) => {
|
||||
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
format!("%~dp0..\\{}", rest.join("\\"))
|
||||
}
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -757,17 +743,6 @@ mod tests {
|
||||
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_shims_name_the_tool_relative_to_themselves() {
|
||||
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
|
||||
let bin = tool.join("bin");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
|
||||
// Outside the tool's directory (a system SDK) stays absolute.
|
||||
let sdk = Path::new("/usr/local/share/dotnet");
|
||||
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn wrapper_runs_target() {
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
//! Show Diff in External Tool: starts the user's diff program on the two sides of a diff.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, settings::ExternalDiffSettings};
|
||||
use serde::Deserialize;
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// One side of the diff: a file on disk, or text written to a temporary file.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExternalDiffSide {
|
||||
/// A saved file, passed to the tool as it is.
|
||||
pub path: Option<PathBuf>,
|
||||
/// Content without a file of its own (a revision, a text), written to a temporary file.
|
||||
pub text: Option<String>,
|
||||
/// The temporary file's name; its extension lets the tool pick a syntax.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Splits a parameter line like a shell does for plain words: whitespace separates
|
||||
/// arguments, double or single quotes keep one together, a backslash escapes the next
|
||||
/// character inside double quotes and outside quotes.
|
||||
pub fn split_parameters(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut in_arg = false;
|
||||
let mut quote: Option<char> = None;
|
||||
let mut chars = line.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match (quote, c) {
|
||||
(Some('\''), '\'') | (Some('"'), '"') => quote = None,
|
||||
(Some('"') | None, '\\') => {
|
||||
if let Some(next) = chars.next() {
|
||||
cur.push(next);
|
||||
}
|
||||
in_arg = true;
|
||||
}
|
||||
(None, '"' | '\'') => {
|
||||
quote = Some(c);
|
||||
in_arg = true;
|
||||
}
|
||||
(None, c) if c.is_whitespace() => {
|
||||
if in_arg {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
in_arg = false;
|
||||
}
|
||||
}
|
||||
(_, c) => {
|
||||
cur.push(c);
|
||||
in_arg = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if in_arg {
|
||||
out.push(cur);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The tool's arguments: `%1` the left file, `%2` the right file, `%3` the title.
|
||||
pub fn expand_parameters(parameters: &str, left: &str, right: &str, title: &str) -> Vec<String> {
|
||||
split_parameters(parameters)
|
||||
.into_iter()
|
||||
.map(|arg| arg.replace("%1", left).replace("%2", right).replace("%3", title))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn side_file(side: &ExternalDiffSide, dir: &Path, sub: &str) -> IdeResult<PathBuf> {
|
||||
if let Some(path) = &side.path {
|
||||
return Ok(path.clone());
|
||||
}
|
||||
let name = Path::new(&side.name).file_name().map(|n| n.to_owned()).unwrap_or_else(|| "content".into());
|
||||
let folder = dir.join(sub);
|
||||
std::fs::create_dir_all(&folder)?;
|
||||
let file = folder.join(name);
|
||||
std::fs::write(&file, side.text.as_deref().unwrap_or_default())?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Starts the configured tool on `left` ↔ `right` and returns once it runs; the tool
|
||||
/// lives on after the diff closes, as it would started from a shell.
|
||||
pub fn launch_external_diff(
|
||||
settings: &ExternalDiffSettings,
|
||||
left: &ExternalDiffSide,
|
||||
right: &ExternalDiffSide,
|
||||
title: &str,
|
||||
) -> IdeResult<()> {
|
||||
let program = settings.path.trim();
|
||||
if program.is_empty() {
|
||||
return Err(IdeError::invalid("no external diff tool is set (Settings › Tools › External Diff Tools)"));
|
||||
}
|
||||
let needs_temp = left.path.is_none() || right.path.is_none();
|
||||
// Kept after the call: the tool reads the files after it starts.
|
||||
let dir = if needs_temp { Some(tempfile::Builder::new().prefix("openidea-diff-").tempdir()?.keep()) } else { None };
|
||||
let temp = dir.as_deref().unwrap_or_else(|| Path::new(""));
|
||||
let a = side_file(left, temp, "left")?;
|
||||
let b = side_file(right, temp, "right")?;
|
||||
let args = expand_parameters(&settings.parameters, &a.to_string_lossy(), &b.to_string_lossy(), title);
|
||||
let mut cmd = Command::new(program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start the external diff tool {program}: {e}")))?;
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn splits_quoted_parameters() {
|
||||
assert_eq!(split_parameters("%1 %2 %3"), ["%1", "%2", "%3"]);
|
||||
assert_eq!(split_parameters(r#"--title "%3" -L 'a b' x\ y"#), ["--title", "%3", "-L", "a b", "x y"]);
|
||||
assert_eq!(split_parameters(r#"--empty "" end"#), ["--empty", "", "end"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_placeholders_inside_arguments() {
|
||||
let args = expand_parameters("--left=%1 %2 --title %3", "/t/a b.rs", "/t/b.rs", "a.rs (HEAD ↔ Your version)");
|
||||
assert_eq!(args, ["--left=/t/a b.rs", "/t/b.rs", "--title", "a.rs (HEAD ↔ Your version)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_text_sides_to_named_temporary_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let side = ExternalDiffSide { path: None, text: Some("x\n".into()), name: "../Main.java".into() };
|
||||
let file = side_file(&side, dir.path(), "left").unwrap();
|
||||
assert_eq!(file, dir.path().join("left/Main.java"));
|
||||
assert_eq!(std::fs::read_to_string(file).unwrap(), "x\n");
|
||||
let saved = ExternalDiffSide { path: Some("/p/a.rs".into()), text: None, name: "a.rs".into() };
|
||||
assert_eq!(side_file(&saved, dir.path(), "right").unwrap(), PathBuf::from("/p/a.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_program() {
|
||||
let side = ExternalDiffSide { path: Some("/p/a".into()), text: None, name: "a".into() };
|
||||
assert!(launch_external_diff(&ExternalDiffSettings::default(), &side, &side, "t").is_err());
|
||||
}
|
||||
}
|
||||
@@ -627,7 +627,6 @@ pub mod changelists;
|
||||
mod cli;
|
||||
mod compare;
|
||||
mod diff;
|
||||
mod external_diff;
|
||||
mod history;
|
||||
mod ignore;
|
||||
mod index_writes;
|
||||
@@ -654,7 +653,6 @@ pub use cli::{
|
||||
set_git_command_observer, set_git_executable,
|
||||
};
|
||||
pub use diff::build_partial_patch;
|
||||
pub use external_diff::{ExternalDiffSide, launch_external_diff};
|
||||
pub use ignore::{IgnoreDestination, add_to_ignore};
|
||||
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
|
||||
pub use remotes::Remote;
|
||||
|
||||
@@ -24,8 +24,8 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
|
||||
&& let Some((upstream_name, upstream_id)) = upstream_of(&repo, name.as_ref())
|
||||
{
|
||||
info.upstream = Some(upstream_name);
|
||||
if let Some(local) = head_commit {
|
||||
let (a, b) = ahead_behind(&repo, local, upstream_id)?;
|
||||
if let (Some(local), Some(up)) = (head_commit, upstream_id) {
|
||||
let (a, b) = ahead_behind(&repo, local, up)?;
|
||||
info.ahead = a;
|
||||
info.behind = b;
|
||||
}
|
||||
@@ -51,12 +51,16 @@ pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
|
||||
Some(op.to_string())
|
||||
}
|
||||
|
||||
/// Short upstream name (`origin/main`) and its commit. A branch whose tracking ref is gone (the
|
||||
/// remote branch was deleted and pruned) tracks nothing, as in IDEA.
|
||||
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> {
|
||||
/// Short upstream name (`origin/main`) and, if the tracking ref exists, its commit.
|
||||
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, Option<gix::ObjectId>)> {
|
||||
let tracking = repo.branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)?.ok()?;
|
||||
let id = repo.try_find_reference(tracking.as_ref()).ok()??.peel_to_id().ok()?.detach();
|
||||
Some((to_string(tracking.as_ref().shorten()), id))
|
||||
let short = to_string(tracking.as_ref().shorten());
|
||||
let id = repo
|
||||
.try_find_reference(tracking.as_ref())
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|mut r| r.peel_to_id().ok().map(|id| id.detach()));
|
||||
Some((short, id))
|
||||
}
|
||||
|
||||
/// Commits in `local` not in `upstream`, and vice versa.
|
||||
@@ -110,9 +114,11 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
|
||||
};
|
||||
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
|
||||
branch.upstream = Some(up);
|
||||
let (a, b) = ahead_behind(&repo, id, up_id)?;
|
||||
branch.ahead = a;
|
||||
branch.behind = b;
|
||||
if let Some(up_id) = up_id {
|
||||
let (a, b) = ahead_behind(&repo, id, up_id)?;
|
||||
branch.ahead = a;
|
||||
branch.behind = b;
|
||||
}
|
||||
}
|
||||
out.push(branch);
|
||||
}
|
||||
|
||||
@@ -777,18 +777,12 @@ fn fetch_prunes_deleted_remote_branches() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
fx.git(&["push", "-q", "origin", "main:gone"]);
|
||||
fx.git(&["fetch", "-q"]);
|
||||
fx.git(&["checkout", "-q", "-b", "feature", "--track", "origin/gone"]);
|
||||
let repo = fx.repo();
|
||||
let upstream = || repo.branches().unwrap().into_iter().find(|b| b.name == "feature").and_then(|b| b.upstream);
|
||||
assert!(repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
|
||||
assert_eq!(upstream().as_deref(), Some("origin/gone"));
|
||||
git_in(&bare, &["branch", "-D", "gone"]);
|
||||
let (cancel, out) = quiet();
|
||||
repo.fetch(&cancel, &out).unwrap();
|
||||
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
|
||||
// The branch that tracked it no longer counts as tracking, as in IDEA.
|
||||
assert_eq!(upstream(), None);
|
||||
assert_eq!(repo.branch_info().unwrap().upstream, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -20,8 +20,6 @@ trash.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
zip.workspace = true
|
||||
flate2.workspace = true
|
||||
tar.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Read-only browsing of zip archives (jar, zip, war…) and gzip'd tars (Zig
|
||||
//! keeps its fetched packages as `.tar.gz` blobs), IDEA's `jar://` file system:
|
||||
//! `<archive>!` is the archive's root and `<archive>!/<entry>` an entry inside
|
||||
//! it. Listing and reading go through a small cache of parsed central
|
||||
//! Read-only browsing of zip archives (jar, zip, war…), IDEA's `jar://` file
|
||||
//! system: `<archive>!` is the archive's root and `<archive>!/<entry>` an entry
|
||||
//! inside it. Listing and reading go through a small cache of parsed central
|
||||
//! directories, refreshed when the archive changes on disk.
|
||||
|
||||
use crate::{EntryKind, FileEntry, mtime_ms, natural_cmp};
|
||||
@@ -9,7 +8,7 @@ use ide_core::{IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Seek};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::SystemTime;
|
||||
@@ -23,21 +22,13 @@ pub const ARCHIVE_SEPARATOR: char = '!';
|
||||
/// Parsed archives kept open.
|
||||
const CACHE_SIZE: usize = 8;
|
||||
|
||||
/// Whether `path` names a file browsed as an archive: a zip extension, or a
|
||||
/// gzip'd tar (`x.tar.gz`).
|
||||
/// Whether `path` names a file browsed as an archive (by extension).
|
||||
pub fn is_archive_file(path: &Path) -> bool {
|
||||
if is_tar_gz(path) {
|
||||
return true;
|
||||
}
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| ARCHIVE_EXTENSIONS.iter().any(|a| a.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
fn is_tar_gz(path: &Path) -> bool {
|
||||
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().ends_with(".tar.gz"))
|
||||
}
|
||||
|
||||
/// `(archive, entry)` for `<archive>!` (entry `""`) or `<archive>!/<entry>`;
|
||||
/// `None` for ordinary paths. The entry is `/`-separated without leading or trailing `/`.
|
||||
pub fn split_archive_path(path: &Path) -> Option<(PathBuf, String)> {
|
||||
@@ -93,14 +84,7 @@ struct Archive {
|
||||
mtime_ms: f64,
|
||||
/// Entry path (`""` = root) → node.
|
||||
nodes: HashMap<String, Node>,
|
||||
contents: Contents,
|
||||
}
|
||||
|
||||
/// Where entry contents come from: a random-access zip, or a gzip'd tar that
|
||||
/// is re-scanned per read (package tarballs are small).
|
||||
enum Contents {
|
||||
Zip(Mutex<zip::ZipArchive<File>>),
|
||||
Tar(Mutex<File>),
|
||||
zip: Mutex<zip::ZipArchive<File>>,
|
||||
}
|
||||
|
||||
/// Most recently used first.
|
||||
@@ -131,81 +115,41 @@ fn parent_of(name: &str) -> (&str, &str) {
|
||||
|
||||
impl Archive {
|
||||
fn open(path: &Path, stamp: (Option<SystemTime>, u64), mtime_ms: f64) -> IdeResult<Self> {
|
||||
let file = File::open(path)?;
|
||||
let (nodes, contents) = if is_tar_gz(path) {
|
||||
(tar_nodes(&file)?, Contents::Tar(Mutex::new(file)))
|
||||
} else {
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| zip_error(path, e))?;
|
||||
let nodes = zip_nodes(&mut zip)?;
|
||||
(nodes, Contents::Zip(Mutex::new(zip)))
|
||||
};
|
||||
Ok(Self { stamp, mtime_ms, nodes, contents })
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory tree of a zip, with each entry's central-directory index.
|
||||
fn zip_nodes(zip: &mut zip::ZipArchive<File>) -> IdeResult<HashMap<String, Node>> {
|
||||
let mut nodes: HashMap<String, Node> = HashMap::new();
|
||||
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
|
||||
for i in 0..zip.len() {
|
||||
let Ok(file) = zip.by_index_raw(i) else { continue };
|
||||
let Ok(name) = file.name() else { continue };
|
||||
let Some(name) = clean_name(&name) else { continue };
|
||||
let (dir, size) = (file.is_dir(), file.size());
|
||||
drop(file);
|
||||
add_entry(&mut nodes, name, i, dir, size);
|
||||
}
|
||||
Ok(link_children(nodes))
|
||||
}
|
||||
|
||||
/// The directory tree of a gzip'd tar, with each entry's ordinal position.
|
||||
/// Entries are re-read by streaming the (decompressed) tar again.
|
||||
fn tar_nodes(file: &File) -> IdeResult<HashMap<String, Node>> {
|
||||
let mut nodes: HashMap<String, Node> = HashMap::new();
|
||||
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
|
||||
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
|
||||
for (i, entry) in tar.entries()?.enumerate() {
|
||||
let Ok(entry) = entry else { break };
|
||||
let Ok(name) = entry.path().map(|p| p.to_string_lossy().into_owned()) else { continue };
|
||||
let Some(name) = clean_name(&name) else { continue };
|
||||
let (dir, size) = match entry.header().entry_type().is_dir() {
|
||||
true => (true, 0),
|
||||
false => (false, entry.header().size().unwrap_or_default()),
|
||||
};
|
||||
add_entry(&mut nodes, name, i, dir, size);
|
||||
}
|
||||
Ok(link_children(nodes))
|
||||
}
|
||||
|
||||
fn add_entry(nodes: &mut HashMap<String, Node>, name: String, index: usize, dir: bool, size: u64) {
|
||||
let mut parent = parent_of(&name).0;
|
||||
while !nodes.contains_key(parent) {
|
||||
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
|
||||
parent = parent_of(parent).0;
|
||||
}
|
||||
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
|
||||
node.dir |= dir;
|
||||
node.index = Some(index);
|
||||
node.size = if node.dir { 0 } else { size };
|
||||
}
|
||||
|
||||
/// Makes every named entry a child of its parent folder node.
|
||||
fn link_children(mut nodes: HashMap<String, Node>) -> HashMap<String, Node> {
|
||||
let links: Vec<(String, String)> = nodes
|
||||
.keys()
|
||||
.filter(|k| !k.is_empty())
|
||||
.map(|k| {
|
||||
let (parent, base) = parent_of(k);
|
||||
(parent.to_owned(), base.to_owned())
|
||||
})
|
||||
.collect();
|
||||
for (parent, base) in links {
|
||||
if let Some(p) = nodes.get_mut(&parent) {
|
||||
p.dir = true;
|
||||
p.children.push(base);
|
||||
let mut zip = zip::ZipArchive::new(File::open(path)?).map_err(|e| zip_error(path, e))?;
|
||||
let mut nodes: HashMap<String, Node> = HashMap::new();
|
||||
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
|
||||
for i in 0..zip.len() {
|
||||
let Ok(file) = zip.by_index_raw(i) else { continue };
|
||||
let Ok(name) = file.name() else { continue };
|
||||
let Some(name) = clean_name(&name) else { continue };
|
||||
let (dir, size) = (file.is_dir(), file.size());
|
||||
drop(file);
|
||||
let mut parent = parent_of(&name).0;
|
||||
while !nodes.contains_key(parent) {
|
||||
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
|
||||
parent = parent_of(parent).0;
|
||||
}
|
||||
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
|
||||
node.dir |= dir;
|
||||
node.index = Some(i);
|
||||
node.size = if node.dir { 0 } else { size };
|
||||
}
|
||||
let links: Vec<(String, String)> = nodes
|
||||
.keys()
|
||||
.filter(|k| !k.is_empty())
|
||||
.map(|k| {
|
||||
let (parent, base) = parent_of(k);
|
||||
(parent.to_owned(), base.to_owned())
|
||||
})
|
||||
.collect();
|
||||
for (parent, base) in links {
|
||||
if let Some(p) = nodes.get_mut(&parent) {
|
||||
p.dir = true;
|
||||
p.children.push(base);
|
||||
}
|
||||
}
|
||||
Ok(Self { stamp, mtime_ms, nodes, zip: Mutex::new(zip) })
|
||||
}
|
||||
nodes
|
||||
}
|
||||
|
||||
/// The parsed archive at `path`, from the cache unless it changed on disk.
|
||||
@@ -291,31 +235,10 @@ pub fn read_archive_entry(archive_path: &Path, entry: &str) -> IdeResult<(Vec<u8
|
||||
Some(_) => return Err(IdeError::invalid(format!("{entry} is a directory"))),
|
||||
None => return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display()))),
|
||||
};
|
||||
let bytes = match &a.contents {
|
||||
Contents::Zip(zip) => {
|
||||
let mut zip = zip.lock();
|
||||
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
|
||||
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
|
||||
file.read_to_end(&mut bytes)?;
|
||||
bytes
|
||||
}
|
||||
Contents::Tar(file) => {
|
||||
let mut file = file.lock();
|
||||
file.seek(std::io::SeekFrom::Start(0))?;
|
||||
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&mut *file));
|
||||
for (i, entry) in tar.entries()?.enumerate() {
|
||||
if i != index {
|
||||
continue;
|
||||
}
|
||||
let mut entry = entry.map_err(|e| IdeError::invalid(format!("{}: {e}", archive_path.display())))?;
|
||||
let mut bytes =
|
||||
Vec::with_capacity(entry.header().size().unwrap_or_default().min(crate::MAX_OPEN_SIZE) as usize);
|
||||
entry.read_to_end(&mut bytes)?;
|
||||
return Ok((bytes, a.mtime_ms));
|
||||
}
|
||||
return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display())));
|
||||
}
|
||||
};
|
||||
let mut zip = a.zip.lock();
|
||||
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
|
||||
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
|
||||
file.read_to_end(&mut bytes)?;
|
||||
Ok((bytes, a.mtime_ms))
|
||||
}
|
||||
|
||||
@@ -339,20 +262,6 @@ pub(crate) mod tests {
|
||||
w.finish().unwrap();
|
||||
}
|
||||
|
||||
/// Writes a gzip'd tar with `files`, the layout of the Zig package cache blobs.
|
||||
pub(crate) fn write_tar_gz(path: &Path, files: &[(&str, &str)]) {
|
||||
let enc = flate2::write::GzEncoder::new(File::create(path).unwrap(), flate2::Compression::default());
|
||||
let mut b = tar::Builder::new(enc);
|
||||
for (name, text) in files {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(text.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
b.append_data(&mut header, name, text.as_bytes()).unwrap();
|
||||
}
|
||||
b.into_inner().unwrap().finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_archive_paths() {
|
||||
assert_eq!(split_archive_path(Path::new("/a/b.txt")), None);
|
||||
@@ -408,34 +317,6 @@ pub(crate) mod tests {
|
||||
assert_eq!(names(""), vec![("only.txt".into(), EntryKind::File)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_and_reads_gzipped_tars() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let hash = "probe_pkg-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
|
||||
let blob = tmp.path().join(format!("{hash}.tar.gz"));
|
||||
let (zon, lib) = (format!("{hash}/build.zig.zon"), format!("{hash}/src/lib.zig"));
|
||||
write_tar_gz(&blob, &[(zon.as_str(), ".{ .name = .probe_pkg }"), (lib.as_str(), "pub fn hello() {}\n")]);
|
||||
let root = |entry: &str| PathBuf::from(format!("{}!/{entry}", blob.display()));
|
||||
let names = |dir: &str| -> Vec<String> {
|
||||
crate::read_dir(&root(&format!("{hash}/{dir}")), &[]).unwrap().into_iter().map(|e| e.name).collect()
|
||||
};
|
||||
assert_eq!(names(""), vec!["src", "build.zig.zon"]);
|
||||
assert_eq!(names("src"), vec!["lib.zig"]);
|
||||
let lib = crate::load_text(&root(&format!("{hash}/src/lib.zig"))).unwrap();
|
||||
assert_eq!((lib.text.as_str(), lib.binary), ("pub fn hello() {}\n", false));
|
||||
|
||||
// A rewritten tar is re-read, and a plain `.gz` stays an ordinary file.
|
||||
write_tar_gz(&blob, &[("only.zig", "1")]);
|
||||
let f = File::options().write(true).open(&blob).unwrap();
|
||||
f.set_modified(SystemTime::now() + std::time::Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(
|
||||
crate::read_dir(&root(""), &[]).unwrap().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
|
||||
["only.zig"]
|
||||
);
|
||||
assert!(!is_archive_file(Path::new("/a/data.gz")));
|
||||
assert!(is_archive_file(Path::new("/a/pack.TAR.GZ")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_dir_and_load_text_go_through_archives() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -197,5 +197,5 @@ You don't write anything special for remote development. In a remote window, `sr
|
||||
1. Put the logic in the owning crate; convert errors to `IdeError` at its edge; use IPC coordinates.
|
||||
2. Add the shared implementation to `ide-host::ops::<domain>` if it touches a project; register it with the remote dispatcher if remote windows need it.
|
||||
3. Add the `#[tauri::command] #[specta::specta]` adapter in `src-tauri/src/commands/<domain>.rs` and list it in `collect_commands!`.
|
||||
4. Decide its trust class: list it by exact name in `restricted_command_allowed` (also in Restricted Mode) or `projectless_command_allowed` (also with no project open), or leave it out to require a trusted project. There are no name prefixes; if it executes anything, leave it out.
|
||||
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`. It also rewrites `src-tauri/tests/commands.snap`; check that the new line shows the trust class and placement you meant.
|
||||
4. If it executes anything, leave it out of the restricted-mode allowlist (it is denied in untrusted projects by default).
|
||||
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`.
|
||||
@@ -28,8 +28,6 @@ Style components with CSS Modules: `Thing.module.css` next to `Thing.tsx`, impor
|
||||
|
||||
Build from the primitives in `src/ui/` before writing your own: `Button`, `BarButton`, `Input`, `Checkbox`, `Select`, `Dialog`, `Popup`, `Menu`, `Tooltip`, `List`, `Tree`, `Tabs`, `Splitter`, `Scrollbar`, `Spinner`, `Kbd`, and `T` for translated text. They already handle focus, keyboard navigation, theming and translation of their labels. Workbench-level pieces (tool windows, status items, overlays) come from [contributions](/en/contribute/architecture/frontend#contributions), not from custom layout.
|
||||
|
||||
Toolbar icon actions use `IconButton`: its full hit target uses `--bg-toolbar-hover` on hover, while pressed and selected states use their corresponding toolbar tokens. Keep semantic icon colours and the keyboard focus ring intact.
|
||||
|
||||
## Accessibility
|
||||
|
||||
- Use real `<button>` and `<input>` elements (or the primitives that render them), never clickable `<div>`s.
|
||||
|
||||
@@ -31,7 +31,7 @@ Opening a project folder can run code that the project controls: language server
|
||||
- When a project that hasn't been decided opens, the **Trust and Open Project?** dialog offers **Trust Project**, **Preview in Restricted Mode** and **Don't Open**. Decisions and trusted locations are managed on Settings' **Project Trust** page (group **Security**), and **Revoke Trust** is an action.
|
||||
- Trust is user-owned state (`crates/ide-host/src/trust.rs`). **Project settings never grant trust.**
|
||||
- Enforcement is in the backend, not the UI: every IPC command passes `Host::authorize_command` in the Tauri invoke handler (`src-tauri/src/lib.rs`) before it runs. In an untrusted project only commands on an explicit allowlist (`restricted_command_allowed`) run: reading and editing files and documents, syntax, search, navigation, local history, spelling, analysis, refactoring, settings and similar.
|
||||
- The allowlist is a default-deny list of exact names: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode. `src-tauri/tests/commands.snap` lists every command's trust class, so a change shows up in review.
|
||||
- The allowlist is a default-deny list: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode.
|
||||
- Below the command layer, language servers don't start (`LspManager` execution switch), and git runs with execution disabled and without the project's `git` executable setting until the project is trusted. Project plugins (`.openidea/plugins/`) load only for trusted projects.
|
||||
- In a remote window the desktop checks the remote project's trust before forwarding a command, and `openidea-server` authorizes every `invoke` again.
|
||||
|
||||
|
||||
@@ -7,12 +7,12 @@ Smoke tests check each language end to end with the real tools the IDE uses: lan
|
||||
|
||||
They are not part of `cargo nextest run` or `pnpm test`, because they need the tools installed. CI runs them in the **Language smoke** workflow with pinned versions.
|
||||
|
||||
| Suite | What it checks | Languages |
|
||||
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------ |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
|
||||
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php, zig |
|
||||
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, zig, php |
|
||||
| Suite | What it checks | Languages |
|
||||
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------- |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
|
||||
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php |
|
||||
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, php |
|
||||
|
||||
## Language smoke
|
||||
|
||||
|
||||
@@ -56,8 +56,6 @@ Agents are unavailable in a project you have not marked as trusted.
|
||||
|
||||
Available models depend on the installed agent and account. If a selected model is removed, choose another before starting. Refreshing does not change running tasks.
|
||||
|
||||
The version below the prompt is reported by a fresh agent initialization when this page is shown or the window regains focus. After updating a CLI, return to this page to refresh it. This does not restart running tasks; an already running agent process keeps its original version until it exits.
|
||||
|
||||
</Step>
|
||||
<Step title="Send">
|
||||
The task opens as an editor tab and starts.
|
||||
@@ -121,8 +119,6 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
|
||||
|
||||
## Add a custom agent
|
||||
|
||||
Any agent that speaks ACP over stdio can be added with an agent file, `agents/<id>.toml` in OpenIDEA's configuration directory:
|
||||
|
||||
@@ -47,7 +47,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
| **Move Caret to Code Block Start** / **End** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
|
||||
| **Toggle Insert/Overwrite** | `Insert` | `Insert` |
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines; they have no default shortcut.
|
||||
|
||||
Brackets and quotes are paired as you type, and typing a quote or bracket over a selection surrounds it. These and other typing aids (smart Home, Tab out of a closing bracket, smart indent on Enter, documentation comment stubs, what Backspace does with indentation, reformat on paste) are under **Settings › Editor › General › Smart Keys**.
|
||||
|
||||
|
||||
@@ -197,5 +197,5 @@ onIdeEvent("projectTrustChanged", (e) => {
|
||||
1. 逻辑放在所属的 crate 里;在其边界把错误转成 `IdeError`;使用 IPC 坐标。
|
||||
2. 如果涉及项目,把共享实现加到 `ide-host::ops::<domain>`;远程窗口需要的话,注册到远程 dispatcher。
|
||||
3. 在 `src-tauri/src/commands/<domain>.rs` 添加 `#[tauri::command] #[specta::specta]` 适配函数,并加入 `collect_commands!`。
|
||||
4. 决定它的信任级别:在 `restricted_command_allowed`(受限模式下也可运行)或 `projectless_command_allowed`(未打开项目时也可运行)中按完整名称列出它,或者不列出,即需要受信任的项目。没有名称前缀规则;会执行任何东西的命令不要列出。
|
||||
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。它也会重写 `src-tauri/tests/commands.snap`;检查新增的那一行是否是你想要的信任级别和运行位置。
|
||||
4. 如果它会执行任何东西,不要把它加进受限模式白名单(未受信任的项目里默认拒绝)。
|
||||
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。
|
||||
@@ -28,8 +28,6 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
|
||||
|
||||
先用 `src/ui/` 里的基础组件,再考虑自己写:`Button`、`BarButton`、`Input`、`Checkbox`、`Select`、`Dialog`、`Popup`、`Menu`、`Tooltip`、`List`、`Tree`、`Tabs`、`Splitter`、`Scrollbar`、`Spinner`、`Kbd`,以及用于翻译文本的 `T`。它们已经处理好焦点、键盘导航、主题和标签翻译。工作台级别的部件(工具窗口、状态栏项、浮层)来自 [contribution](/zh/contribute/architecture/frontend),不要自己写布局。
|
||||
|
||||
工具栏图标操作使用 `IconButton`:悬停时整个点击区域使用 `--bg-toolbar-hover`,按下和选中状态使用对应的工具栏 token。保留图标的语义颜色和键盘焦点环。
|
||||
|
||||
## 无障碍
|
||||
|
||||
- 使用真正的 `<button>` 和 `<input>` 元素(或渲染它们的基础组件),不要用可点击的 `<div>`。
|
||||
|
||||
@@ -28,7 +28,7 @@ description: "如何报告漏洞,以及贡献者需要维护的安全模型:
|
||||
- 打开一个尚未做过决定的项目时,会弹出 **信任并打开项目?** 对话框,提供 **信任项目**、**以受限模式预览** 和 **不打开**。已有决定和受信任的位置在设置的 **项目信任** 页面(**安全** 分组)里管理,**撤销信任** 是一个 action。
|
||||
- 信任是用户自己的状态(`crates/ide-host/src/trust.rs`)。**项目设置永远不能授予信任。**
|
||||
- 拦截在后端而不是 UI:每个 IPC 命令执行前,都要在 Tauri 的 invoke handler(`src-tauri/src/lib.rs`)里经过 `Host::authorize_command`。未受信任的项目里,只有显式白名单(`restricted_command_allowed`)中的命令能运行:读写文件和文档、语法、搜索、导航、本地历史、拼写、分析、重构、设置等。
|
||||
- 这份白名单按完整名称列出,默认拒绝:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。`src-tauri/tests/commands.snap` 列出每个命令的信任级别,改动会出现在审查的 diff 里。
|
||||
- 这份白名单是默认拒绝的:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。
|
||||
- 在命令层之下,项目受信任之前语言服务器不会启动(`LspManager` 的执行开关),git 以禁止执行的方式运行,也不使用项目里配置的 `git` 可执行文件。项目插件(`.openidea/plugins/`)只在受信任的项目中加载。
|
||||
- 远程窗口中,桌面端在转发命令前会先确认远程项目是否受信任,`openidea-server` 对每个 `invoke` 还会再校验一次。
|
||||
|
||||
|
||||
@@ -7,12 +7,12 @@ description: "在 fixtures 示例项目上,用真实语言服务器跑语言
|
||||
|
||||
由于需要安装这些工具,冒烟测试不包含在 `cargo nextest run` 或 `pnpm test` 中。CI 在 **Language smoke** 工作流里用固定版本运行它们。
|
||||
|
||||
| 套件 | 检查内容 | 语言 |
|
||||
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
|
||||
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php、zig |
|
||||
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、zig、php |
|
||||
| 套件 | 检查内容 | 语言 |
|
||||
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
|
||||
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、php |
|
||||
|
||||
## 语言冒烟测试
|
||||
|
||||
|
||||
@@ -56,8 +56,6 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
|
||||
可用模型取决于已安装的 agent 和账号。如果已选模型被移除,需要先选择其他模型才能开始任务。刷新不会更改正在运行的任务。
|
||||
|
||||
提示词下方的版本来自 agent 的初始化响应;显示此页面或窗口重新获得焦点时会重新查询。更新 CLI 后,返回此页面即可刷新版本。这不会重启正在运行的任务;已运行的 agent 进程在退出前仍使用原来的版本。
|
||||
|
||||
</Step>
|
||||
<Step title="发送">
|
||||
任务会在编辑器标签页中打开并开始运行。
|
||||
@@ -121,8 +119,6 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
|
||||
|
||||
## 添加自定义 agent
|
||||
|
||||
任何通过 stdio 使用 ACP 的 agent,都可以用一个 agent 文件添加:OpenIDEA 配置目录下的 `agents/<id>.toml`。
|
||||
|
||||
@@ -47,7 +47,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
| **将光标移至代码块开头** / **末尾** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
|
||||
| **切换插入/改写** | `Insert` | `Insert` |
|
||||
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行重新排序,默认没有快捷键。
|
||||
|
||||
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
|
||||
|
||||
|
||||
@@ -83,8 +83,8 @@ for (const placement of ["editor", "toolWindow"] as const) {
|
||||
},
|
||||
{ id: task.id, placement },
|
||||
);
|
||||
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
|
||||
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
|
||||
// The working indicator ends the conversation, after its rows.
|
||||
await expect(stream.getByRole("status").getByText("Working…", { exact: true })).toBeVisible();
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
|
||||
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
|
||||
const timer = await page.evaluate(async (id) => {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test.beforeEach(async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
// Load the IPC module in Vite's browser realm, not Playwright's Node process.
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const { commands } = await import(ipcPath);
|
||||
const provider = {
|
||||
id: "omp",
|
||||
name: "OMP",
|
||||
command: "omp acp",
|
||||
program: "omp",
|
||||
args: ["acp"],
|
||||
defaultProgram: null,
|
||||
defaultArgs: [],
|
||||
loginHint: null,
|
||||
commandOverridden: false,
|
||||
commandEditable: true,
|
||||
commandReadOnlyReason: null,
|
||||
installed: true,
|
||||
env: {},
|
||||
commands: [],
|
||||
source: { kind: "custom" },
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
};
|
||||
let installed = "18.20.0";
|
||||
let cached = installed;
|
||||
window.addEventListener("test:agent-upgraded", () => {
|
||||
installed = "18.20.2";
|
||||
});
|
||||
commands.agentProviders = async () => ({ status: "ok", data: [provider] });
|
||||
commands.agentProbe = async (id: string, refresh: boolean) => {
|
||||
if (refresh) cached = installed;
|
||||
return {
|
||||
status: "ok",
|
||||
data: { provider: id, name: "omp", version: cached, protocol: "ACP v1", error: null },
|
||||
};
|
||||
};
|
||||
commands.agentRefreshModels = async () => ({
|
||||
status: "ok",
|
||||
data: {
|
||||
provider: "omp",
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
|
||||
const message = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await message.focus();
|
||||
await page.keyboard.insertText("Keep this unsent draft");
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new Event("test:agent-upgraded"));
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
});
|
||||
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
await expect(message).toHaveText("Keep this unsent draft");
|
||||
});
|
||||
|
||||
test("refreshes an upgraded agent's version when New Task is reopened", async ({ workbench: page }) => {
|
||||
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -98,101 +98,6 @@ test("completion lists the server's items and inserts the chosen one", async ({
|
||||
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(async () => {
|
||||
// Long enough for the pane to reach its max-width: a short doc leaves it at
|
||||
// `width: max-content`, so the placement assertions would never exercise the room calculation.
|
||||
const longDocs =
|
||||
"Computes the order total including tax, discounts and shipping, rounded to the currency's scale. " +
|
||||
"The result is cached until the order changes, so callers should not hold on to it across edits; " +
|
||||
"ask for a fresh value after every update.";
|
||||
const item = (label: string, detail: string) => ({
|
||||
label,
|
||||
labelDetail: "()",
|
||||
detail,
|
||||
kind: "method",
|
||||
documentation: { kind: "markdown", value: `Docs for **${label}**. ${longDocs}` },
|
||||
sortText: null,
|
||||
filterText: null,
|
||||
preselect: false,
|
||||
deprecated: false,
|
||||
insertText: `${label}()`,
|
||||
isSnippet: false,
|
||||
replaceRange: null,
|
||||
replaceRangeTab: null,
|
||||
additionalEdits: [],
|
||||
commitCharacters: [],
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
});
|
||||
window.__ipc.handlers.lsp_completion = () => ({
|
||||
isIncomplete: false,
|
||||
items: [item("total", "BigDecimal"), item("toDto", "OrderDto")],
|
||||
});
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectPath);
|
||||
const settings = structuredClone(useProject.getState().settings ?? {});
|
||||
const editor = settings.editor ?? {};
|
||||
settings.editor = {
|
||||
...editor,
|
||||
completion: { ...editor.completion, showDocumentation: true, documentationDelay: 0 },
|
||||
};
|
||||
useProject.setState({ settings });
|
||||
});
|
||||
const popup = page.locator(".cm-tooltip-autocomplete");
|
||||
|
||||
const openLookup = async () => {
|
||||
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("order.");
|
||||
await page.keyboard.press("Control+Space");
|
||||
await expect(popup.getByText("total", { exact: true })).toBeVisible();
|
||||
await expect(page.locator(".cm-completionInfo")).toContainText("Docs for");
|
||||
};
|
||||
|
||||
const geometry = () =>
|
||||
page.evaluate(() => {
|
||||
const info = document.querySelector(".cm-completionInfo") as HTMLElement;
|
||||
const list = (document.querySelector(".cm-tooltip-autocomplete") as HTMLElement).getBoundingClientRect();
|
||||
const rect = info.getBoundingClientRect();
|
||||
const overlapX = Math.max(0, Math.min(rect.right, list.right) - Math.max(rect.left, list.left));
|
||||
const overlapY = Math.max(0, Math.min(rect.bottom, list.bottom) - Math.max(rect.top, list.top));
|
||||
const side = info.classList.contains("cm-completionInfo-left")
|
||||
? "left"
|
||||
: info.classList.contains("cm-completionInfo-right")
|
||||
? "right"
|
||||
: "none";
|
||||
return {
|
||||
overlap: overlapX * overlapY,
|
||||
visible: !!document.elementFromPoint(rect.left + 4, rect.top + 4)?.closest(".cm-completionInfo"),
|
||||
inside: rect.left >= 0 && rect.right <= document.documentElement.clientWidth,
|
||||
side,
|
||||
};
|
||||
});
|
||||
|
||||
await page.setViewportSize({ width: 760, height: 900 });
|
||||
await openLookup();
|
||||
await page.screenshot({ path: info.outputPath("completion-documentation.png"), animations: "disabled" });
|
||||
const narrow = await geometry();
|
||||
expect(narrow.overlap).toBe(0);
|
||||
expect(narrow.visible).toBe(true);
|
||||
expect(narrow.inside).toBe(true);
|
||||
expect(narrow.side).toBe("left");
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toBeHidden();
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
await openLookup();
|
||||
const wide = await geometry();
|
||||
expect(wide.overlap).toBe(0);
|
||||
expect(wide.visible).toBe(true);
|
||||
expect(wide.inside).toBe(true);
|
||||
expect(wide.side).toBe("right");
|
||||
});
|
||||
|
||||
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(() => {
|
||||
|
||||
@@ -174,36 +174,12 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const svg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
|
||||
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
|
||||
const routeModule = "/src/platform/tauriCore.ts";
|
||||
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
|
||||
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText(
|
||||
[
|
||||
"# Order Service",
|
||||
"",
|
||||
"Manage **Order** items and `Order` status.",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" A --> B",
|
||||
"```",
|
||||
"",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(preview).toContainText("Manage Order items");
|
||||
@@ -233,44 +209,6 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
|
||||
})),
|
||||
)
|
||||
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
|
||||
|
||||
const mermaidSvg = preview.locator(".mermaid-output svg");
|
||||
const excalidrawImg = preview.locator('img[alt="Diagram"]');
|
||||
await expect(mermaidSvg).toBeVisible();
|
||||
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
|
||||
|
||||
const widths = async () => ({
|
||||
mermaid: (await mermaidSvg.boundingBox())!.width,
|
||||
excalidraw: (await excalidrawImg.boundingBox())!.width,
|
||||
});
|
||||
const base = await widths();
|
||||
expect(base.mermaid).toBeGreaterThan(50);
|
||||
expect(base.excalidraw).toBeCloseTo(320, 0);
|
||||
|
||||
const runAction = (id: string, times = 1) =>
|
||||
page.evaluate(
|
||||
async ({ id, times }) => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
for (let i = 0; i < times; i++) await executeAction(id);
|
||||
},
|
||||
{ id, times },
|
||||
);
|
||||
|
||||
await runAction("editor.increaseFontSize", 4);
|
||||
const zoomedIn = await widths();
|
||||
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
|
||||
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
|
||||
|
||||
await runAction("editor.decreaseFontSize", 6);
|
||||
const zoomedOut = await widths();
|
||||
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
|
||||
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
|
||||
|
||||
await runAction("editor.resetFontSize");
|
||||
const reset = await widths();
|
||||
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
for (const theme of ["light", "dark"] as const) {
|
||||
test(`${theme}: toolbar icon buttons provide hover feedback without changing their layout or icons`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
|
||||
await gear.click();
|
||||
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
|
||||
await page
|
||||
.getByRole("menuitemcheckbox", { name: `Islands ${theme === "light" ? "Light" : "Dark"}`, exact: true })
|
||||
.click();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
|
||||
|
||||
const toolbar = page.locator("header").first();
|
||||
const disabledRun = toolbar.getByRole("button", { name: "Run", exact: true });
|
||||
await expect(disabledRun).toBeDisabled();
|
||||
await disabledRun.hover();
|
||||
await expect(disabledRun).toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
|
||||
await openFromTree(page, "App.tsx");
|
||||
await page.locator("[data-run-chooser]").click();
|
||||
await page.getByRole("option", { name: "Current File", exact: true }).click();
|
||||
const project = page.getByRole("region", { name: "Project", exact: true });
|
||||
const buttons = [
|
||||
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
|
||||
project.getByRole("button", { name, exact: true }),
|
||||
),
|
||||
...[
|
||||
"Run Current File",
|
||||
"Debug Current File",
|
||||
"More Actions",
|
||||
"Search Everywhere",
|
||||
"IDE and Project Settings",
|
||||
].map((name) => toolbar.getByRole("button", { name, exact: true })),
|
||||
];
|
||||
for (const button of buttons) {
|
||||
await page.mouse.move(700, 500);
|
||||
const bounds = await button.boundingBox();
|
||||
const iconColors = await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
|
||||
nodes.map((node) => {
|
||||
const style = getComputedStyle(node);
|
||||
return { fill: style.fill, stroke: style.stroke };
|
||||
}),
|
||||
);
|
||||
await expect(button).toBeEnabled();
|
||||
// Hover inside the hit target but outside its centred icon.
|
||||
await button.hover({ position: { x: bounds!.width / 2, y: 1 } });
|
||||
await expect(button).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
expect(await button.boundingBox()).toEqual(bounds);
|
||||
if (/^(Run|Debug) Current File$/.test((await button.getAttribute("aria-label")) ?? "")) {
|
||||
expect(
|
||||
await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
|
||||
nodes.map((node) => {
|
||||
const style = getComputedStyle(node);
|
||||
return { fill: style.fill, stroke: style.stroke };
|
||||
}),
|
||||
),
|
||||
).toEqual(iconColors);
|
||||
}
|
||||
await button.focus();
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(button).toBeFocused();
|
||||
await expect(button).toHaveCSS("outline-style", "solid");
|
||||
await expect(button).toHaveCSS("outline-width", "2px");
|
||||
}
|
||||
|
||||
const expand = project.getByRole("button", { name: "Expand All", exact: true });
|
||||
await expand.hover();
|
||||
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
|
||||
await page.mouse.down();
|
||||
await expect(expand).not.toHaveCSS("background-color", hover);
|
||||
await page.mouse.up();
|
||||
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
|
||||
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
|
||||
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
await project.getByRole("button", { name: "Options", exact: true }).click();
|
||||
await expect(page.getByRole("menu", { name: "Project options", exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await toolbar.getByRole("button", { name: "More Actions", exact: true }).click();
|
||||
await expect(page.getByRole("menuitem", { name: /^Edit Configurations…/ })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await toolbar.getByRole("button", { name: "Search Everywhere", exact: true }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Search Everywhere", exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await project.getByRole("button", { name: "Hide", exact: true }).click();
|
||||
await expect(project).toBeHidden();
|
||||
});
|
||||
}
|
||||
@@ -28,11 +28,4 @@ pub fn build(b: *std.Build) void {
|
||||
const tests = b.addTest(.{ .root_module = tally });
|
||||
const test_step = b.step("test", "Run the tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
|
||||
const failing_tests = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/failing.zig"),
|
||||
.target = target,
|
||||
}) });
|
||||
const test_failing_step = b.step("test-failing", "Run the tests that fail on purpose");
|
||||
test_failing_step.dependOn(&b.addRunArtifact(failing_tests).step);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
//! Fails on purpose: the `test-failing` step, for checking that a run's failure shows up
|
||||
//! in the test tree and Rerun Failed Tests re-runs it alone.
|
||||
test "intentionally fails" {
|
||||
return error.OpenideaFail;
|
||||
}
|
||||
@@ -3,8 +3,7 @@ const tally = @import("tally");
|
||||
|
||||
pub fn main() !void {
|
||||
const prices = [_]u32{ 4999, 2499, 5999 };
|
||||
const sum = tally.total(&prices);
|
||||
const sum = tally.total(&prices); // Set a breakpoint here
|
||||
var buf: [16]u8 = undefined;
|
||||
// Set a breakpoint here (QA: debugger) and inspect `sum`.
|
||||
std.debug.print("Total: {s}\n", .{try tally.format(&buf, sum)});
|
||||
}
|
||||
@@ -164,17 +164,6 @@ const CASES: Record<string, Case> = {
|
||||
variable: "line",
|
||||
evaluate: ["print line", / = /],
|
||||
},
|
||||
// Zig ships no debugger of its own: CodeLLDB debugs the binary `zig build` produces.
|
||||
// The breakpoint lands on the last use of `sum`: zig's debuginfo gives a const local a
|
||||
// location only within its live range, so `prices` (used earlier) is not in the frame.
|
||||
zig: {
|
||||
fixture: "zig-app",
|
||||
tools: ["codelldb"],
|
||||
adapter: "codelldb",
|
||||
file: "src/main.zig",
|
||||
variable: "sum",
|
||||
evaluate: ["sum", /13497/],
|
||||
},
|
||||
php: {
|
||||
fixture: "php-app",
|
||||
setup: (root) =>
|
||||
|
||||
@@ -135,19 +135,6 @@ const CASES: Record<string, Case> = {
|
||||
file: "ThresholdCustomsTest.php",
|
||||
},
|
||||
},
|
||||
// The failing run uses the fixture's dedicated `test-failing` step (`zig build` forwards
|
||||
// no args to the test binary, so a failing test can't be switched on through the config).
|
||||
zig: {
|
||||
fixture: "zig-app",
|
||||
run: { config: "zig:run", prints: "Total: $134.97" },
|
||||
tests: {
|
||||
config: "zig:test-failing",
|
||||
failing: (c) => c,
|
||||
passed: 0,
|
||||
failed: "intentionally fails",
|
||||
file: "src/failing.zig",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let server: Server | null = null;
|
||||
|
||||
@@ -358,7 +358,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
vcs::vcs_conflict_versions,
|
||||
vcs::vcs_diff_text,
|
||||
vcs::vcs_diff_hunks,
|
||||
vcs::diff_external_tool,
|
||||
vcs::vcs_stage_hunks,
|
||||
vcs::vcs_clone,
|
||||
vcs::vcs_init,
|
||||
|
||||
@@ -518,21 +518,6 @@ pub async fn vcs_diff_hunks(app: AppHandle, old_text: String, new_text: String)
|
||||
.expect("line diff panicked")
|
||||
}
|
||||
|
||||
/// Show Diff in External Tool: starts the tool set in the global settings (never a
|
||||
/// project's, which a cloned repository could carry) on the two sides, on this machine
|
||||
/// (a remote window passes the sides as text).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn diff_external_tool(
|
||||
state: State<'_, AppState>,
|
||||
left: ExternalDiffSide,
|
||||
right: ExternalDiffSide,
|
||||
title: String,
|
||||
) -> IdeResult<()> {
|
||||
let settings = state.global_settings.effective().external_diff;
|
||||
state.host.blocking(move || launch_external_diff(&settings, &left, &right, &title)).await
|
||||
}
|
||||
|
||||
/// Stages only the selected hunks of a file's working-tree changes.
|
||||
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,700 +0,0 @@
|
||||
# Generated by `pnpm gen:bindings`; do not edit. One line per command:
|
||||
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.
|
||||
agent_accept_changes trusted project_host bindings async
|
||||
agent_archive always project_host bindings sync
|
||||
agent_base_text trusted project_host bindings async
|
||||
agent_cancel always project_host bindings sync
|
||||
agent_changes trusted project_host bindings async
|
||||
agent_commands always project_host bindings async
|
||||
agent_create trusted project_host bindings async
|
||||
agent_create_ephemeral trusted desktop bindings async
|
||||
agent_custom_import trusted desktop bindings sync
|
||||
agent_custom_remove trusted desktop bindings sync
|
||||
agent_custom_save trusted desktop bindings sync
|
||||
agent_delete trusted project_host bindings async
|
||||
agent_entries always project_host bindings sync
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_list always project_host bindings sync
|
||||
agent_mcp_remove always project_host bindings sync
|
||||
agent_mcp_save always project_host bindings sync
|
||||
agent_mcp_set_enabled always project_host bindings sync
|
||||
agent_probe trusted project_host bindings async
|
||||
agent_prompt trusted project_host bindings async
|
||||
agent_providers trusted project_host bindings sync
|
||||
agent_refresh_models trusted project_host bindings sync
|
||||
agent_registry_install always project_host bindings async
|
||||
agent_registry_list always project_host bindings async
|
||||
agent_registry_remove always project_host bindings async
|
||||
agent_rename trusted project_host bindings sync
|
||||
agent_respond trusted project_host bindings sync
|
||||
agent_rollback trusted project_host bindings async
|
||||
agent_rollback_changes trusted project_host bindings async
|
||||
agent_send_queued_now trusted project_host bindings sync
|
||||
agent_set_command trusted project_host bindings sync
|
||||
agent_set_config trusted project_host bindings async
|
||||
agent_set_env trusted project_host bindings sync
|
||||
agent_stop_background always project_host bindings async
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
agent_unqueue always project_host bindings sync
|
||||
analysis_locate_duplicates always project_host bindings async
|
||||
android_devices trusted desktop bindings async
|
||||
android_logcat trusted desktop bindings async
|
||||
app_build_info always desktop bindings sync
|
||||
app_cancel_quit always desktop bindings sync
|
||||
app_check_update always desktop bindings async
|
||||
app_cli_install always desktop bindings async
|
||||
app_cli_uninstall always desktop bindings async
|
||||
app_info always desktop bindings sync
|
||||
app_install_update always desktop bindings async
|
||||
app_log_location always desktop bindings sync
|
||||
app_metrics always desktop bindings async
|
||||
app_quit always desktop bindings sync
|
||||
app_release_notes trusted desktop bindings async
|
||||
app_restart always desktop bindings sync
|
||||
app_update_announcement always desktop bindings sync
|
||||
app_update_status always desktop bindings sync
|
||||
app_update_window_ready always desktop bindings sync
|
||||
apply_workspace_edit always project_host bindings async
|
||||
build_compile_file trusted project_host bindings async
|
||||
build_model trusted project_host bindings async
|
||||
build_run trusted project_host bindings async
|
||||
build_sync trusted project_host bindings async
|
||||
caches_local_data_info trusted desktop bindings sync
|
||||
caches_schedule_invalidation always desktop bindings sync
|
||||
caches_set_local_data_dir trusted desktop bindings sync
|
||||
cancel_request always project_host bindings sync
|
||||
cancel_task always project_host bindings sync
|
||||
clear_caches always desktop bindings async
|
||||
clipboard_file_list always desktop bindings async
|
||||
clipboard_has_files always desktop bindings sync
|
||||
clipboard_has_image always desktop bindings sync
|
||||
clipboard_image always desktop bindings async
|
||||
clipboard_set_file_list always desktop bindings async
|
||||
clipboard_text trusted desktop bindings async
|
||||
clipboard_write_text always desktop bindings async
|
||||
close_project always project_host bindings spawn
|
||||
coverage_collect trusted project_host bindings async
|
||||
coverage_import always project_host bindings async
|
||||
coverage_prepare trusted project_host bindings async
|
||||
db_apply_edits trusted project_host bindings async
|
||||
db_completion trusted project_host bindings async
|
||||
db_connect trusted project_host bindings async
|
||||
db_connected trusted project_host bindings sync
|
||||
db_console_path always project_host bindings sync
|
||||
db_consoles always project_host bindings sync
|
||||
db_database_catalog trusted project_host bindings async
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
db_export_file always desktop bindings async
|
||||
db_finish_transaction trusted project_host bindings async
|
||||
db_history trusted project_host bindings async
|
||||
db_object_ddl trusted project_host bindings async
|
||||
db_remove_history trusted project_host bindings async
|
||||
db_retain_catalog trusted project_host bindings async
|
||||
db_save_sources trusted project_host bindings async
|
||||
db_saved_catalog trusted project_host bindings async
|
||||
db_schema_objects trusted project_host bindings async
|
||||
db_schemas trusted project_host bindings async
|
||||
db_session_context trusted project_host bindings async
|
||||
db_set_manual_commit trusted project_host bindings async
|
||||
db_set_password trusted project_host bindings async
|
||||
db_set_ssh_secret trusted project_host bindings async
|
||||
db_sources trusted project_host bindings sync
|
||||
db_statements trusted project_host bindings sync
|
||||
db_table_details trusted project_host bindings async
|
||||
db_table_page trusted project_host bindings async
|
||||
db_tables trusted project_host bindings async
|
||||
db_test trusted project_host bindings async
|
||||
db_test_tunnel trusted project_host bindings async
|
||||
db_trust_ssh_host trusted project_host bindings async
|
||||
debug_attachable_processes always project_host bindings async
|
||||
debug_breakpoint_states trusted project_host bindings sync
|
||||
debug_capabilities trusted project_host bindings sync
|
||||
debug_completions trusted project_host bindings async
|
||||
debug_data_breakpoint_info trusted project_host bindings async
|
||||
debug_evaluate trusted project_host bindings async
|
||||
debug_evaluate_in trusted project_host bindings async
|
||||
debug_exception_filters trusted project_host bindings sync
|
||||
debug_force_step_over trusted project_host bindings async
|
||||
debug_free_port trusted project_host bindings async
|
||||
debug_heap_capture trusted project_host bindings async
|
||||
debug_heap_classes trusted project_host bindings async
|
||||
debug_heap_close trusted project_host bindings async
|
||||
debug_heap_compare trusted project_host bindings async
|
||||
debug_heap_dominators trusted project_host bindings async
|
||||
debug_heap_open trusted project_host bindings async
|
||||
debug_heap_path trusted project_host bindings async
|
||||
debug_heap_save trusted project_host bindings async
|
||||
debug_hot_reload trusted desktop bindings async
|
||||
debug_hot_restart trusted desktop bindings async
|
||||
debug_js_custom_breakpoints trusted project_host bindings async
|
||||
debug_js_response_body trusted project_host bindings async
|
||||
debug_js_response_overrides trusted project_host bindings async
|
||||
debug_js_start_profile trusted project_host bindings async
|
||||
debug_js_stop_profile trusted project_host bindings async
|
||||
debug_jvm_memory_classes trusted project_host bindings async
|
||||
debug_jvm_memory_fields trusted project_host bindings async
|
||||
debug_jvm_memory_instances trusted project_host bindings async
|
||||
debug_jvm_memory_referrers trusted project_host bindings async
|
||||
debug_listen_for_jvm trusted project_host bindings async
|
||||
debug_pause trusted project_host bindings async
|
||||
debug_redefine_classes trusted project_host bindings async
|
||||
debug_restart_frame trusted project_host bindings async
|
||||
debug_resume trusted project_host bindings async
|
||||
debug_run_to trusted project_host bindings async
|
||||
debug_scopes trusted project_host bindings async
|
||||
debug_send_input trusted project_host bindings async
|
||||
debug_sessions always project_host bindings sync
|
||||
debug_set_breakpoints trusted project_host bindings async
|
||||
debug_set_data_breakpoints trusted project_host bindings async
|
||||
debug_set_exception_breakpoints trusted project_host bindings async
|
||||
debug_set_function_breakpoints trusted project_host bindings async
|
||||
debug_set_variable trusted project_host bindings async
|
||||
debug_stack_trace trusted project_host bindings async
|
||||
debug_start trusted project_host bindings async
|
||||
debug_step trusted project_host bindings async
|
||||
debug_step_in_target trusted project_host bindings async
|
||||
debug_step_in_targets trusted project_host bindings async
|
||||
debug_stop always project_host bindings async
|
||||
debug_threads trusted project_host bindings async
|
||||
debug_variables trusted project_host bindings async
|
||||
dependency_versions trusted project_host bindings async
|
||||
deploy_compare trusted project_host bindings async
|
||||
deploy_coverage always project_host bindings async
|
||||
deploy_delete_remote trusted project_host bindings async
|
||||
deploy_download trusted project_host bindings async
|
||||
deploy_info trusted project_host bindings async
|
||||
deploy_server_root trusted project_host bindings async
|
||||
deploy_sync trusted project_host bindings async
|
||||
deploy_test_connection always project_host bindings async
|
||||
deploy_upload trusted project_host bindings async
|
||||
diff_external_tool always desktop bindings async
|
||||
doc_close always project_host bindings async
|
||||
doc_edit always project_host bindings async
|
||||
doc_folding always project_host bindings async
|
||||
doc_highlights always project_host bindings async
|
||||
doc_open always project_host bindings async
|
||||
doc_open_untitled always project_host bindings async
|
||||
doc_open_virtual always project_host bindings async
|
||||
doc_outline always project_host bindings async
|
||||
doc_python_facts always project_host bindings async
|
||||
doc_save always project_host bindings async
|
||||
doc_save_all always project_host bindings async
|
||||
doc_save_as always project_host bindings async
|
||||
doc_selection_ranges always project_host bindings async
|
||||
doc_set_bom always project_host bindings async
|
||||
doc_set_encoding always project_host bindings async
|
||||
doc_set_line_ending always project_host bindings async
|
||||
doc_snapshot always project_host bindings async
|
||||
doc_sync_from_disk always project_host bindings async
|
||||
doc_ui_mode always project_host bindings async
|
||||
docker_compose_op trusted desktop bindings async
|
||||
docker_container_op trusted desktop bindings async
|
||||
docker_container_stats trusted desktop bindings async
|
||||
docker_container_top trusted desktop bindings async
|
||||
docker_events trusted desktop bindings async
|
||||
docker_image_history trusted desktop bindings async
|
||||
docker_inspect trusted desktop bindings async
|
||||
docker_logs trusted desktop bindings async
|
||||
docker_prune trusted desktop bindings async
|
||||
docker_pull trusted desktop bindings async
|
||||
docker_registry_login trusted desktop bindings async
|
||||
docker_remove trusted desktop bindings async
|
||||
docker_run_env always project_host bindings async
|
||||
docker_save_settings always desktop bindings async
|
||||
docker_set_registry_password always desktop bindings async
|
||||
docker_settings always desktop bindings async
|
||||
docker_snapshot trusted desktop bindings async
|
||||
end_process trusted desktop bindings async
|
||||
env_reload always project_host bindings async
|
||||
file_dialog_needs_gtk trusted desktop bindings async
|
||||
find_dirs always project_host bindings sync
|
||||
find_files always project_host bindings sync
|
||||
find_files_named always project_host bindings async
|
||||
find_symbols always project_host bindings sync
|
||||
fs_compare_directories always project_host bindings async
|
||||
fs_copy always project_host bindings async
|
||||
fs_copy_merge always project_host bindings async
|
||||
fs_create_dir always project_host bindings sync
|
||||
fs_create_file always project_host bindings sync
|
||||
fs_create_file_bytes always project_host bindings async
|
||||
fs_delete always project_host bindings async
|
||||
fs_entry_kind always project_host bindings async
|
||||
fs_open_with_system always desktop bindings async
|
||||
fs_probe always project_host bindings async
|
||||
fs_read_dir always project_host bindings async
|
||||
fs_read_image always project_host bindings async
|
||||
fs_read_range always project_host bindings async
|
||||
fs_read_text always project_host bindings async
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_set_writable always project_host bindings sync
|
||||
gh_account_repos trusted desktop bindings async
|
||||
gh_api trusted desktop bindings async
|
||||
gh_availability trusted desktop bindings async
|
||||
gh_pr_checkout trusted desktop bindings async
|
||||
gh_pr_comment trusted desktop bindings async
|
||||
gh_pr_create trusted desktop bindings async
|
||||
gh_pr_list trusted desktop bindings async
|
||||
gh_pr_prepare_diff trusted desktop bindings async
|
||||
gh_pr_review trusted desktop bindings async
|
||||
gh_pr_review_comments trusted desktop bindings async
|
||||
gh_pr_view trusted desktop bindings async
|
||||
git_credential_forget always desktop bindings sync
|
||||
git_credentials always desktop bindings sync
|
||||
gradle_dependencies trusted project_host bindings async
|
||||
gradle_link_projects trusted project_host bindings async
|
||||
gradle_published_catalog trusted project_host bindings async
|
||||
gradle_unlink_projects trusted project_host bindings async
|
||||
gtk_pick_paths trusted desktop bindings async
|
||||
history_content always project_host bindings async
|
||||
history_list always project_host bindings async
|
||||
history_list_dir always project_host bindings async
|
||||
history_put_label always project_host bindings sync
|
||||
history_restore always project_host bindings async
|
||||
http_curl trusted desktop bindings async
|
||||
http_environment_file trusted desktop bindings async
|
||||
http_environments trusted desktop bindings async
|
||||
http_execute trusted desktop bindings async
|
||||
http_from_curl trusted desktop bindings sync
|
||||
http_history trusted desktop bindings sync
|
||||
http_history_clear trusted desktop bindings sync
|
||||
http_history_get trusted desktop bindings sync
|
||||
http_requests trusted desktop bindings sync
|
||||
http_variable_definitions trusted desktop bindings async
|
||||
index_file_extensions always project_host bindings sync
|
||||
index_status always project_host bindings sync
|
||||
inspect_code trusted project_host bindings async
|
||||
java_build_workspace trusted project_host bindings async
|
||||
java_debug_server trusted project_host bindings async
|
||||
java_resolve_launch trusted project_host bindings async
|
||||
jdk_download always project_host bindings async
|
||||
jdk_download_location always project_host bindings sync
|
||||
jdk_download_releases always project_host bindings async
|
||||
jdk_download_vendors always project_host bindings sync
|
||||
jdtls_required_java always project_host bindings async
|
||||
jvm_file_presentations always project_host bindings async
|
||||
languages always desktop bindings sync
|
||||
light_edit_open always desktop bindings async
|
||||
light_edit_open_untitled always desktop bindings async
|
||||
log_frontend always desktop bindings sync
|
||||
lsp_apply_code_action trusted project_host bindings async
|
||||
lsp_call_hierarchy trusted project_host bindings async
|
||||
lsp_can_download_sources trusted project_host bindings async
|
||||
lsp_code_action_query trusted project_host bindings async
|
||||
lsp_code_actions trusted project_host bindings async
|
||||
lsp_code_lens trusted project_host bindings async
|
||||
lsp_completion trusted project_host bindings async
|
||||
lsp_document_highlights trusted project_host bindings async
|
||||
lsp_document_links trusted project_host bindings async
|
||||
lsp_execute_code_action trusted project_host bindings async
|
||||
lsp_execute_command trusted project_host bindings async
|
||||
lsp_format trusted project_host bindings async
|
||||
lsp_goto trusted project_host bindings async
|
||||
lsp_goto_implementation trusted project_host bindings async
|
||||
lsp_hierarchy_members trusted project_host bindings async
|
||||
lsp_hierarchy_refactor trusted project_host bindings async
|
||||
lsp_hover trusted project_host bindings async
|
||||
lsp_implementations trusted project_host bindings async
|
||||
lsp_inlay_hints trusted project_host bindings async
|
||||
lsp_inline_completion trusted project_host bindings async
|
||||
lsp_library_sources trusted project_host bindings async
|
||||
lsp_prepare_rename trusted project_host bindings async
|
||||
lsp_prepare_type_hierarchy trusted project_host bindings async
|
||||
lsp_references trusted project_host bindings async
|
||||
lsp_rename trusted project_host bindings async
|
||||
lsp_resend_diagnostics always project_host bindings sync
|
||||
lsp_resolve_class_file trusted project_host bindings async
|
||||
lsp_resolve_code_action trusted project_host bindings async
|
||||
lsp_resolve_command trusted project_host bindings async
|
||||
lsp_resolve_completion trusted project_host bindings async
|
||||
lsp_restart trusted project_host bindings async
|
||||
lsp_restart_named trusted desktop bindings async
|
||||
lsp_semantic_tokens trusted project_host bindings async
|
||||
lsp_servers always project_host bindings sync
|
||||
lsp_signature_help trusted project_host bindings async
|
||||
lsp_type_hierarchy trusted project_host bindings async
|
||||
lsp_virtual_document trusted project_host bindings async
|
||||
lsp_workspace_symbols trusted project_host bindings async
|
||||
mark_recent always project_host bindings sync
|
||||
maven_dependency_completion trusted project_host bindings async
|
||||
maven_dependency_declaration trusted project_host bindings async
|
||||
maven_exclude_dependency trusted project_host bindings async
|
||||
maven_goto_declaration trusted project_host bindings async
|
||||
mcp_agent_run_closed trusted desktop bindings sync
|
||||
mcp_regenerate_token trusted desktop bindings sync
|
||||
mcp_report_problems trusted project_host bindings sync
|
||||
mcp_respond trusted desktop bindings sync
|
||||
mcp_server_status trusted desktop bindings sync
|
||||
mcp_set_focused_editor trusted project_host bindings sync
|
||||
mcp_set_open_editors trusted project_host bindings sync
|
||||
mcp_ui_ready trusted desktop bindings sync
|
||||
menu_configure always desktop bindings sync
|
||||
menu_model always desktop bindings sync
|
||||
menu_refresh always desktop bindings sync
|
||||
menu_set_disabled always desktop bindings sync
|
||||
nav_index_definitions always project_host bindings async
|
||||
nav_inheritance always project_host bindings async
|
||||
nav_resolve_module always project_host bindings async
|
||||
notebook_cell_docs trusted project_host bindings sync
|
||||
notebook_close always project_host bindings async
|
||||
notebook_edit always project_host bindings async
|
||||
notebook_execute trusted project_host bindings async
|
||||
notebook_get always project_host bindings sync
|
||||
notebook_interrupt always project_host bindings async
|
||||
notebook_open always project_host bindings async
|
||||
notebook_redo always project_host bindings async
|
||||
notebook_reload always project_host bindings async
|
||||
notebook_restart trusted project_host bindings async
|
||||
notebook_save always project_host bindings async
|
||||
notebook_undo always project_host bindings async
|
||||
open_project always project_host bindings async
|
||||
path_completions always project_host bindings async
|
||||
plugin_activation_event trusted desktop bindings async
|
||||
plugin_answer_command trusted project_host bindings sync
|
||||
plugin_answer_commit trusted project_host bindings sync
|
||||
plugin_answer_prompt trusted project_host bindings sync
|
||||
plugin_answer_run_target trusted project_host bindings async
|
||||
plugin_assets always desktop bindings async
|
||||
plugin_cancel_task trusted project_host bindings sync
|
||||
plugin_catalog always desktop bindings async
|
||||
plugin_choose_program outside_restricted project_host bindings async
|
||||
plugin_color_presentations trusted project_host bindings async
|
||||
plugin_commit_checks trusted project_host bindings async
|
||||
plugin_content_tab_action trusted project_host bindings sync
|
||||
plugin_context_keys trusted project_host bindings sync
|
||||
plugin_debug_attach_target trusted project_host bindings async
|
||||
plugin_decoration_sets trusted project_host bindings sync
|
||||
plugin_endpoints trusted project_host bindings async
|
||||
plugin_event_kinds trusted project_host bindings async
|
||||
plugin_finish_operation trusted project_host bindings sync
|
||||
plugin_formatters trusted project_host bindings sync
|
||||
plugin_grant outside_restricted desktop bindings async
|
||||
plugin_install_dir outside_restricted desktop bindings async
|
||||
plugin_installed_intellij_themes always desktop bindings async
|
||||
plugin_language_visuals trusted project_host bindings async
|
||||
plugin_line_markers trusted project_host bindings async
|
||||
plugin_link trusted desktop bindings async
|
||||
plugin_list always desktop bindings async
|
||||
plugin_log_tab_spawn trusted desktop bindings async
|
||||
plugin_market always desktop bindings async
|
||||
plugin_market_download always desktop bindings async
|
||||
plugin_market_url always desktop bindings sync
|
||||
plugin_navigation_files trusted project_host bindings async
|
||||
plugin_navigation_goto trusted project_host bindings async
|
||||
plugin_navigation_index trusted project_host bindings async
|
||||
plugin_navigation_invalidate trusted project_host bindings sync
|
||||
plugin_navigation_markers trusted project_host bindings async
|
||||
plugin_parse_test_results trusted project_host bindings async
|
||||
plugin_post_events trusted project_host bindings sync
|
||||
plugin_prepare_debug_run trusted project_host bindings async
|
||||
plugin_preview_install always desktop bindings async
|
||||
plugin_program outside_restricted project_host bindings async
|
||||
plugin_read_intellij_theme always desktop bindings async
|
||||
plugin_reload outside_restricted desktop bindings async
|
||||
plugin_revoke_net_host outside_restricted desktop bindings async
|
||||
plugin_roll_back outside_restricted desktop bindings async
|
||||
plugin_run_command trusted project_host bindings async
|
||||
plugin_run_targets trusted project_host bindings async
|
||||
plugin_secrets trusted desktop bindings sync
|
||||
plugin_select_tests trusted project_host bindings async
|
||||
plugin_service_detail trusted project_host bindings async
|
||||
plugin_service_log trusted project_host bindings async
|
||||
plugin_set_active_file always project_host bindings sync
|
||||
plugin_set_capability outside_restricted desktop bindings async
|
||||
plugin_set_enabled outside_restricted desktop bindings async
|
||||
plugin_set_market_url always desktop bindings sync
|
||||
plugin_set_secret trusted desktop bindings sync
|
||||
plugin_set_theme always desktop bindings sync
|
||||
plugin_set_theme_frame always desktop bindings sync
|
||||
plugin_set_ui_locale always project_host bindings async
|
||||
plugin_stage_package always desktop bindings async
|
||||
plugin_status_items trusted project_host bindings sync
|
||||
plugin_subscribe always desktop bindings sync
|
||||
plugin_sync_languages trusted project_host - -
|
||||
plugin_sync_packages trusted project_host - -
|
||||
plugin_terminal_session_close trusted project_host bindings sync
|
||||
plugin_terminal_session_spawn trusted project_host bindings async
|
||||
plugin_uninstall outside_restricted desktop bindings async
|
||||
plugin_unlink trusted desktop bindings async
|
||||
plugin_unpack_package always desktop bindings async
|
||||
plugin_view_event trusted project_host bindings async
|
||||
plugin_view_render trusted project_host bindings async
|
||||
plugin_web_page trusted desktop bindings sync
|
||||
plugin_web_pty_spawn trusted desktop bindings async
|
||||
plugin_web_read_file trusted desktop bindings async
|
||||
plugin_web_save_file trusted desktop bindings async
|
||||
prepare_workspace_edit always project_host bindings async
|
||||
profiler_collect trusted desktop bindings async
|
||||
profiler_gc_before_stop trusted desktop bindings async
|
||||
profiler_prepare trusted desktop bindings async
|
||||
project_current always project_host bindings sync
|
||||
project_rename always desktop bindings sync
|
||||
project_roots always project_host bindings sync
|
||||
project_trust_add_location always desktop bindings async
|
||||
project_trust_list always project_host bindings sync
|
||||
project_trust_remove_location always project_host bindings async
|
||||
project_trust_set always project_host bindings async
|
||||
project_trust_status always project_host bindings sync
|
||||
proxy_check_connection always desktop bindings async
|
||||
recent_files always project_host bindings sync
|
||||
recent_project_groups always desktop bindings sync
|
||||
recent_projects always desktop bindings async
|
||||
redo_workspace_edit always project_host bindings async
|
||||
refactor_can_undo_file_move always project_host bindings sync
|
||||
refactor_file_move_edits always project_host bindings async
|
||||
refactor_file_move_text_edits always project_host bindings async
|
||||
refactor_move_files always project_host bindings async
|
||||
refactor_undo_file_move always project_host bindings async
|
||||
remote_bootstrap_list always desktop bindings async
|
||||
remote_connect always desktop bindings async
|
||||
remote_current always desktop bindings sync
|
||||
remote_delete trusted project_host bindings async
|
||||
remote_disconnect always desktop bindings sync
|
||||
remote_download_into trusted project_host bindings async
|
||||
remote_forward_port trusted desktop bindings async
|
||||
remote_forwarded_ports trusted desktop bindings sync
|
||||
remote_import_local trusted desktop bindings async
|
||||
remote_invoke always desktop bindings async
|
||||
remote_list always project_host bindings async
|
||||
remote_mkdir trusted project_host bindings async
|
||||
remote_of always project_host bindings sync
|
||||
remote_open always project_host bindings async
|
||||
remote_rename trusted project_host bindings async
|
||||
remote_stop_forwarding trusted desktop bindings async
|
||||
remote_trust_set always desktop bindings sync
|
||||
remote_trust_status always desktop bindings sync
|
||||
remove_recent always project_host bindings sync
|
||||
remove_recent_project always desktop bindings sync
|
||||
replace_in_files trusted project_host bindings async
|
||||
replace_preview trusted project_host bindings async
|
||||
run_application_build trusted project_host bindings async
|
||||
run_application_publish trusted project_host bindings async
|
||||
run_apply_settings trusted project_host bindings async
|
||||
run_close_stdin trusted project_host bindings sync
|
||||
run_configs trusted project_host bindings async
|
||||
run_dotnet_resolve trusted project_host bindings async
|
||||
run_env_files trusted project_host bindings async
|
||||
run_gradle_init_script trusted project_host bindings async
|
||||
run_gradle_jvm_args_script always project_host bindings async
|
||||
run_import_configs trusted project_host bindings async
|
||||
run_import_sources trusted project_host bindings async
|
||||
run_list always project_host bindings sync
|
||||
run_resize trusted project_host bindings sync
|
||||
run_save_configs trusted project_host bindings async
|
||||
run_save_templates trusted project_host bindings async
|
||||
run_start trusted project_host bindings async
|
||||
run_stdin trusted project_host bindings sync
|
||||
run_stop always project_host bindings sync
|
||||
run_system_env always project_host bindings sync
|
||||
run_templates trusted project_host bindings async
|
||||
run_test_reports trusted project_host bindings async
|
||||
run_tomcat_artifacts trusted project_host bindings async
|
||||
run_tomcat_build trusted project_host bindings async
|
||||
run_tomcat_home trusted project_host bindings async
|
||||
run_tomcat_installations trusted project_host bindings async
|
||||
run_tomcat_sync trusted project_host bindings async
|
||||
run_tomcat_update trusted project_host bindings async
|
||||
run_without_derived trusted project_host bindings async
|
||||
scaffold_catalog always project_host bindings sync
|
||||
scaffold_create always project_host bindings async
|
||||
scaffold_options always project_host bindings async
|
||||
scaffold_requirements always project_host bindings async
|
||||
sdk_container_python trusted project_host bindings sync
|
||||
sdk_container_python_refresh trusted project_host bindings async
|
||||
sdk_detect trusted project_host bindings async
|
||||
sdk_locate_tools trusted project_host bindings async
|
||||
sdk_php_composer_install trusted project_host bindings async
|
||||
sdk_php_effective trusted project_host bindings sync
|
||||
sdk_php_language_level trusted project_host bindings async
|
||||
sdk_php_xdebug trusted project_host bindings async
|
||||
sdk_project_libraries trusted project_host bindings async
|
||||
sdk_python_create_venv trusted project_host bindings async
|
||||
sdk_python_effective trusted project_host bindings sync
|
||||
sdk_python_interpreter trusted project_host bindings async
|
||||
sdk_python_packages trusted project_host bindings async
|
||||
sdk_python_pip trusted project_host bindings async
|
||||
sdk_python_project_interpreters trusted project_host bindings async
|
||||
search_start always project_host bindings async
|
||||
search_validate always project_host bindings sync
|
||||
set_recent_project_groups always desktop bindings sync
|
||||
settings_export always desktop bindings async
|
||||
settings_get always project_host bindings sync
|
||||
settings_get_global always desktop bindings sync
|
||||
settings_import always desktop bindings async
|
||||
settings_list_jetbrains_ides always desktop bindings async
|
||||
settings_read_jetbrains always desktop bindings async
|
||||
settings_set always project_host bindings sync
|
||||
spell_check always project_host bindings async
|
||||
spell_suggest always project_host bindings async
|
||||
spring_route_sources trusted desktop bindings sync
|
||||
ssh_askpass_answer always desktop bindings sync
|
||||
ssh_connected always project_host bindings sync
|
||||
ssh_disconnect always project_host bindings sync
|
||||
ssh_needs_secret always project_host bindings sync
|
||||
ssh_open_terminal always desktop bindings async
|
||||
ssh_password_saved always project_host bindings sync
|
||||
ssh_set_secret always project_host bindings sync
|
||||
ssh_test always project_host bindings async
|
||||
ssh_trust_host always project_host bindings async
|
||||
structural_languages always project_host bindings async
|
||||
structural_search always project_host bindings async
|
||||
structural_validate always project_host bindings async
|
||||
syntax_errors always project_host bindings async
|
||||
syntax_expression_at always project_host bindings async
|
||||
syntax_identifiers always project_host bindings async
|
||||
syntax_identifiers_in_files always project_host bindings async
|
||||
syntax_locals always project_host bindings async
|
||||
syntax_node_at always project_host bindings async
|
||||
syntax_structural_ranges always project_host bindings async
|
||||
syntax_support always project_host bindings sync
|
||||
system_font_families always desktop bindings async
|
||||
system_probe_hotkeys trusted desktop bindings sync
|
||||
term_available_shells always project_host bindings sync
|
||||
term_default_shell always project_host bindings sync
|
||||
term_is_busy always project_host bindings async
|
||||
term_kill always project_host bindings sync
|
||||
term_resize always project_host bindings sync
|
||||
term_spawn always project_host bindings async
|
||||
term_store_image always project_host bindings async
|
||||
term_write always project_host bindings sync
|
||||
tools_install trusted project_host bindings async
|
||||
tools_list trusted project_host bindings async
|
||||
tools_uninstall trusted project_host bindings async
|
||||
tools_updates trusted project_host bindings async
|
||||
undo_workspace_edit always project_host bindings async
|
||||
user_font_data always desktop - async
|
||||
vcs_add_to_ignore trusted project_host bindings async
|
||||
vcs_add_worktree trusted project_host bindings async
|
||||
vcs_apply_patch trusted project_host bindings async
|
||||
vcs_blame always project_host bindings async
|
||||
vcs_block_history always project_host bindings async
|
||||
vcs_branch_info always project_host bindings async
|
||||
vcs_branches always project_host bindings async
|
||||
vcs_changelists_load always project_host bindings async
|
||||
vcs_changelists_save trusted project_host bindings sync
|
||||
vcs_checkout trusted project_host bindings async
|
||||
vcs_clone always project_host bindings async
|
||||
vcs_commit trusted project_host bindings async
|
||||
vcs_commit_files always project_host bindings async
|
||||
vcs_commits_changes always project_host bindings async
|
||||
vcs_compare_paths always project_host bindings async
|
||||
vcs_compare_scope always project_host bindings async
|
||||
vcs_config_get always project_host bindings async
|
||||
vcs_conflict_versions always project_host bindings async
|
||||
vcs_create_branch trusted project_host bindings async
|
||||
vcs_create_patch trusted project_host bindings async
|
||||
vcs_create_tag trusted project_host bindings async
|
||||
vcs_delete_branch trusted project_host bindings async
|
||||
vcs_delete_tag trusted project_host bindings async
|
||||
vcs_detected_git always project_host bindings sync
|
||||
vcs_diff_hunks always project_host bindings async
|
||||
vcs_diff_numstat always project_host bindings async
|
||||
vcs_diff_revisions always project_host bindings async
|
||||
vcs_diff_text always project_host bindings async
|
||||
vcs_diff_with_worktree always project_host bindings async
|
||||
vcs_discard trusted project_host bindings async
|
||||
vcs_edit_remote trusted project_host bindings async
|
||||
vcs_file_at always project_host bindings async
|
||||
vcs_file_mode trusted project_host bindings async
|
||||
vcs_git_version trusted project_host bindings async
|
||||
vcs_has_hook always project_host bindings async
|
||||
vcs_ignore_blame_revision trusted project_host bindings async
|
||||
vcs_init always project_host bindings async
|
||||
vcs_line_hunks always project_host bindings async
|
||||
vcs_log always project_host bindings async
|
||||
vcs_log_details always project_host bindings async
|
||||
vcs_log_details_batch always project_host bindings async
|
||||
vcs_log_refs always project_host bindings async
|
||||
vcs_log_users always project_host bindings async
|
||||
vcs_merge trusted project_host bindings async
|
||||
vcs_merge_base always project_host bindings async
|
||||
vcs_merge_with trusted project_host bindings async
|
||||
vcs_move_worktree trusted project_host bindings async
|
||||
vcs_open_external_log always project_host bindings async
|
||||
vcs_operation trusted project_host bindings async
|
||||
vcs_patch_preview trusted project_host bindings async
|
||||
vcs_rebase trusted project_host bindings async
|
||||
vcs_rebase_with trusted project_host bindings async
|
||||
vcs_remote trusted project_host bindings async
|
||||
vcs_remotes always project_host bindings async
|
||||
vcs_remove_worktree trusted project_host bindings async
|
||||
vcs_rename_branch trusted project_host bindings async
|
||||
vcs_restore_branch trusted project_host bindings async
|
||||
vcs_restore_head trusted project_host bindings async
|
||||
vcs_restore_tag trusted project_host bindings async
|
||||
vcs_revision_children always project_host bindings async
|
||||
vcs_revision_files always project_host bindings async
|
||||
vcs_reword trusted project_host bindings async
|
||||
vcs_roots always project_host bindings sync
|
||||
vcs_shelf_delete trusted project_host bindings async
|
||||
vcs_shelf_diff trusted project_host bindings async
|
||||
vcs_shelf_import trusted project_host bindings async
|
||||
vcs_shelf_patch always project_host bindings async
|
||||
vcs_shelf_rename trusted project_host bindings async
|
||||
vcs_shelve trusted project_host bindings async
|
||||
vcs_shelves always project_host bindings async
|
||||
vcs_stage trusted project_host bindings async
|
||||
vcs_stage_hunks trusted project_host bindings async
|
||||
vcs_stage_patch trusted project_host bindings async
|
||||
vcs_stash_apply trusted project_host bindings async
|
||||
vcs_stash_drop trusted project_host bindings async
|
||||
vcs_stash_push trusted project_host bindings async
|
||||
vcs_stashes always project_host bindings async
|
||||
vcs_status always project_host bindings async
|
||||
vcs_status_paths always project_host bindings async
|
||||
vcs_tags always project_host bindings async
|
||||
vcs_undo_commit trusted project_host bindings async
|
||||
vcs_unshelve trusted project_host bindings async
|
||||
vcs_unstage trusted project_host bindings async
|
||||
vcs_worktrees always project_host bindings async
|
||||
vcs_write_patch always project_host bindings async
|
||||
web_browsers always desktop bindings async
|
||||
web_goto always project_host bindings async
|
||||
web_open always desktop bindings async
|
||||
web_serves_page trusted desktop bindings async
|
||||
web_unresolved_references always project_host bindings async
|
||||
web_url always project_host bindings async
|
||||
window_close_context always desktop bindings sync
|
||||
window_complete_launch always desktop bindings sync
|
||||
window_cycle always desktop bindings sync
|
||||
window_flash_taskbar always desktop bindings sync
|
||||
window_group_cancel_close always desktop bindings sync
|
||||
window_group_close always desktop bindings sync
|
||||
window_group_close_tabs always desktop bindings sync
|
||||
window_group_current always desktop bindings sync
|
||||
window_group_detach always desktop bindings async
|
||||
window_group_merge always desktop bindings async
|
||||
window_group_reorder always desktop bindings async
|
||||
window_group_restore always desktop bindings async
|
||||
window_group_select always desktop bindings async
|
||||
window_is_fullscreen always desktop bindings sync
|
||||
window_new always desktop bindings async
|
||||
window_open_comparison always desktop bindings async
|
||||
window_open_deployment always desktop bindings async
|
||||
window_open_diff always desktop bindings async
|
||||
window_open_file_in_new_window always desktop bindings async
|
||||
window_open_files always desktop bindings async
|
||||
window_open_project always desktop bindings async
|
||||
window_open_projects always desktop bindings sync
|
||||
window_open_remote always desktop bindings async
|
||||
window_open_settings always desktop bindings async
|
||||
window_set_titlebar_height always desktop bindings sync
|
||||
window_start_drag always desktop bindings sync
|
||||
window_take_launch always desktop bindings sync
|
||||
window_toggle_fullscreen always desktop bindings sync
|
||||
window_toggle_zoom always desktop bindings sync
|
||||
workspace_attach always desktop bindings async
|
||||
workspace_create always desktop bindings async
|
||||
workspace_discover_projects always desktop bindings async
|
||||
workspace_update always desktop bindings async
|
||||
wsl_distros always desktop bindings async
|
||||
wsl_resolve always desktop bindings sync
|
||||
@@ -1,98 +1,7 @@
|
||||
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts` and
|
||||
//! `src-tauri/tests/commands.snap` without launching the app (used by `pnpm gen:bindings`
|
||||
//! and CI drift checks).
|
||||
|
||||
use ide_host::trust::{projectless_command_allowed, restricted_command_allowed};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
use tauri_specta::{BuilderConfiguration, LanguageExt};
|
||||
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts`
|
||||
//! without launching the app (used by `pnpm gen:bindings` and CI drift checks).
|
||||
|
||||
#[test]
|
||||
fn export_bindings() {
|
||||
openidea_lib::export_bindings(&openidea_lib::specta_builder());
|
||||
}
|
||||
|
||||
/// Commands registered outside tauri-specta (`src-tauri/src/lib.rs`), with how Tauri runs them.
|
||||
const RAW_COMMANDS: &[(&str, &str)] = &[("user_font_data", "async")];
|
||||
|
||||
/// Every command, one line each: its trust class, where a remote window runs it, whether it is
|
||||
/// in `bindings.ts`, and how Tauri runs it. A change to any of these shows up in this file's diff.
|
||||
#[test]
|
||||
fn export_command_snapshot() {
|
||||
let target = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/commands.snap");
|
||||
let fresh = std::env::temp_dir().join(format!("openidea-commands-{}.snap", std::process::id()));
|
||||
openidea_lib::specta_builder().export(CommandSnapshot, &fresh).expect("command snapshot");
|
||||
let text = std::fs::read(&fresh).expect("exported command snapshot");
|
||||
let _ = std::fs::remove_file(&fresh);
|
||||
if std::fs::read(&target).ok().as_deref() != Some(text.as_slice()) {
|
||||
std::fs::write(&target, text).expect("failed to write the command snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandSnapshot;
|
||||
|
||||
impl LanguageExt for CommandSnapshot {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn export(self, cfg: &BuilderConfiguration, path: &Path) -> std::io::Result<()> {
|
||||
let spawned = spawned_commands();
|
||||
let mut modes: BTreeMap<&str, &str> = cfg
|
||||
.commands
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let mode = if spawned.contains(f.name()) {
|
||||
"spawn"
|
||||
} else if f.asyncness() {
|
||||
"async"
|
||||
} else {
|
||||
"sync"
|
||||
};
|
||||
(f.name(), mode)
|
||||
})
|
||||
.collect();
|
||||
let in_bindings: BTreeSet<&str> = modes.keys().copied().collect();
|
||||
modes.extend(RAW_COMMANDS.iter().copied());
|
||||
let routed: BTreeSet<&str> = ide_host::rpc::client_commands().into_iter().collect();
|
||||
let names: BTreeSet<&str> = modes.keys().chain(&routed).copied().collect();
|
||||
|
||||
let mut out = String::from(
|
||||
"# Generated by `pnpm gen:bindings`; do not edit. One line per command:\n\
|
||||
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.\n",
|
||||
);
|
||||
for name in names {
|
||||
let trust = if restricted_command_allowed(name) {
|
||||
"always"
|
||||
} else if projectless_command_allowed(name) {
|
||||
"outside_restricted"
|
||||
} else {
|
||||
"trusted"
|
||||
};
|
||||
let placement = if routed.contains(name) { "project_host" } else { "desktop" };
|
||||
let bindings = if in_bindings.contains(name) { "bindings" } else { "-" };
|
||||
let mode = modes.get(name).copied().unwrap_or("-");
|
||||
out.push_str(&format!("{name:<44} {trust:<18} {placement:<12} {bindings:<8} {mode}\n"));
|
||||
}
|
||||
std::fs::write(path, out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sync commands declared `#[tauri::command(async)]`, which Tauri runs off the main thread.
|
||||
fn spawned_commands() -> BTreeSet<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
while let Some(dir) = dirs.pop() {
|
||||
for entry in std::fs::read_dir(&dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
dirs.push(path);
|
||||
continue;
|
||||
}
|
||||
let source = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
for (_, rest) in source.match_indices("#[tauri::command(async)]").map(|(i, _)| source.split_at(i)) {
|
||||
let name = rest.split("fn ").nth(1).and_then(|s| s.split('(').next());
|
||||
out.insert(name.expect("a function after #[tauri::command(async)]").trim().to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+1
-63
@@ -750,12 +750,6 @@ export const commands = {
|
||||
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
|
||||
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
|
||||
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
|
||||
/**
|
||||
* Show Diff in External Tool: starts the tool set in the global settings (never a
|
||||
* project's, which a cloned repository could carry) on the two sides, on this machine
|
||||
* (a remote window passes the sides as text).
|
||||
*/
|
||||
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
|
||||
/**
|
||||
* Stages only the selected hunks of a file's working-tree changes.
|
||||
* Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
|
||||
@@ -2270,18 +2264,6 @@ export type AgentSettings_Deserialize = {
|
||||
smoothText?: boolean,
|
||||
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
|
||||
fitWindowWidth?: boolean,
|
||||
/** While the agent works, playful words fill the pauses in what it reports. */
|
||||
playfulStatus?: boolean,
|
||||
/**
|
||||
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
* from the start.
|
||||
*/
|
||||
playfulAfterSeconds?: number,
|
||||
/**
|
||||
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
* the built-in ones of that activity; an empty list keeps its status factual.
|
||||
*/
|
||||
playfulWords?: { [key in string]: string[] },
|
||||
thinking?: ThinkingDisplay,
|
||||
toolCalls?: ToolCallDisplay,
|
||||
/** A tool call's output (a command's, a diff) is shown without opening it. */
|
||||
@@ -2322,18 +2304,6 @@ export type AgentSettings_Serialize = {
|
||||
smoothText: boolean,
|
||||
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
|
||||
fitWindowWidth: boolean,
|
||||
/** While the agent works, playful words fill the pauses in what it reports. */
|
||||
playfulStatus: boolean,
|
||||
/**
|
||||
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
* from the start.
|
||||
*/
|
||||
playfulAfterSeconds: number,
|
||||
/**
|
||||
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
* the built-in ones of that activity; an empty list keeps its status factual.
|
||||
*/
|
||||
playfulWords: { [key in string]: string[] },
|
||||
thinking: ThinkingDisplay,
|
||||
toolCalls: ToolCallDisplay,
|
||||
/** A tool call's output (a command's, a diff) is shown without opening it. */
|
||||
@@ -5100,26 +5070,6 @@ export type ExtensionPointInfo = {
|
||||
contributors: string[],
|
||||
};
|
||||
|
||||
/** Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences. */
|
||||
export type ExternalDiffSettings = {
|
||||
/** Offer Show Diff in External Tool in diff viewers. */
|
||||
enabled?: boolean,
|
||||
/** The program to start. */
|
||||
path?: string,
|
||||
/** Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title. */
|
||||
parameters?: string,
|
||||
};
|
||||
|
||||
/** One side of the diff: a file on disk, or text written to a temporary file. */
|
||||
export type ExternalDiffSide = {
|
||||
/** A saved file, passed to the tool as it is. */
|
||||
path: string | null,
|
||||
/** Content without a file of its own (a revision, a text), written to a temporary file. */
|
||||
text: string | null,
|
||||
/** The temporary file's name; its extension lets the tool pick a syntax. */
|
||||
name: string,
|
||||
};
|
||||
|
||||
/** A formatter that runs outside the language servers, with its own settings group. */
|
||||
export type ExternalFormatter = "prettier" | "oxfmt" | "ruff";
|
||||
|
||||
@@ -6993,7 +6943,6 @@ export type LanguagesSettings = {
|
||||
ruby?: RubySettings,
|
||||
markdown?: MarkdownSettings,
|
||||
arduino?: ArduinoSettings,
|
||||
zig?: ZigSettings,
|
||||
};
|
||||
|
||||
/** What a freshly opened window should do once its frontend is up. */
|
||||
@@ -7082,7 +7031,7 @@ export type Launch_Serialize = {
|
||||
export type LibraryGroup = {
|
||||
/** Display name, e.g. `Python 3.12 (.venv)`. */
|
||||
name: string,
|
||||
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`. */
|
||||
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`. */
|
||||
kind: string,
|
||||
roots: LibraryRoot[],
|
||||
};
|
||||
@@ -9514,8 +9463,6 @@ export type RunSettings = {
|
||||
/** Ask before closing a Run tab whose process is still running. */
|
||||
confirmTerminate?: boolean,
|
||||
showOnStart?: boolean,
|
||||
/** New Run/Debug tabs start pinned: a later run doesn't take their place once finished. */
|
||||
pinTabs?: boolean,
|
||||
/** Grace period between interrupt and kill when stopping a process. */
|
||||
terminationTimeoutMs?: number,
|
||||
};
|
||||
@@ -9803,8 +9750,6 @@ export type Settings_Deserialize = {
|
||||
terminal?: TerminalSettings,
|
||||
actionsOnSave?: ActionsOnSaveSettings,
|
||||
externalTools?: ExternalTool[],
|
||||
/** Tools › Diff & Merge › External Diff Tools. */
|
||||
externalDiff?: ExternalDiffSettings,
|
||||
/**
|
||||
* Language servers / debug adapters at a user-chosen location, by the
|
||||
* command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
@@ -9869,8 +9814,6 @@ export type Settings_Serialize = {
|
||||
terminal: TerminalSettings,
|
||||
actionsOnSave: ActionsOnSaveSettings,
|
||||
externalTools: ExternalTool[],
|
||||
/** Tools › Diff & Merge › External Diff Tools. */
|
||||
externalDiff: ExternalDiffSettings,
|
||||
/**
|
||||
* Language servers / debug adapters at a user-chosen location, by the
|
||||
* command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
@@ -11012,11 +10955,6 @@ export type Worktree = {
|
||||
prunable: boolean,
|
||||
};
|
||||
|
||||
export type ZigSettings = {
|
||||
/** Directory holding the `zig` executable; empty = the one on `PATH`. */
|
||||
zig?: string,
|
||||
};
|
||||
|
||||
/* Tauri Specta runtime */
|
||||
async function typedError<T, E>(result: Promise<T>): Promise<{ status: "ok"; data: T } | { status: "error"; error: E }> {
|
||||
try {
|
||||
|
||||
@@ -4,13 +4,11 @@
|
||||
* (view/FindBar.tsx). Highlighting is ours because CodeMirror only highlights
|
||||
* while its own panel is open. Match positions found by the bar's counter are
|
||||
* kept in `findMarks` for the overview lane. The search context (comments /
|
||||
* string literals), excluded matches and "Search In Changes" (a diff's changed
|
||||
* ranges) filter matches through the query's `test`, so CodeMirror's own commands
|
||||
* honour them too.
|
||||
* string literals) and excluded matches filter matches through the query's
|
||||
* `test`, so CodeMirror's own commands honour them too.
|
||||
*/
|
||||
import {
|
||||
EditorSelection,
|
||||
Facet,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
@@ -95,33 +93,16 @@ export function isExcluded(state: EditorState, from: number, to: number): boolea
|
||||
return (state.field(findExcluded, false) ?? []).some((x) => x.from === from && x.to === to);
|
||||
}
|
||||
|
||||
/**
|
||||
* The changed ranges of a diff pane, for "Search In Changes"; editors outside a diff have none.
|
||||
* Called per match, so providers read state the diff already keeps.
|
||||
*/
|
||||
export const findChangedRanges = Facet.define<
|
||||
(state: EditorState) => readonly FindScope[],
|
||||
((state: EditorState) => readonly FindScope[]) | null
|
||||
>({ combine: (values) => values[0] ?? null });
|
||||
|
||||
function inChangedRange(state: EditorState, from: number, to: number): boolean {
|
||||
const ranges = state.facet(findChangedRanges)?.(state) ?? [];
|
||||
return ranges.some((r) => r.from <= from && to <= r.to);
|
||||
}
|
||||
|
||||
type MatchTest = (match: string, state: EditorState, from: number, to: number) => boolean;
|
||||
const tests = new Map<string, MatchTest>();
|
||||
const tests = new Map<SearchContext, MatchTest>();
|
||||
|
||||
/** One stable test per filter, so equal options give equal queries (`SearchQuery.eq`). */
|
||||
function testFor(context: SearchContext, inChanges: boolean): MatchTest {
|
||||
const key = `${context}:${inChanges}`;
|
||||
let test = tests.get(key);
|
||||
/** One stable test per context, so equal options give equal queries (`SearchQuery.eq`). */
|
||||
function testFor(context: SearchContext): MatchTest {
|
||||
let test = tests.get(context);
|
||||
if (!test) {
|
||||
test = (_match, state, from, to) =>
|
||||
!isExcluded(state, from, to) &&
|
||||
(!inChanges || inChangedRange(state, from, to)) &&
|
||||
(context === "any" || contextAccepts(context, literalKindAt(state, from)));
|
||||
tests.set(key, test);
|
||||
!isExcluded(state, from, to) && (context === "any" || contextAccepts(context, literalKindAt(state, from)));
|
||||
tests.set(context, test);
|
||||
}
|
||||
return test;
|
||||
}
|
||||
@@ -234,13 +215,7 @@ export interface FindOptions {
|
||||
preserveCase?: boolean;
|
||||
}
|
||||
|
||||
/** A bar's query: its options, plus filters that belong to what it searches rather than the last search. */
|
||||
export interface FindQueryOptions extends FindOptions {
|
||||
/** Only matches inside a diff's changed ranges (`findChangedRanges`). */
|
||||
inChanges?: boolean;
|
||||
}
|
||||
|
||||
export function makeQuery(o: FindQueryOptions) {
|
||||
export function makeQuery(o: FindOptions) {
|
||||
return new SearchQuery({
|
||||
search: o.search,
|
||||
// Plain-text search and replace are literal (`\n` is not a newline), as in IDEA.
|
||||
@@ -249,11 +224,11 @@ export function makeQuery(o: FindQueryOptions) {
|
||||
wholeWord: o.wholeWord,
|
||||
regexp: o.regexp,
|
||||
replace: o.replace,
|
||||
test: testFor(o.context ?? "any", !!o.inChanges),
|
||||
test: testFor(o.context ?? "any"),
|
||||
});
|
||||
}
|
||||
|
||||
export function setQuery(view: EditorView, o: FindQueryOptions) {
|
||||
export function setQuery(view: EditorView, o: FindOptions) {
|
||||
const q = makeQuery(o);
|
||||
if (q.eq(getSearchQuery(view.state))) return;
|
||||
view.dispatch({ effects: setSearchQuery.of(q) });
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { getIndentation, indentUnit } from "@codemirror/language";
|
||||
import { completedSyntaxTree } from "@/test/syntax";
|
||||
import { classHighlighter, highlightTree } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport, loadedSupport } from "./languages";
|
||||
@@ -82,23 +81,6 @@ describe("frontend string interpolation", () => {
|
||||
expect(out.some((t) => t.text.includes("{brace}") && t.style === "tok-string")).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["Kotlin", "Scala", "Dart", "Groovy", "C#"])(
|
||||
"%s indents brackets opened after a string from the line's indentation",
|
||||
async (mode) => {
|
||||
const support = await loadSupport(findLanguageDescription(mode, "")!);
|
||||
const doc = 'f(\n pair("a", g(\n x\n )),\n)';
|
||||
const state = EditorState.create({
|
||||
doc,
|
||||
extensions: [support!, indentUnit.of(" "), EditorState.tabSize.of(4)],
|
||||
});
|
||||
completedSyntaxTree(state);
|
||||
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
|
||||
expect(indent(3)).toBe(8);
|
||||
// C#'s mode leaves a closing bracket's indentation to the editor.
|
||||
if (mode !== "C#") expect(indent(4)).toBe(4);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps Groovy dotted interpolation in code", async () => {
|
||||
const out = await tokens("Groovy", '"$person.name tail"');
|
||||
expect(out).toContainEqual(expect.objectContaining({ text: "name", style: "tok-variableName" }));
|
||||
|
||||
@@ -114,11 +114,7 @@ export function interpolationParser<S>(base: StreamParser<S>, dialect: Interpola
|
||||
}
|
||||
if (opening && style !== "comment" && style !== "string.special") {
|
||||
stream.pos = from + opening.length;
|
||||
// Let the base tokenizer see an empty string at the literal's own column: a stream
|
||||
// at column 0 would read as a new line and reset the base's line indentation.
|
||||
const empty = new StringStream(stream.string.slice(0, from) + '""', 4, state.indentUnit);
|
||||
empty.pos = empty.start = from;
|
||||
base.token(empty, frame.code);
|
||||
base.token(new StringStream('""', 4, state.indentUnit), frame.code);
|
||||
frame.literal = {
|
||||
quote,
|
||||
braces,
|
||||
|
||||
@@ -28,14 +28,6 @@ describe("Sort Lines / Reverse Lines", () => {
|
||||
expect(apply(doc, sel, sortLinesSpec)).toBe("a\nb\n--\nc\nd");
|
||||
});
|
||||
|
||||
it("sorts by code unit, uppercase before lowercase, as IDEA does", () => {
|
||||
const doc = '"github:opentofu/tofu-ls" = "0.5"\n"github:PowerShell/PowerShellEditorServices" = "4.7"';
|
||||
expect(apply(doc, undefined, sortLinesSpec)).toBe(
|
||||
'"github:PowerShell/PowerShellEditorServices" = "4.7"\n"github:opentofu/tofu-ls" = "0.5"',
|
||||
);
|
||||
expect(apply("b\nB\na\nA\n_\n1", undefined, sortLinesSpec)).toBe("1\nA\nB\n_\na\nb");
|
||||
});
|
||||
|
||||
it("does nothing for a single line or an already sorted block", () => {
|
||||
expect(apply("only", undefined, sortLinesSpec)).toBeNull();
|
||||
expect(apply("a\nb", undefined, sortLinesSpec)).toBeNull();
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
type TransactionSpec,
|
||||
} from "@codemirror/state";
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: false, sensitivity: "variant" });
|
||||
|
||||
/** Line blocks the command applies to: one per non-empty selection range, or the document. */
|
||||
function blocks(state: EditorState): Array<{ from: number; to: number }> {
|
||||
const ranges = state.selection.ranges.filter((r) => !r.empty);
|
||||
@@ -57,11 +59,8 @@ function rewrite(
|
||||
};
|
||||
}
|
||||
|
||||
/** Plain UTF-16 code-unit order, as IDEA sorts (`String.compareTo`): every uppercase letter before every lowercase one. */
|
||||
const byCodeUnit = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
||||
|
||||
export function sortLinesSpec(state: EditorState): TransactionSpec | null {
|
||||
return rewrite(state, (lines) => [...lines].sort(byCodeUnit), "input.sort");
|
||||
return rewrite(state, (lines) => [...lines].sort((a, b) => collator.compare(a, b)), "input.sort");
|
||||
}
|
||||
|
||||
export function reverseLinesSpec(state: EditorState): TransactionSpec | null {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DocModel } from "./model/document";
|
||||
import { offerMakeWritable, readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
|
||||
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
|
||||
|
||||
function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: string | null }> = {}) {
|
||||
const meta = { readOnly, banner: extra.banner ?? (readOnly ? "readOnly" : null) };
|
||||
@@ -43,27 +43,3 @@ describe("Toggle Read-only Attribute", () => {
|
||||
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
|
||||
});
|
||||
});
|
||||
|
||||
describe("editing a read-only file", () => {
|
||||
it("offers to make it writable once, then lets edits through", async () => {
|
||||
const m = model(true);
|
||||
answer = true;
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable" }));
|
||||
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
|
||||
expect(offerMakeWritable(m)).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses edits without asking for library, binary and too-large documents", () => {
|
||||
for (const m of [
|
||||
model(true, { virtual: true }),
|
||||
model(true, { banner: "binary" }),
|
||||
model(true, { banner: "tooLarge" }),
|
||||
])
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
expect(offerMakeWritable(model(false))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* File › File Properties › Make File Read-only / Writable (IDEA's "Toggle
|
||||
* Read-only Attribute", also the status bar lock): asks, then flips the
|
||||
* file's writable bit and the open document's editability. Typing into a file
|
||||
* whose read-only attribute is set asks the same (IDEA's Clear Read-Only Status).
|
||||
* file's writable bit and the open document's editability.
|
||||
*/
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
@@ -42,22 +41,3 @@ export function toggleReadOnly(model: DocModel) {
|
||||
(ok) => ok && void setFileWritable(model, meta.readOnly),
|
||||
);
|
||||
}
|
||||
|
||||
let asking: DocModel | null = null;
|
||||
|
||||
/**
|
||||
* An edit was attempted in `model`. When only the file's read-only attribute is in the
|
||||
* way (not a binary, too large or library file), offers to make it writable, once at a
|
||||
* time. Returns whether the edit was refused: the caller drops it either way.
|
||||
*/
|
||||
export function offerMakeWritable(model: DocModel): boolean {
|
||||
const meta = model.getMeta();
|
||||
if (!meta.readOnly) return false;
|
||||
if (model.virtual || meta.banner !== "readOnly" || asking) return true;
|
||||
asking = model;
|
||||
const q = readOnlyQuestion(basename(model.path), true);
|
||||
void confirm({ title: q.title, message: q.message, ok: q.confirm })
|
||||
.then((ok) => ok && model.getMeta().readOnly && setFileWritable(model, true))
|
||||
.finally(() => (asking = null));
|
||||
return true;
|
||||
}
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
import { showContextMenu } from "@/ui";
|
||||
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
import { offerMakeWritable } from "../fileAttributes";
|
||||
import type { DocModel } from "./document";
|
||||
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
|
||||
import { isNavigation } from "./navHistory";
|
||||
@@ -148,12 +147,6 @@ export class EditorSlot {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
private refuseReadOnlyEdit(e: Event): boolean {
|
||||
if (!offerMakeWritable(this.model)) return false;
|
||||
e.preventDefault();
|
||||
return true;
|
||||
}
|
||||
|
||||
private slotExtensions() {
|
||||
return [
|
||||
this.model.manager.workspaceHistory.extension(this.historyTarget),
|
||||
@@ -176,10 +169,6 @@ export class EditorSlot {
|
||||
this.host.onContextMenu(this, e);
|
||||
return true;
|
||||
},
|
||||
// Typing, pasting or dropping into a read-only file offers to make it writable.
|
||||
beforeinput: (e) => this.refuseReadOnlyEdit(e),
|
||||
paste: (e) => this.refuseReadOnlyEdit(e),
|
||||
drop: (e) => this.refuseReadOnlyEdit(e),
|
||||
}),
|
||||
ViewPlugin.define((view) => {
|
||||
// Gutters sit outside the content DOM. Gutter extensions with their own menu (breakpoints,
|
||||
|
||||
@@ -99,8 +99,6 @@ export interface FindTarget {
|
||||
/** Still open: an unmount that isn't a close (React's dev-mode remount) keeps the highlights. */
|
||||
isOpen(): boolean;
|
||||
results?(options: FindOptions): FindResultsSource | null;
|
||||
/** A diff pane's "Search In Changes" filter, kept by the diff (not the last search). */
|
||||
inChanges?: { get(): boolean; set(on: boolean): void };
|
||||
}
|
||||
|
||||
const activeTab = (paneId: string) => useTabs.getState().panes[paneId]?.active ?? null;
|
||||
@@ -375,13 +373,6 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
const [historyMenu, setHistoryMenu] = useState<"find" | "replace" | null>(null);
|
||||
const [filterMenu, setFilterMenu] = useState(false);
|
||||
const setOpts = (patch: Partial<FindOptions>) => updateOptions(id, () => patch);
|
||||
// Search In Changes applies to finding only, as in IDEA: the replace bar searches the whole side.
|
||||
const [inChangesOn, setInChangesOn] = useState(() => !!target.inChanges?.get());
|
||||
const inChanges = !!target.inChanges && !replace && inChangesOn;
|
||||
const toggleInChanges = () => {
|
||||
target.inChanges?.set(!inChangesOn);
|
||||
setInChangesOn(!inChangesOn);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
panelTargets.set(id, target);
|
||||
@@ -430,16 +421,15 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
|
||||
// Push the query into the editor. Like IDEA, only a change of the query (typing, options)
|
||||
// selects the nearest match: showing the bar again over its editor leaves the caret alone.
|
||||
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions; inChanges: boolean } | null>(null);
|
||||
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions } | null>(null);
|
||||
useEffect(() => {
|
||||
const view = target.view();
|
||||
if (!view) return;
|
||||
const prev = shown.current;
|
||||
const changed =
|
||||
prev?.target === target && prev.version === version && (prev.opts !== opts || prev.inChanges !== inChanges);
|
||||
shown.current = { target, version, opts, inChanges };
|
||||
const changed = prev?.target === target && prev.version === version && prev.opts !== opts;
|
||||
shown.current = { target, version, opts };
|
||||
const valid = !opts.regexp || regexValid(opts.search);
|
||||
setQuery(view, valid ? { ...opts, inChanges } : { ...opts, search: "" });
|
||||
setQuery(view, valid ? opts : { ...opts, search: "" });
|
||||
view.dispatch({ effects: setFindOpen.of(true) });
|
||||
if (changed && valid && opts.search && useFindPreferences.getState().scrollToResults) {
|
||||
const from = view.state.selection.main.from;
|
||||
@@ -447,7 +437,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
findNext(view);
|
||||
}
|
||||
recount(target);
|
||||
}, [opts, target, version, inChanges]);
|
||||
}, [opts, target, version]);
|
||||
|
||||
// Keep the counter current while the document / selection changes.
|
||||
useEffect(() => {
|
||||
@@ -574,9 +564,6 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
checked: scoped || undefined,
|
||||
run: () => toggleScope(target),
|
||||
},
|
||||
...(target.inChanges && !replace
|
||||
? [{ label: "Search In Changes", checked: inChangesOn || undefined, run: toggleInChanges }]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Search Scope" },
|
||||
...SEARCH_CONTEXTS.map((c) => ({
|
||||
@@ -701,7 +688,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
icon="filter"
|
||||
title="Filter Search Results"
|
||||
size="small"
|
||||
pressed={scoped || inChanges || opts.context !== "any"}
|
||||
pressed={scoped || opts.context !== "any"}
|
||||
onClick={() => setFilterMenu(true)}
|
||||
/>
|
||||
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
explicitCompletion,
|
||||
makeCompletion,
|
||||
matchRanges,
|
||||
positionCompletionInfo,
|
||||
sortAlphabetically,
|
||||
} from "./completion";
|
||||
import {
|
||||
@@ -660,58 +659,6 @@ describe("explicit completion", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("documentation beside the lookup", () => {
|
||||
const view = {} as EditorView;
|
||||
const space = { left: 0, top: 0, right: 1200, bottom: 800 };
|
||||
const option = { left: 100, right: 300, top: 120, bottom: 144 };
|
||||
const info = { left: 0, right: 400, top: 0, bottom: 300 };
|
||||
const beside = { left: 100, right: 520, top: 100, bottom: 400 };
|
||||
|
||||
const originalWidth = document.documentElement.clientWidth;
|
||||
afterEach(() => {
|
||||
Object.defineProperty(document.documentElement, "clientWidth", { value: originalWidth, configurable: true });
|
||||
});
|
||||
|
||||
/** `windowWidth` is the room the pane may use; the editor's own box does not limit it. */
|
||||
function place(list: typeof beside, windowWidth = 1200, bounds = space) {
|
||||
Object.defineProperty(document.documentElement, "clientWidth", { value: windowWidth, configurable: true });
|
||||
return positionCompletionInfo(view, list, option, info, bounds);
|
||||
}
|
||||
|
||||
it("sits right of the list when there is room, top edges aligned", () => {
|
||||
const pos = place(beside);
|
||||
expect(pos.class).toBe("cm-completionInfo-right");
|
||||
expect(pos.style).toContain("top: 0");
|
||||
expect(pos.style).toContain("left: calc(100% + 6px)");
|
||||
expect(pos.style).toContain("max-width: 440px");
|
||||
expect(pos.style).toContain("max-height: 320px");
|
||||
});
|
||||
|
||||
it("moves to the left of the list when the right side is narrower", () => {
|
||||
const pos = place({ ...beside, left: 700, right: 1120 });
|
||||
expect(pos.class).toBe("cm-completionInfo-left");
|
||||
expect(pos.style).toContain("right: calc(100% + 6px)");
|
||||
});
|
||||
|
||||
it("narrows the pane to the room the window has, not the editor's", () => {
|
||||
// A 620px-wide editor would leave 94px; the window leaves 274px.
|
||||
const pos = place(beside, 800, { ...space, right: 620 });
|
||||
expect(pos.class).toBe("cm-completionInfo-right");
|
||||
expect(pos.style).toContain("max-width: 274px");
|
||||
});
|
||||
|
||||
it("keeps a readable width in a narrow window rather than covering the list", () => {
|
||||
const pos = place(beside, 620);
|
||||
expect(pos.class).toBe("cm-completionInfo-right");
|
||||
expect(pos.style).toContain("max-width: 220px");
|
||||
});
|
||||
|
||||
it("caps the height to the room below the list and to 320px", () => {
|
||||
expect(place({ ...beside, top: 700, bottom: 780 }).style).toContain("max-height: 100px");
|
||||
expect(place(beside, 1200, { ...space, bottom: 600 }).style).toContain("max-height: 320px");
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion footer", () => {
|
||||
let view: EditorView | null = null;
|
||||
afterEach(() => {
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
|
||||
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
@@ -159,43 +159,6 @@ function resetLookupDocs() {
|
||||
docWaiters.clear();
|
||||
}
|
||||
|
||||
const DOC_MIN_WIDTH = 220;
|
||||
const DOC_MAX_WIDTH = 440;
|
||||
const DOC_MAX_HEIGHT = 320;
|
||||
const DOC_GAP = 6;
|
||||
|
||||
/**
|
||||
* Places the documentation beside the lookup, on whichever side has more room,
|
||||
* with the two popups' top edges aligned. Room is measured to the window's
|
||||
* edges, so a narrow editor still has space for a readable pane; when even the
|
||||
* window is too narrow, the pane keeps a readable width rather than covering the
|
||||
* options.
|
||||
*/
|
||||
export function positionCompletionInfo(
|
||||
_view: EditorView,
|
||||
list: Rect,
|
||||
_option: Rect,
|
||||
_info: Rect,
|
||||
space: Rect,
|
||||
): { style: string; class: string } {
|
||||
const windowWidth = document.documentElement.clientWidth;
|
||||
const rightRoom = windowWidth - list.right - DOC_GAP;
|
||||
const leftRoom = list.left - DOC_GAP;
|
||||
const side = rightRoom >= leftRoom ? "right" : "left";
|
||||
const room = side === "right" ? rightRoom : leftRoom;
|
||||
const width = Math.max(DOC_MIN_WIDTH, Math.min(DOC_MAX_WIDTH, room));
|
||||
return {
|
||||
class: `cm-completionInfo-${side}`,
|
||||
style: [
|
||||
"top: 0",
|
||||
// `left`/`right` names the side the pane sits on; the offset goes on the opposite edge.
|
||||
`${side === "right" ? "left" : "right"}: calc(100% + ${DOC_GAP}px)`,
|
||||
`max-width: ${width}px`,
|
||||
`max-height: ${Math.min(DOC_MAX_HEIGHT, space.bottom - list.top)}px`,
|
||||
].join("; "),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* F1 while the lookup is open: shows the selected item's docs beside it
|
||||
* (`shown`), or reports that they are already showing (`showing`) so the
|
||||
@@ -904,7 +867,6 @@ export function completionExtension() {
|
||||
);
|
||||
},
|
||||
tooltipClass: () => "cm-lsp-completion",
|
||||
positionInfo: positionCompletionInfo,
|
||||
}),
|
||||
completionFooter,
|
||||
lookupTracker,
|
||||
|
||||
@@ -109,8 +109,7 @@ export const lspTheme = EditorView.theme({
|
||||
// (gutter + project sidebar) keeps the word well clear of that edge.
|
||||
marginLeft:
|
||||
"calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))",
|
||||
// No overflow clipping: CodeMirror nests the documentation pane in this box and
|
||||
// positions it outside it (see `positionCompletionInfo`). The footer rounds itself.
|
||||
overflow: "hidden",
|
||||
},
|
||||
".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": {
|
||||
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
|
||||
@@ -195,7 +194,6 @@ export const lspTheme = EditorView.theme({
|
||||
whiteSpace: "nowrap",
|
||||
gap: "12px",
|
||||
justifyContent: "space-between",
|
||||
borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)",
|
||||
},
|
||||
".cm-lsp-completion-sort": {
|
||||
padding: "0",
|
||||
|
||||
@@ -6,7 +6,7 @@ import { HomeEditor } from "./HomeEditor";
|
||||
import homeStyles from "./Home.module.css";
|
||||
import { HOME, disconnect, savedDraft, updateComposer, useAgents } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn(), probe: vi.fn() }));
|
||||
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn() }));
|
||||
const ok = <T,>(data: T) => Promise.resolve({ status: "ok", data });
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
@@ -22,7 +22,7 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agentProbe: (provider: string, refresh: boolean) => backend.probe(provider, refresh),
|
||||
agentProbe: () => ok(null),
|
||||
vcsBranchInfo: () => ok({ head: "main" }),
|
||||
vcsBranches: () => ok([]),
|
||||
agentCreate: (req: NewAgentTask) => backend.create(req),
|
||||
@@ -47,7 +47,6 @@ const option = (id: string, category: string, values: string[], current: string)
|
||||
beforeEach(() => {
|
||||
disconnect();
|
||||
backend.create.mockReset().mockImplementation((req: NewAgentTask) => ok({ id: "new", config: req.config }));
|
||||
backend.probe.mockReset().mockImplementation(() => ok(null));
|
||||
backend.providers = [
|
||||
{
|
||||
id: "fake",
|
||||
@@ -167,25 +166,3 @@ it("applies fitWidth on the New Task page only when fitWindowWidth is enabled",
|
||||
useProject.setState({ settings });
|
||||
}
|
||||
});
|
||||
|
||||
it("refreshes the displayed agent version after a CLI upgrade when the window regains focus", async () => {
|
||||
let installed = "18.20.0";
|
||||
let cached = installed;
|
||||
backend.probe.mockImplementation((provider: string, refresh: boolean) => {
|
||||
if (refresh) cached = installed;
|
||||
return ok({ provider, name: "omp", version: cached, protocol: "ACP v1", error: null });
|
||||
});
|
||||
render(<HomeEditor />);
|
||||
await screen.findByText("omp · 18.20.0 · ACP v1");
|
||||
installed = "18.20.2";
|
||||
fireEvent(window, new Event("focus"));
|
||||
await screen.findByText("omp · 18.20.2 · ACP v1");
|
||||
});
|
||||
|
||||
it("does not reuse a previous page's cached agent version when opened again", async () => {
|
||||
backend.probe.mockImplementation((provider: string, refresh: boolean) =>
|
||||
ok({ provider, name: "omp", version: refresh ? "18.20.2" : "18.20.0", protocol: "ACP v1", error: null }),
|
||||
);
|
||||
render(<HomeEditor />);
|
||||
await screen.findByText("omp · 18.20.2 · ACP v1");
|
||||
});
|
||||
@@ -82,8 +82,7 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
|
||||
}, [root, project?.workspace]);
|
||||
|
||||
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
|
||||
const shown = useEditorShown();
|
||||
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command, shown);
|
||||
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command);
|
||||
const catalog = useAgents((s) => s.modelCatalogs.get(provider?.id ?? ""));
|
||||
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
|
||||
const launch = provider && JSON.stringify([provider.program, provider.args, provider.env, provider.command]);
|
||||
@@ -97,6 +96,7 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
|
||||
const { defaults, fitWindowWidth } = useAgentSettings();
|
||||
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
|
||||
const homeRoot = useRef<HTMLDivElement>(null);
|
||||
const shown = useEditorShown();
|
||||
const unavailableModel = config.some(
|
||||
(o) =>
|
||||
o.category === "model" &&
|
||||
@@ -293,29 +293,18 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
|
||||
);
|
||||
}
|
||||
|
||||
/** Rechecks the installed agent when this page is shown or its window regains focus; opens no session. */
|
||||
function useProbe(provider: string | null, command: string | undefined, shown: boolean): AgentProbe | null {
|
||||
/** What the agent reports about itself when it starts (no session is opened), once per agent. */
|
||||
function useProbe(provider: string | null, command?: string): AgentProbe | null {
|
||||
const [probe, setProbe] = useState<AgentProbe | null>(null);
|
||||
useEffect(() => {
|
||||
if (!provider || !shown) return;
|
||||
if (!provider) return;
|
||||
let live = true;
|
||||
let pending = false;
|
||||
const refresh = () => {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
call(commands.agentProbe(provider, true))
|
||||
.then((p) => live && setProbe(p))
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
pending = false;
|
||||
});
|
||||
};
|
||||
refresh();
|
||||
window.addEventListener("focus", refresh);
|
||||
call(commands.agentProbe(provider, false))
|
||||
.then((p) => live && setProbe(p))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
window.removeEventListener("focus", refresh);
|
||||
};
|
||||
}, [provider, command, shown]);
|
||||
}, [provider, command]);
|
||||
return probe?.provider === provider ? probe : null;
|
||||
}
|
||||
@@ -1031,16 +1031,6 @@
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* Announced to screen readers, not shown: the fact behind a playful status. */
|
||||
.srOnly {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.retrying {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
@@ -86,16 +86,6 @@ import { ImagePreview, imageSrc } from "./ImagePreview";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
|
||||
import { useRevealedText } from "./reveal";
|
||||
import {
|
||||
ACTIVITY_STATUS,
|
||||
PLAYFUL_MIN_MS,
|
||||
PLAYFUL_WORD_MS,
|
||||
PLAYFUL_WORDS,
|
||||
activityOf,
|
||||
playfulIndex,
|
||||
progressKey,
|
||||
type Activity,
|
||||
} from "./workingStatus";
|
||||
import { AgentReply, MessageActions, ReplyActions } from "./AgentReply";
|
||||
import {
|
||||
commandPrefix,
|
||||
@@ -2695,81 +2685,27 @@ function WorkingRow({
|
||||
return (
|
||||
<div className={styles.working} role="status">
|
||||
<Spinner size={12} />
|
||||
{subagent.status === "needsInput" ? (
|
||||
<T>Waiting for your answer…</T>
|
||||
) : (
|
||||
<WorkingLabel turn={entries ?? []} seed={subagent.startedMs ?? 0} />
|
||||
)}
|
||||
<T>{subagent.status === "needsInput" ? "Waiting for your answer…" : "Working…"}</T>
|
||||
{subagent.startedMs != null && <Elapsed since={subagent.startedMs} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (task.status !== "running" && task.status !== "starting") return null;
|
||||
if (entries?.some((e) => e.type === "permission" && !e.chosen && !e.questions?.length)) return null;
|
||||
const userAt = entries?.findLastIndex((e) => e.type === "user") ?? -1;
|
||||
const lastUser = userAt >= 0 ? (entries![userAt] as UserEntry) : undefined;
|
||||
const lastUser = entries?.findLast((e): e is UserEntry => e.type === "user");
|
||||
return (
|
||||
<div className={styles.working} role="status">
|
||||
<Spinner size={12} />
|
||||
{task.retry ? (
|
||||
<Retrying retry={task.retry} />
|
||||
) : task.status === "starting" ? (
|
||||
<T>Starting the agent…</T>
|
||||
) : (
|
||||
<WorkingLabel turn={entries?.slice(userAt + 1) ?? []} seed={lastUser?.sentMs ?? 0} />
|
||||
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
|
||||
)}
|
||||
{lastUser?.sentMs != null && !lastUser.doneMs && <Elapsed since={lastUser.sentMs} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is doing, said by the activity's playful words in turns (the user's own, else the
|
||||
* built-in ones) from the start, or once it has reported nothing new for the user's quiet time;
|
||||
* screen readers hear only the fact. A word stays its full time while it still fits what the agent
|
||||
* does, and a little while when it no longer does, so the row never flickers.
|
||||
*/
|
||||
function WorkingLabel({ turn, seed }: { turn: AgentEntry[]; seed: number }) {
|
||||
const tx = useTx();
|
||||
const { playfulStatus, playfulAfterSeconds, playfulWords } = useAgentSettings();
|
||||
const now = useNow(1000);
|
||||
const key = progressKey(turn);
|
||||
const [progress, setProgress] = useState({ key, at: now });
|
||||
if (progress.key !== key) setProgress({ key, at: now });
|
||||
// The word on screen, and how many the turn has shown, so the next one continues the order.
|
||||
const [playful, setPlayful] = useState<{ shown: number; word: PlayfulWord | null }>({ shown: 0, word: null });
|
||||
const activity = activityOf(turn);
|
||||
const kind = activity ?? "working";
|
||||
const fact = tx(ACTIVITY_STATUS[kind]);
|
||||
const own = playfulWords[kind];
|
||||
const words = own ?? PLAYFUL_WORDS[kind];
|
||||
const due = words.length > 0 && (!activity || now - progress.at >= playfulAfterSeconds * 1000);
|
||||
const current = playful.word;
|
||||
const fits = due && current?.kind === kind;
|
||||
const stays = current && playfulStatus && now - current.since < (fits ? PLAYFUL_WORD_MS : PLAYFUL_MIN_MS);
|
||||
let next = playful;
|
||||
if (!stays && playfulStatus && due) {
|
||||
const text = words[playfulIndex(words.length, seed, playful.shown)]!;
|
||||
next = { shown: playful.shown + 1, word: { text, kind, own: !!own, since: now } };
|
||||
} else if (!stays && current) next = { shown: playful.shown, word: null };
|
||||
if (next !== playful) setPlayful(next);
|
||||
if (!next.word) return fact;
|
||||
return (
|
||||
<>
|
||||
<span aria-hidden>{next.word.own ? next.word.text : tx(next.word.text)}</span>
|
||||
<span className={styles.srOnly}>{fact}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A playful word for `kind` on screen since `since`: the user's own as written, else a built-in one to translate. */
|
||||
interface PlayfulWord {
|
||||
text: string;
|
||||
kind: Activity;
|
||||
own: boolean;
|
||||
since: number;
|
||||
}
|
||||
|
||||
/** The approval the agent waits for, with its answers on 1, 2, 3… */
|
||||
function PendingPermission({ task, entry }: { task: AgentTask; entry: PermissionEntry }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.activity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.after {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.seconds {
|
||||
width: 64px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.items {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
padding: 4px 8px;
|
||||
background: var(--bg-subtle);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
.word {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
/**
|
||||
* Settings › Agents › Working Status: whether the status under a conversation turns playful, after
|
||||
* how long without news, and the playful words of each activity, the built-in ones until the user
|
||||
* writes their own.
|
||||
*/
|
||||
import { useId, useState } from "react";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { PLAYFUL_AFTER_LIMITS } from "@/platform/agentStatus";
|
||||
import { Button, Checkbox, IconButton, Input, Select, T, type SelectOption } from "@/ui";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { AGENT_SETTINGS_DEFAULTS } from "./agentSettings";
|
||||
import { ACTIVITIES, ACTIVITY_STATUS, PLAYFUL_WORDS, type Activity } from "./workingStatus";
|
||||
import styles from "./WorkingStatus.module.css";
|
||||
|
||||
export function WorkingStatusPage() {
|
||||
const tx = useTx();
|
||||
const form = useSettingsForm();
|
||||
const playful =
|
||||
(form.useValue("agents.playfulStatus") as boolean | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulStatus;
|
||||
const own = (form.useValue("agents.playfulWords") ?? {}) as Record<string, string[]>;
|
||||
const [activity, setActivity] = useState<Activity>("working");
|
||||
const [draft, setDraft] = useState("");
|
||||
const selectId = useId();
|
||||
const custom = own[activity];
|
||||
const words = custom ?? PLAYFUL_WORDS[activity].map((w) => tx(w));
|
||||
|
||||
const options: SelectOption<Activity>[] = ACTIVITIES.map((a) => ({
|
||||
value: a,
|
||||
label: ACTIVITY_STATUS[a],
|
||||
detail: own[a] ? "Custom" : undefined,
|
||||
}));
|
||||
const setWords = (next: string[] | null) => {
|
||||
const others = Object.fromEntries(Object.entries(own).filter(([a]) => a !== activity));
|
||||
form.set("agents.playfulWords", next ? { ...others, [activity]: next } : others);
|
||||
};
|
||||
const add = () => {
|
||||
const word = draft.trim();
|
||||
if (!word) return;
|
||||
setDraft("");
|
||||
if (!words.includes(word)) setWords([...words, word]);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={styles.body} aria-label={tx("Working Status")}>
|
||||
<p className={styles.notice}>
|
||||
<T>
|
||||
While the agent works, the line under the conversation says what it is doing. With playful words on, words for
|
||||
what it does take turns there instead, from the start or once it reports nothing new for a while; screen
|
||||
readers still hear the plain status.
|
||||
</T>
|
||||
</p>
|
||||
<Checkbox
|
||||
checked={playful}
|
||||
onChange={(on) => form.set("agents.playfulStatus", on)}
|
||||
label="Playful words while the agent works"
|
||||
/>
|
||||
<PlayfulAfter disabled={!playful} />
|
||||
<div className={styles.activity}>
|
||||
<label htmlFor={selectId}>
|
||||
<T>While the status says</T>
|
||||
</label>
|
||||
<Select id={selectId} value={activity} options={options} onChange={setActivity} disabled={!playful} />
|
||||
</div>
|
||||
<div className={styles.items} role="list" aria-label={tx("Playful words")}>
|
||||
{words.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>No playful words: the status stays factual</T>
|
||||
</div>
|
||||
)}
|
||||
{words.map((word, i) => (
|
||||
<div key={`${i}:${word}`} className={styles.item} role="listitem">
|
||||
<span className={styles.word}>{word}</span>
|
||||
<IconButton
|
||||
icon="close"
|
||||
size="small"
|
||||
title={tx`Remove ${word}`}
|
||||
disabled={!playful}
|
||||
onClick={() => setWords(words.filter((_, j) => j !== i))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.add}>
|
||||
<input
|
||||
type="text"
|
||||
className={styles.input}
|
||||
value={draft}
|
||||
disabled={!playful}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
// Enter adds the word; it does not press the dialog's OK.
|
||||
e.preventDefault();
|
||||
add();
|
||||
}}
|
||||
placeholder={tx("e.g. Reticulating splines…")}
|
||||
aria-label={tx("New playful word")}
|
||||
/>
|
||||
<Button size="small" disabled={!playful} onClick={add}>
|
||||
Add
|
||||
</Button>
|
||||
<Button size="small" disabled={!playful || !custom} onClick={() => setWords(null)}>
|
||||
Restore Built-in Words
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Seconds without news before the status turns playful; invalid text is flagged and reverted on blur. */
|
||||
function PlayfulAfter({ disabled }: { disabled: boolean }) {
|
||||
const tx = useTx();
|
||||
const form = useSettingsForm();
|
||||
const value =
|
||||
(form.useValue("agents.playfulAfterSeconds") as number | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulAfterSeconds;
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const id = useId();
|
||||
const { min, max } = PLAYFUL_AFTER_LIMITS;
|
||||
const parse = (text: string) => {
|
||||
const n = /^\s*\d+\s*$/.test(text) ? Number(text) : NaN;
|
||||
return n >= min && n <= max ? n : null;
|
||||
};
|
||||
const invalid = draft !== null && parse(draft) === null;
|
||||
return (
|
||||
<div className={styles.after}>
|
||||
<label htmlFor={id}>
|
||||
<T>Start after the agent reports nothing new for</T>
|
||||
</label>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.seconds}
|
||||
inputMode="numeric"
|
||||
value={draft ?? String(value)}
|
||||
invalid={invalid}
|
||||
disabled={disabled}
|
||||
title={invalid ? tx`Enter a value between ${min} and ${max}` : undefined}
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
const n = parse(e.target.value);
|
||||
if (n !== null) form.set("agents.playfulAfterSeconds", n);
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
/>
|
||||
<T>seconds</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,9 +13,6 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
|
||||
foldTurns: true,
|
||||
smoothText: true,
|
||||
fitWindowWidth: false,
|
||||
playfulStatus: false,
|
||||
playfulAfterSeconds: 0,
|
||||
playfulWords: {},
|
||||
thinking: "auto",
|
||||
toolCalls: "grouped",
|
||||
expandToolOutput: false,
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
SESSION_KIND,
|
||||
TASK_DRAG,
|
||||
TOOL_WINDOW,
|
||||
WORKING_STATUS_PAGE,
|
||||
providerIcon,
|
||||
} from "./model";
|
||||
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
|
||||
@@ -66,15 +65,6 @@ export function activateSettingsPages(): () => void {
|
||||
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
|
||||
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
|
||||
}),
|
||||
registerSettingsPage({
|
||||
id: WORKING_STATUS_PAGE,
|
||||
title: "Working Status",
|
||||
group: AGENTS_GROUP,
|
||||
// After Chat.
|
||||
order: 465,
|
||||
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
|
||||
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
|
||||
}),
|
||||
registerSettingsPage({
|
||||
id: MCP_PAGE,
|
||||
title: "External MCP Servers",
|
||||
|
||||
@@ -15,8 +15,6 @@ export const AGENTS_GROUP = "Agents";
|
||||
export const MCP_PAGE = "agents.mcpServers";
|
||||
/** Settings › Agents › Command Permissions. */
|
||||
export const POLICY_PAGE = "agents.policy";
|
||||
/** Settings › Agents › Working Status: the playful words under a working conversation. */
|
||||
export const WORKING_STATUS_PAGE = "agents.workingStatus";
|
||||
|
||||
export const sessionKey = (task: string) => `agent:${task}`;
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ import { useChangesOptions } from "./changesOptions";
|
||||
import { taskActions } from "./taskActions";
|
||||
import { replyActions } from "./replyActions";
|
||||
import { focusedSession } from "./sessionFocus";
|
||||
import { PLAYFUL_MIN_MS, PLAYFUL_WORD_MS, PLAYFUL_WORDS } from "./workingStatus";
|
||||
import styles from "./Session.module.css";
|
||||
import chipStyles from "./ReferenceChip.module.css";
|
||||
import { caretOf, textOf, typeIn } from "./composerTesting";
|
||||
@@ -485,130 +484,11 @@ describe("turn folding", () => {
|
||||
// The turn isn't over: its latest message is no final reply yet.
|
||||
expect(stream().querySelector(`.${styles.agentMessage} > .${styles.messageFooter}`)).toBeNull();
|
||||
// What the agent is doing ends the conversation, below its latest output.
|
||||
const working = stream().querySelector(`.${styles.working}`);
|
||||
expect(working).toHaveRole("status");
|
||||
const working = within(stream()).getByText("Working…").closest(`.${styles.working}`);
|
||||
expect(stream().lastElementChild).toBe(working);
|
||||
});
|
||||
});
|
||||
|
||||
describe("working status", () => {
|
||||
const running = (entries: AgentEntry[]) => {
|
||||
backend.entries.set("A", [
|
||||
{ type: "user", text: "Question", attachments: [], steered: false, sentMs: 1000, doneMs: null },
|
||||
...entries,
|
||||
]);
|
||||
useAgents.setState({
|
||||
entries: new Map(backend.entries),
|
||||
tasks: new Map(useAgents.getState().tasks).set("A", {
|
||||
...useAgents.getState().tasks.get("A")!,
|
||||
status: "running",
|
||||
}),
|
||||
});
|
||||
};
|
||||
const playful = (status: HTMLElement) => status.querySelector("[aria-hidden]")?.textContent ?? null;
|
||||
const playfulOn = (agents: object = {}) =>
|
||||
useProject.setState({ settings: { agents: { playfulStatus: true, ...agents } } as never });
|
||||
|
||||
it("says plainly what the agent does by default", async () => {
|
||||
vi.useFakeTimers();
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS * 2));
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
expect(playful(status)).toBeNull();
|
||||
expect(status).toHaveTextContent("Reading…");
|
||||
});
|
||||
|
||||
it("is playful from the start, holds each word while the work goes on, and turns to the new work's words", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn();
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
// Screen readers still hear the fact.
|
||||
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Reading…");
|
||||
|
||||
// More of the same work keeps the word its full time.
|
||||
running([tool("one", { status: "running" }), tool("two", { status: "running" })]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const second = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(second);
|
||||
|
||||
// New work leaves the word a moment, then says the new work playfully too.
|
||||
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe(second);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
|
||||
expect(PLAYFUL_WORDS.writing).toContain(playful(status));
|
||||
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Writing…");
|
||||
});
|
||||
|
||||
it("with a quiet time, is factual until the agent reports nothing new for it, and again on progress", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulAfterSeconds: 10 });
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
expect(status).toHaveTextContent("Reading…");
|
||||
expect(playful(status)).toBeNull();
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(9000));
|
||||
expect(playful(status)).toBeNull();
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
|
||||
// Progress right after a word appeared leaves it a moment before the fact returns.
|
||||
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
|
||||
expect(playful(status)).toBeNull();
|
||||
expect(status).toHaveTextContent("Writing…");
|
||||
});
|
||||
|
||||
it("keeps each word its full time however soon the status turns playful", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulAfterSeconds: 1 });
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(playful(status));
|
||||
});
|
||||
|
||||
it("shows the user's own words of the activity, and none where they left the list empty", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulWords: { reading: ["Squinting really hard…"], working: [] } });
|
||||
running([]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
// Nothing reported yet is `working`, whose list the user emptied.
|
||||
expect(playful(status)).toBeNull();
|
||||
expect(status).toHaveTextContent("Working…");
|
||||
|
||||
running([tool("one", { status: "running" })]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe("Squinting really hard…");
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS));
|
||||
expect(playful(status)).toBe("Squinting really hard…");
|
||||
});
|
||||
});
|
||||
|
||||
describe("opened runs", () => {
|
||||
it("stay open when the finished turn folds them away and is opened again", async () => {
|
||||
const asked = {
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
/**
|
||||
* The label of the row under a conversation while the agent works: what the turn's latest
|
||||
* output says it is doing, and playful words while it reports nothing new (or nothing yet).
|
||||
*/
|
||||
import type { AgentEntry } from "@/bindings";
|
||||
import { subagentWorking } from "./model";
|
||||
|
||||
/** How long one playful word stays while the agent still reports nothing new. */
|
||||
export const PLAYFUL_WORD_MS = 8_000;
|
||||
/** How long a playful word stays at least, even when the agent reports something new meanwhile. */
|
||||
export const PLAYFUL_MIN_MS = 3_000;
|
||||
|
||||
/** What the agent can be doing, as the status tells it; `working` covers the rest. */
|
||||
export const ACTIVITIES = [
|
||||
"working",
|
||||
"thinking",
|
||||
"writing",
|
||||
"reading",
|
||||
"editing",
|
||||
"deleting",
|
||||
"moving",
|
||||
"searching",
|
||||
"running",
|
||||
"fetching",
|
||||
"subagent",
|
||||
] as const;
|
||||
export type Activity = (typeof ACTIVITIES)[number];
|
||||
|
||||
/** The factual status of each activity, also what screen readers hear while it is playful. */
|
||||
export const ACTIVITY_STATUS: Record<Activity, string> = {
|
||||
working: "Working…",
|
||||
thinking: "Thinking…",
|
||||
writing: "Writing…",
|
||||
reading: "Reading…",
|
||||
editing: "Editing…",
|
||||
deleting: "Deleting…",
|
||||
moving: "Moving files…",
|
||||
searching: "Searching…",
|
||||
running: "Running a command…",
|
||||
fetching: "Fetching…",
|
||||
subagent: "Running a subagent…",
|
||||
};
|
||||
|
||||
/** The built-in playful words of each activity, until the user writes their own. */
|
||||
export const PLAYFUL_WORDS: Record<Activity, readonly string[]> = {
|
||||
working: [
|
||||
"Untangling imports…",
|
||||
"Explaining it to the rubber duck…",
|
||||
"Herding semicolons…",
|
||||
"Rebasing onto reality…",
|
||||
"Measuring twice…",
|
||||
"Sharpening the pencils…",
|
||||
"Invalidating a cache…",
|
||||
],
|
||||
thinking: [
|
||||
"Refactoring a hunch…",
|
||||
"Garbage-collecting thoughts…",
|
||||
"Compiling a plan…",
|
||||
"Caching an insight…",
|
||||
"Bisecting the problem…",
|
||||
"Naming things…",
|
||||
],
|
||||
writing: [
|
||||
"Counting brackets…",
|
||||
"Settling tabs versus spaces…",
|
||||
"Choosing words carefully…",
|
||||
"Polishing the prose…",
|
||||
"Drafting, redrafting…",
|
||||
],
|
||||
reading: [
|
||||
"Reading the fine manual…",
|
||||
"Following the breadcrumbs…",
|
||||
"Walking the call stack…",
|
||||
"Reading between the lines…",
|
||||
"Skimming the source…",
|
||||
],
|
||||
editing: [
|
||||
"Squinting at the diff…",
|
||||
"Negotiating with the borrow checker…",
|
||||
"Asking the linter nicely…",
|
||||
"Nudging a semicolon…",
|
||||
"Moving code around gently…",
|
||||
],
|
||||
deleting: ["Tidying up…", "Taking out the trash…", "Pruning dead code…", "Saying goodbye…"],
|
||||
moving: ["Rearranging the furniture…", "Packing boxes…", "Finding a better home…"],
|
||||
searching: ["Grepping the void…", "Chasing a null pointer…", "Looking under the couch…", "Searching high and low…"],
|
||||
running: [
|
||||
"Warming up the compiler…",
|
||||
"Pressing Enter with confidence…",
|
||||
"Watching the logs scroll…",
|
||||
"Waiting on the shell…",
|
||||
],
|
||||
fetching: ["Waiting on the network…", "Downloading the internet…", "Following links…"],
|
||||
subagent: ["Delegating…", "Consulting a colleague…", "Calling in reinforcements…", "Holding a quick stand-up…"],
|
||||
};
|
||||
|
||||
const TOOL_ACTIVITY: Record<string, Activity> = {
|
||||
read: "reading",
|
||||
edit: "editing",
|
||||
delete: "deleting",
|
||||
move: "moving",
|
||||
search: "searching",
|
||||
execute: "running",
|
||||
fetch: "fetching",
|
||||
think: "thinking",
|
||||
};
|
||||
|
||||
/** What the turn's latest entry says the agent is doing; null before it reports anything. */
|
||||
export function activityOf(turn: readonly AgentEntry[]): Activity | null {
|
||||
const last = turn.at(-1);
|
||||
if (!last) return null;
|
||||
switch (last.type) {
|
||||
case "thought":
|
||||
return "thinking";
|
||||
case "agent":
|
||||
return "writing";
|
||||
case "tool":
|
||||
return last.status === "pending" || last.status === "running"
|
||||
? (TOOL_ACTIVITY[last.kind] ?? "working")
|
||||
: "working";
|
||||
case "subagent":
|
||||
return subagentWorking(last.status) ? "subagent" : "working";
|
||||
default:
|
||||
return "working";
|
||||
}
|
||||
}
|
||||
|
||||
/** Changes whenever the agent reports something new in the turn: an entry, more text, a tool's progress. */
|
||||
export function progressKey(turn: readonly AgentEntry[]): string {
|
||||
const last = turn.at(-1);
|
||||
const detail =
|
||||
last?.type === "agent" || last?.type === "thought"
|
||||
? last.text.length
|
||||
: last?.type === "tool"
|
||||
? `${last.status}:${last.output?.length ?? 0}`
|
||||
: last?.type === "subagent"
|
||||
? last.status
|
||||
: "";
|
||||
return `${turn.length}:${last?.type ?? ""}:${detail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of `count` playful words is the `n`th to show in the turn that started at `seed`. Each turn
|
||||
* goes through every word in an order of its own.
|
||||
*/
|
||||
export function playfulIndex(count: number, seed: number, n: number): number {
|
||||
const order = Array.from({ length: count }, (_, i) => i);
|
||||
let state = seed >>> 0;
|
||||
for (let i = order.length - 1; i > 0; i--) {
|
||||
// mulberry32
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let r = Math.imul(state ^ (state >>> 15), state | 1);
|
||||
r ^= r + Math.imul(r ^ (r >>> 7), r | 61);
|
||||
const j = ((r ^ (r >>> 14)) >>> 0) % (i + 1);
|
||||
[order[i], order[j]] = [order[j]!, order[i]!];
|
||||
}
|
||||
return order[n % count]!;
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { SettingsFormContext } from "@/workbench/contributions";
|
||||
import { useSettingsFormFor } from "@/features/settings/components/context";
|
||||
import { closeSettings, openSettings, stagedValue, useSettingsDialog } from "@/features/settings/model/staging";
|
||||
import { WORKING_STATUS_PAGE } from "./model";
|
||||
import { WorkingStatusPage as Page } from "./WorkingStatusPage";
|
||||
import { PLAYFUL_WORDS } from "./workingStatus";
|
||||
|
||||
function WorkingStatusPage() {
|
||||
const form = useSettingsFormFor(WORKING_STATUS_PAGE, "global");
|
||||
return (
|
||||
<SettingsFormContext.Provider value={form}>
|
||||
<Page />
|
||||
</SettingsFormContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const staged = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulWords");
|
||||
const words = () =>
|
||||
within(screen.getByRole("list", { name: "Playful words" }))
|
||||
.queryAllByRole("listitem")
|
||||
.map((item) => item.textContent);
|
||||
/** The page with playful words turned on, so its word controls are enabled. */
|
||||
function renderOn() {
|
||||
render(<WorkingStatusPage />);
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Playful words while the agent works" }));
|
||||
}
|
||||
|
||||
describe("Working Status settings", () => {
|
||||
beforeEach(() => openSettings(WORKING_STATUS_PAGE));
|
||||
afterEach(() => closeSettings());
|
||||
|
||||
it("is off by default, and turning it on enables the words", () => {
|
||||
render(<WorkingStatusPage />);
|
||||
const toggle = screen.getByRole("checkbox", { name: "Playful words while the agent works" });
|
||||
expect(toggle).not.toBeChecked();
|
||||
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeDisabled();
|
||||
fireEvent.click(toggle);
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "agents.playfulStatus")).toBe(true);
|
||||
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("turns the built-in words into the user's own on the first edit, and restores them", () => {
|
||||
renderOn();
|
||||
const builtIn = [...PLAYFUL_WORDS.working];
|
||||
expect(words()).toEqual(builtIn);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: `Remove ${builtIn[0]}` }));
|
||||
const input = screen.getByRole("textbox", { name: "New playful word" });
|
||||
fireEvent.change(input, { target: { value: " Reticulating splines… " } });
|
||||
// Enter adds the word and is not left to press the Settings dialog's OK.
|
||||
expect(fireEvent.keyDown(input, { key: "Enter" })).toBe(false);
|
||||
const own = [...builtIn.slice(1), "Reticulating splines…"];
|
||||
expect(words()).toEqual(own);
|
||||
expect(staged()).toEqual({ working: own });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Restore Built-in Words" }));
|
||||
expect(staged()).toEqual({});
|
||||
expect(words()).toEqual(builtIn);
|
||||
});
|
||||
|
||||
it("keeps an emptied list, which leaves the status factual", () => {
|
||||
renderOn();
|
||||
for (const word of PLAYFUL_WORDS.working) fireEvent.click(screen.getByRole("button", { name: `Remove ${word}` }));
|
||||
expect(staged()).toEqual({ working: [] });
|
||||
expect(screen.getByText("No playful words: the status stays factual")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saves the quiet time while the text is a valid number, and drops invalid text on blur", () => {
|
||||
renderOn();
|
||||
const after = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulAfterSeconds");
|
||||
const seconds = screen.getByRole("textbox", { name: "Start after the agent reports nothing new for" });
|
||||
expect(seconds).toHaveValue("0");
|
||||
fireEvent.change(seconds, { target: { value: "25" } });
|
||||
expect(after()).toBe(25);
|
||||
fireEvent.change(seconds, { target: { value: "601" } });
|
||||
expect(seconds).toHaveAttribute("aria-invalid", "true");
|
||||
expect(after()).toBe(25);
|
||||
fireEvent.blur(seconds);
|
||||
expect(seconds).toHaveValue("25");
|
||||
});
|
||||
});
|
||||
@@ -284,7 +284,7 @@ async function openCliDiff(diff: { left: string; right: string }): Promise<void>
|
||||
import("@/features/vcs/diffInput"),
|
||||
import("@/features/vcs/compareData"),
|
||||
]);
|
||||
await openVcsDiff({ ...compareFilesData(diff.left, diff.right), swappable: true });
|
||||
await openVcsDiff(compareFilesData(diff.left, diff.right));
|
||||
}
|
||||
|
||||
/** Closes the project tabs on `side` of the `arg` tab (default: the current one), keeping that tab. */
|
||||
|
||||
@@ -85,7 +85,7 @@ export function UsagesTabs() {
|
||||
id: String(t.id),
|
||||
label: label(t),
|
||||
closable: true,
|
||||
pinned: t.pinned,
|
||||
icon: t.pinned ? "pin" : undefined,
|
||||
}))}
|
||||
activeId={String(search.id)}
|
||||
onSelect={(id) => useUsages.setState({ active: Number(id) })}
|
||||
@@ -97,18 +97,16 @@ export function UsagesTabs() {
|
||||
onContextMenu={(id, e) => {
|
||||
const t = tabs.find((x) => x.id === Number(id));
|
||||
if (!t) return;
|
||||
// IDEA's content tab menu.
|
||||
showContextMenu(e, [
|
||||
{ id: "pin", label: t.pinned ? "Unpin Tab" : "Pin Tab", run: () => pinUsageTab(t.id, !t.pinned) },
|
||||
{ kind: "separator" },
|
||||
{ id: "close", label: "Close Tab", run: () => closeUsageTab(t.id) },
|
||||
{ id: "closeAll", label: "Close All Tabs", run: () => tabs.forEach((o) => closeUsageTab(o.id)) },
|
||||
{
|
||||
id: "closeOthers",
|
||||
label: "Close Other Tabs",
|
||||
disabled: tabs.length < 2,
|
||||
run: () => tabs.forEach((o) => o.id !== t.id && closeUsageTab(o.id)),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ id: "pin", label: t.pinned ? "Unpin Tab" : "Pin Tab", run: () => pinUsageTab(t.id, !t.pinned) },
|
||||
]);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -372,31 +372,6 @@ describe("run config → launch config", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("Zig under CodeLLDB: no source-language mode, so evaluation stays LLDB's own", () => {
|
||||
const exe = launchConfigFor(
|
||||
rc({ kind: "zig-application", command: "./zig-out/bin/app", debugAdapter: "codelldb" }),
|
||||
"/p",
|
||||
)!;
|
||||
expect(exe.adapter).toBe("codelldb");
|
||||
expect(extra(exe)).toEqual({ sourceLanguages: [] });
|
||||
const single = launchConfigFor(
|
||||
rc({
|
||||
kind: "native",
|
||||
command: "/tmp/openidea-run/calc-1",
|
||||
debugAdapter: "codelldb",
|
||||
params: { language: "zig" },
|
||||
}),
|
||||
"/p",
|
||||
)!;
|
||||
expect(extra(single)).toEqual({ sourceLanguages: [] });
|
||||
// Rust-compiled binaries keep CodeLLDB's default (Rust) source mode.
|
||||
const rust = launchConfigFor(
|
||||
rc({ kind: "native", command: "/tmp/openidea-run/app-1", debugAdapter: "codelldb" }),
|
||||
"/p",
|
||||
)!;
|
||||
expect(rust.extraJson).toBeNull();
|
||||
});
|
||||
|
||||
it("Godot: the editor's adapter plays the main scene or the chosen one of the project", () => {
|
||||
const project = rc({
|
||||
kind: "godot",
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
removeAllBreakpoints,
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { handleDebugEvent, pinSession, rerunSession, startPreparedSession, startSession, useDebug } from "../state";
|
||||
import { handleDebugEvent, startPreparedSession, startSession, useDebug } from "../state";
|
||||
import type { LaunchConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
@@ -237,49 +237,3 @@ it("replaces finished tabs as soon as a prepared start begins", async () => {
|
||||
await expect(started).resolves.toBe(43);
|
||||
expect(Object.keys(useDebug.getState().sessions)).toEqual(["43"]);
|
||||
});
|
||||
|
||||
it("replaces only the finished tab of the same name; other finished tabs stay", async () => {
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
await startSession({ ...config("launch"), name: "Client" });
|
||||
handleDebugEvent(1, { kind: "terminated" });
|
||||
handleDebugEvent(2, { kind: "terminated" });
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => [s.name, s.status])).toEqual([
|
||||
["Client", "terminated"],
|
||||
["Server", "running"],
|
||||
]);
|
||||
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 4 });
|
||||
const started = startPreparedSession({ id: "other", name: "Other" } as never, async () => ({
|
||||
...config("launch"),
|
||||
name: "Other",
|
||||
}));
|
||||
// No finished tab named "Other": the first finished one (Client) gives way.
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
|
||||
await started;
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
|
||||
});
|
||||
|
||||
it("keeps a pinned finished tab; Rerun on it takes its place and keeps it pinned", async () => {
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
pinSession(1, true);
|
||||
handleDebugEvent(1, { kind: "terminated" });
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 2 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
const tabs = () => Object.values(useDebug.getState().sessions).map((s) => [s.id, s.status, !!s.pinned]);
|
||||
expect(tabs()).toEqual([
|
||||
[1, "terminated", true],
|
||||
[2, "running", false],
|
||||
]);
|
||||
|
||||
handleDebugEvent(2, { kind: "terminated" });
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
await rerunSession(1);
|
||||
expect(tabs()).toEqual([
|
||||
[2, "terminated", false],
|
||||
[3, "running", true],
|
||||
]);
|
||||
});
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
useDebugRunSessions,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerDebugActions } from "./actions";
|
||||
import { registerDebugTabActions } from "./tabActions";
|
||||
import { loadBreakpoints } from "./breakpoints/store";
|
||||
import { loadExceptionBreakpoints } from "./breakpoints/exceptions";
|
||||
import { loadJsBreakpoints, watchPageSessions } from "./js/eventBreakpoints";
|
||||
@@ -73,7 +72,6 @@ export function activate(): () => void {
|
||||
const disposers = [
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
|
||||
registerDebugActions(),
|
||||
registerDebugTabActions(),
|
||||
// Remote JVM Debug, Go Remote, …: Run/Debug Configurations › Add New Configuration.
|
||||
...REMOTE_TYPES.map(registerRunConfigType),
|
||||
registerRunConfigType(jsBrowserType),
|
||||
|
||||
@@ -359,10 +359,6 @@ function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
|
||||
env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`),
|
||||
...(from && to && from !== to ? { sourceMap: [[from, to]] } : {}),
|
||||
});
|
||||
} else if (rc.kind === "zig-application" || rc.params?.language === "zig") {
|
||||
// Zig under CodeLLDB: without a source language, evaluation stays LLDB's own
|
||||
// (the default Rust mode would shape `Evaluate Expression` as Rust).
|
||||
out.extraJson = JSON.stringify({ sourceLanguages: [] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -74,8 +74,6 @@ export interface DebugSession {
|
||||
programInput?: boolean;
|
||||
/** Process the session is attached to (a Run tab's build tool); stopped with the session. */
|
||||
process: RunId | null;
|
||||
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
|
||||
pinned?: boolean;
|
||||
status: SessionStatus;
|
||||
stoppedThread: number | null;
|
||||
stopReason: string | null;
|
||||
@@ -306,30 +304,15 @@ function settleStart(id: DebugSessionId | null, discard = false) {
|
||||
for (const s of leftovers) if (isLive(useDebug.getState().sessions[s])) markTerminated(s);
|
||||
}
|
||||
|
||||
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
|
||||
let rerunOf: DebugSessionId | null = null;
|
||||
|
||||
/**
|
||||
* As IDEA reuses run content: a new session takes the place of one finished tab (with its
|
||||
* children) that isn't pinned, preferring one named like it, then the selected one; other
|
||||
* finished tabs stay. Returns whether the new tab is pinned: as the tab it replaced on a
|
||||
* rerun, else per the settings.
|
||||
*/
|
||||
function replaceFinished(name: string): boolean | undefined {
|
||||
const { sessions, active } = useDebug.getState();
|
||||
const own = rerunOf != null ? sessions[rerunOf] : undefined;
|
||||
rerunOf = null;
|
||||
if (own && !isLive(own)) {
|
||||
removeSession(own.id);
|
||||
return own.pinned;
|
||||
}
|
||||
const finished = Object.values(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
|
||||
const selected = active != null ? sessions[active] : undefined;
|
||||
const ordered =
|
||||
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
|
||||
const reused = ordered.find((s) => s.name === name) ?? ordered[0];
|
||||
if (reused) removeSession(reused.id);
|
||||
return workflowSettings().run.pinTabs || undefined;
|
||||
/** Drops finished sessions; running ones stay (multiple concurrent sessions are fine). */
|
||||
function dropFinished() {
|
||||
useDebug.setState((s) => {
|
||||
const sessions = Object.fromEntries(Object.entries(s.sessions).filter(([, v]) => isLive(v)));
|
||||
const consoleLines = Object.fromEntries(Object.entries(s.console).filter(([k]) => sessions[+k]));
|
||||
for (const id of ansiStreams.keys()) if (!sessions[id]) ansiStreams.delete(id);
|
||||
return { sessions, console: consoleLines, active: s.active != null && sessions[s.active] ? s.active : null };
|
||||
});
|
||||
publishContext();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -687,17 +670,12 @@ export async function startPreparedSession(
|
||||
const id = --preparationSeq as DebugSessionId;
|
||||
const controller = new AbortController();
|
||||
preparations.set(id, controller);
|
||||
// The new tab takes the place of a finished one while its build runs, not once the adapter starts.
|
||||
const pinned = replaceFinished(config.name);
|
||||
// The new tab takes the place of finished ones while its build runs, not once the adapter starts.
|
||||
dropFinished();
|
||||
useDebug.setState((s) => ({
|
||||
sessions: {
|
||||
...s.sessions,
|
||||
[id]: blank(id, {
|
||||
name: config.name,
|
||||
adapter: config.debugAdapter ?? "",
|
||||
runConfig: config,
|
||||
pinned,
|
||||
}),
|
||||
[id]: blank(id, { name: config.name, adapter: config.debugAdapter ?? "", runConfig: config }),
|
||||
},
|
||||
console: { ...s.console, [id]: [] },
|
||||
active: id,
|
||||
@@ -750,7 +728,7 @@ export async function startSession(
|
||||
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
|
||||
const afterDetach = justDetached(options.process);
|
||||
const previousActive = useDebug.getState().active;
|
||||
let pinned = !afterDetach && !options.preparation ? replaceFinished(launch.name) : undefined;
|
||||
if (!afterDetach) dropFinished();
|
||||
try {
|
||||
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
|
||||
} catch {
|
||||
@@ -765,7 +743,7 @@ export async function startSession(
|
||||
const id = await call(commands.debugStart(launch));
|
||||
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
|
||||
owned.add(id);
|
||||
if (afterDetach && !options.preparation) pinned = replaceFinished(launch.name);
|
||||
if (afterDetach) dropFinished();
|
||||
if (options.preparation?.signal.aborted) {
|
||||
await call(commands.debugStop(id)).catch(() => undefined);
|
||||
settleStart(id);
|
||||
@@ -797,7 +775,6 @@ export async function startSession(
|
||||
adapter: cur.adapter || launch.adapter,
|
||||
launch: options.rerunnable === false ? null : launch,
|
||||
process: options.process ?? null,
|
||||
pinned: preparation ? preparation.pinned : pinned,
|
||||
status: cur.status === "starting" ? "running" : cur.status,
|
||||
},
|
||||
},
|
||||
@@ -914,11 +891,6 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Pins or unpins a session's tab. */
|
||||
export function pinSession(id: DebugSessionId, pinned: boolean) {
|
||||
patch(id, { pinned });
|
||||
}
|
||||
|
||||
/** Forgets a session and its children; a selected one passes the selection to the tab on its left. */
|
||||
export function removeSession(id: DebugSessionId) {
|
||||
const st = useDebug.getState();
|
||||
@@ -946,7 +918,6 @@ export function removeSession(id: DebugSessionId) {
|
||||
});
|
||||
for (const goneId of gone) {
|
||||
owned.delete(goneId);
|
||||
ansiStreams.delete(goneId);
|
||||
unfollowProcessOutput(goneId);
|
||||
}
|
||||
updateExecutionPoint();
|
||||
@@ -957,20 +928,18 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
|
||||
const s = useDebug.getState().sessions[id];
|
||||
if (!s) return;
|
||||
const root = rootOf(s);
|
||||
const launch = root.launch;
|
||||
if (!root.runConfig && !launch) return;
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
rerunOf = root.id;
|
||||
try {
|
||||
if (root.runConfig)
|
||||
await executeAction(
|
||||
"run.debugConfig",
|
||||
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
|
||||
);
|
||||
else await startSession(launch!, { show: options.show });
|
||||
} finally {
|
||||
rerunOf = null;
|
||||
if (root.runConfig) {
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
await executeAction(
|
||||
"run.debugConfig",
|
||||
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const launch = root.launch;
|
||||
if (!launch) return;
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
await startSession(launch, { show: options.show });
|
||||
}
|
||||
|
||||
async function loadCapabilities(id: DebugSessionId) {
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { registerActions, type ActionContext } from "@/platform/actions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import type { DebugSessionId } from "@/platform/ipc";
|
||||
import { closeSessionTab, pinSession, useDebug } from "./state";
|
||||
import { sessionTabs } from "./ui/sessionTabs";
|
||||
|
||||
/** The sessions the Debug tabs close: each tab's owner, in tab order. */
|
||||
function owners(): DebugSessionId[] {
|
||||
return [...new Set(sessionTabs(Object.values(useDebug.getState().sessions)).map((t) => t.owner))];
|
||||
}
|
||||
|
||||
/** The tab owner an action is for: its argument, else the selected tab's. */
|
||||
function target({ arg }: ActionContext): DebugSessionId | null {
|
||||
const { sessions, active } = useDebug.getState();
|
||||
const id = typeof arg === "number" ? arg : active;
|
||||
if (id == null || !sessions[id]) return null;
|
||||
return sessionTabs(Object.values(sessions)).find((t) => t.session.id === id || t.owner === id)?.owner ?? null;
|
||||
}
|
||||
|
||||
/** `id` and the sessions it runs under: closing one of those would close `id` too. */
|
||||
function lineage(id: DebugSessionId): Set<DebugSessionId> {
|
||||
const { sessions } = useDebug.getState();
|
||||
const out = new Set<DebugSessionId>();
|
||||
for (let cur = sessions[id]; cur && !out.has(cur.id); cur = cur.parent != null ? sessions[cur.parent] : undefined)
|
||||
out.add(cur.id);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Closes the tabs one after another; a running session the user keeps stops the rest. */
|
||||
async function closeTabs(ids: readonly DebugSessionId[]) {
|
||||
for (const id of ids) if (useDebug.getState().sessions[id] && !(await closeSessionTab(id))) return;
|
||||
}
|
||||
|
||||
/** A pinnable tab: a user-started session's (a child's tab goes with its parent). */
|
||||
function pinnable(id: DebugSessionId | null) {
|
||||
const s = id != null ? useDebug.getState().sessions[id] : undefined;
|
||||
return s && s.parent == null ? s : undefined;
|
||||
}
|
||||
|
||||
export function registerDebugTabActions(): () => void {
|
||||
return registerActions([
|
||||
{
|
||||
id: "debug.closeTab",
|
||||
title: "Close Tab",
|
||||
category: "Debug",
|
||||
enabled: (c) => target(c) !== null,
|
||||
run: (c) => void closeSessionTab(target(c)!),
|
||||
},
|
||||
{
|
||||
id: "debug.closeOtherTabs",
|
||||
title: "Close Other Tabs",
|
||||
category: "Debug",
|
||||
enabled: (c) => target(c) !== null && owners().length > 1,
|
||||
run: async (c) => {
|
||||
const keep = lineage(target(c)!);
|
||||
await closeTabs(owners().filter((id) => !keep.has(id)));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "debug.closeAllTabs",
|
||||
title: "Close All Tabs",
|
||||
category: "Debug",
|
||||
enabled: () => owners().length > 0,
|
||||
run: () => closeTabs(owners()),
|
||||
},
|
||||
{
|
||||
id: "debug.pinTab",
|
||||
title: "Pin / Unpin Tab",
|
||||
category: "Debug",
|
||||
icon: "pin",
|
||||
enabled: (c) => !!pinnable(target(c)),
|
||||
run: (c) => {
|
||||
const s = pinnable(target(c));
|
||||
if (s) pinSession(s.id, !s.pinned);
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/** The context menu of a Debug tab (IDEA's content tab menu); `owner` is the session the tab stands for. */
|
||||
export function debugTabMenu(owner: DebugSessionId): MenuItem[] {
|
||||
const s = pinnable(owner);
|
||||
return [
|
||||
{ kind: "action", action: "debug.closeTab", arg: owner },
|
||||
{ kind: "action", action: "debug.closeAllTabs", arg: owner },
|
||||
{ kind: "action", action: "debug.closeOtherTabs", arg: owner },
|
||||
...(s
|
||||
? ([
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "debug.pinTab", arg: owner, label: s.pinned ? "Unpin Tab" : "Pin Tab" },
|
||||
] satisfies MenuItem[])
|
||||
: []),
|
||||
];
|
||||
}
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
} from "../state";
|
||||
import { remoteWaitingNote } from "../remote";
|
||||
import { sessionTabs } from "./sessionTabs";
|
||||
import { debugTabMenu } from "../tabActions";
|
||||
import { stopNote } from "../js/eventBreakpoints";
|
||||
import { NetworkView } from "../js/NetworkView";
|
||||
import { liveWatchesApply, useLiveWatches } from "../js/liveWatches";
|
||||
@@ -139,15 +138,13 @@ export function DebugTabs() {
|
||||
const list = Object.values(sessions);
|
||||
if (!list.length) return null;
|
||||
const tabs = sessionTabs(list);
|
||||
const ownerOf = (id: string) => tabs.find((t) => t.session.id === +id)?.owner ?? +id;
|
||||
const items: TabItem[] = tabs.map(({ session: s, child, owner }) => ({
|
||||
const items: TabItem[] = tabs.map(({ session: s, child }) => ({
|
||||
id: String(s.id),
|
||||
label: child ? tx`${s.name} (child)` : s.name,
|
||||
text: s.name,
|
||||
icon: "debug",
|
||||
italic: s.status === "terminated",
|
||||
closable: true,
|
||||
pinned: !child && !!sessions[owner]?.pinned,
|
||||
tooltip: statusText(s),
|
||||
}));
|
||||
// A browser launch's own session has no tab: its page's tab stands for it.
|
||||
@@ -160,12 +157,7 @@ export function DebugTabs() {
|
||||
items={items}
|
||||
activeId={shown ? String(shown.session.id) : null}
|
||||
onSelect={(id) => selectSession(+id)}
|
||||
onClose={(id) => void closeSessionTab(ownerOf(id))}
|
||||
onTogglePin={(id) => void executeAction("debug.pinTab", ownerOf(id))}
|
||||
onContextMenu={(id, e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(e, debugTabMenu(ownerOf(id)), { owner: e.currentTarget });
|
||||
}}
|
||||
onClose={(id) => void closeSessionTab(tabs.find((t) => t.session.id === +id)?.owner ?? +id)}
|
||||
panelIdPrefix="openidea-debug"
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
font-size: var(--fs-small, var(--fs-ui));
|
||||
}
|
||||
|
||||
.button:hover,
|
||||
.button.text:hover,
|
||||
.button[aria-expanded="true"] {
|
||||
background-color: var(--bg-toolbar-hover);
|
||||
}
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
* External Libraries: the project's SDK / library source folders (the Python
|
||||
* interpreter's standard library and site-packages, the JDK, node_modules
|
||||
* packages, Cargo crates and the Rust standard library, GOROOT and Go modules,
|
||||
* the Zig standard library and its fetched build.zig.zon packages, Maven /
|
||||
* Gradle dependency jars) as a Project view root. Their files open read-only,
|
||||
* like IDEA's library sources. Archives (the JDK's `src.zip`, jars, Zig
|
||||
* package tarballs) are browsed through the backend's `<archive>!/<entry>` paths.
|
||||
* Maven / Gradle dependency jars) as a Project view root. Their files open
|
||||
* read-only, like IDEA's library sources. Archives (the JDK's `src.zip`, jars)
|
||||
* are browsed through the backend's `<archive>!/<entry>` paths.
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { commands, type LibraryGroup, type RequestId } from "@/bindings";
|
||||
@@ -33,12 +32,10 @@ const GROUP_ICONS: Record<string, string> = {
|
||||
classpath: "file-java",
|
||||
ruby: "file-ruby",
|
||||
gems: "file-ruby",
|
||||
zig: "file-zig",
|
||||
zigPackages: "file-zig",
|
||||
};
|
||||
|
||||
/** SDK groups, which IDEA writes in angle brackets (`< 21 >`); library groups (`Maven: g:a:v`) go without. */
|
||||
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust", "zig"]);
|
||||
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust"]);
|
||||
|
||||
/** An archive's root (`/jdk/lib/src.zip!`): its entries live below `<archive>!/`. */
|
||||
const isArchiveRoot = (path: string) => path.endsWith("!");
|
||||
@@ -65,7 +62,6 @@ const MANIFESTS = new Set([
|
||||
"go.mod",
|
||||
"go.sum",
|
||||
"go.work",
|
||||
"build.zig.zon",
|
||||
".classpath",
|
||||
"pyproject.toml",
|
||||
"setup.py",
|
||||
@@ -133,7 +129,6 @@ const sdkKey = (s: ReturnType<typeof useProject.getState>) => {
|
||||
l?.go?.goroot,
|
||||
l?.go?.gopath,
|
||||
l?.go?.modules,
|
||||
l?.zig?.zig,
|
||||
s.settings?.projectStructure?.libraries,
|
||||
s.settings?.projectStructure?.sourceRoots,
|
||||
]);
|
||||
|
||||
@@ -29,24 +29,13 @@ describe("External Libraries", () => {
|
||||
|
||||
it("gives each ecosystem's groups their icon", () => {
|
||||
const root = librariesRoot(
|
||||
[
|
||||
"jdk",
|
||||
"nodeCore",
|
||||
"nodeModules",
|
||||
"rust",
|
||||
"cargo",
|
||||
"go",
|
||||
"goModules",
|
||||
"maven",
|
||||
"gradle",
|
||||
"zig",
|
||||
"zigPackages",
|
||||
"other",
|
||||
].map((kind) => ({
|
||||
name: kind,
|
||||
kind,
|
||||
roots: [{ name: "r", path: `/libs/${kind}` }],
|
||||
})),
|
||||
["jdk", "nodeCore", "nodeModules", "rust", "cargo", "go", "goModules", "maven", "gradle", "other"].map(
|
||||
(kind) => ({
|
||||
name: kind,
|
||||
kind,
|
||||
roots: [{ name: "r", path: `/libs/${kind}` }],
|
||||
}),
|
||||
),
|
||||
)!;
|
||||
expect(Object.fromEntries(root.children!.map((g) => [g.label, g.icon]))).toEqual({
|
||||
"< jdk >": "file-java",
|
||||
@@ -58,8 +47,6 @@ describe("External Libraries", () => {
|
||||
goModules: "file-gomod",
|
||||
maven: "maven-project",
|
||||
gradle: "file-gradle",
|
||||
"< zig >": "file-zig",
|
||||
zigPackages: "file-zig",
|
||||
other: "library",
|
||||
});
|
||||
});
|
||||
@@ -76,22 +63,18 @@ describe("External Libraries", () => {
|
||||
group("Go SDK 1.27.4", "go"),
|
||||
group("Maven: com.acme:core:2.1.27", "maven"),
|
||||
group("Node.js Core", "nodeCore"),
|
||||
group("Zig 0.16.0", "zig"),
|
||||
group("Zig packages", "zigPackages"),
|
||||
];
|
||||
const labels = (groups: typeof detected) => librariesRoot(groups)!.children!.map((g) => g.label);
|
||||
expect(labels(detected)).toEqual([
|
||||
"< Go SDK 1.27.4 >",
|
||||
"< Python 3.14 >",
|
||||
"< temurin-21 >",
|
||||
"< Zig 0.16.0 >",
|
||||
"Cargo dependencies",
|
||||
"Gradle: com.acme:lib:1.0",
|
||||
"Maven: com.acme:core:2.1.27",
|
||||
"Maven: org.junit:junit:4.13",
|
||||
"node_modules",
|
||||
"Node.js Core",
|
||||
"Zig packages",
|
||||
]);
|
||||
expect(labels([...detected].reverse())).toEqual(labels(detected));
|
||||
});
|
||||
@@ -121,7 +104,6 @@ describe("External Libraries", () => {
|
||||
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
|
||||
expect(touchesManifest(["/p/.venv/pyvenv.cfg"])).toBe(true);
|
||||
expect(touchesManifest(["/p/pnpm-workspace.yaml", "/p/Gemfile.lock"])).toBe(true);
|
||||
expect(touchesManifest(["/p/build.zig.zon", "/p/go.work"])).toBe(true);
|
||||
expect(touchesManifest(["/p/node_modules/react/package.json"])).toBe(false);
|
||||
expect(touchesManifest(["/p/src/package.json.bak", "/p/README.md"])).toBe(false);
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
|
||||
import { bracketMatching, indentOnInput, syntaxHighlighting } from "@codemirror/language";
|
||||
import type { NotebookCellDoc } from "@/bindings";
|
||||
import { cellEditorExtensions, embeddedEditorExtensions } from "@/editor/api";
|
||||
import { cellEditorExtensions } from "@/editor/api";
|
||||
import { openideaTheme } from "@/editor/core/cm/theme";
|
||||
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
|
||||
import { selectionMarks } from "@/editor/core/cm/selectionMarks";
|
||||
@@ -97,7 +97,6 @@ export function CellEditor({
|
||||
]),
|
||||
),
|
||||
keymap.of([indentWithTab, ...defaultKeymap]),
|
||||
embeddedEditorExtensions(session.path),
|
||||
language.of([]),
|
||||
services.current.of(languageServices(type, initialDoc.current)),
|
||||
readonly.current.of(EditorState.readOnly.of(session.getState().frozen)),
|
||||
|
||||
@@ -2,19 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import type { RunTargetValid } from "@/platform/remoteSettings";
|
||||
import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Menu,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Tabs,
|
||||
type TabItem,
|
||||
T,
|
||||
showContextMenu,
|
||||
} from "@/ui";
|
||||
import { EmptyState, Icon, IconButton, Menu, SplitGroup, SplitHandle, SplitPanel, Tabs, type TabItem, T } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
|
||||
import { ConsoleModel } from "./console";
|
||||
@@ -27,6 +15,7 @@ import {
|
||||
baseConfigOf,
|
||||
canRunSelectedTests,
|
||||
clearConsole,
|
||||
closeSessionTab,
|
||||
closeStdin,
|
||||
debugSession,
|
||||
failedTests,
|
||||
@@ -42,13 +31,11 @@ import {
|
||||
writeTerminal,
|
||||
type RunSession,
|
||||
isLive,
|
||||
pinSession,
|
||||
} from "./store";
|
||||
import { rerunFailedConfigs } from "./testing/rerun";
|
||||
import { nodeOutput } from "./testing";
|
||||
import { TestTreeView, formatDuration } from "./TestTreeView";
|
||||
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
|
||||
import { closeRunTab, runTabMenu } from "./runTabs";
|
||||
import { StackTracePanel, closeStackTrace, useStackTraces, type StackTraceTab } from "./stackTrace";
|
||||
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
|
||||
import { isUpdatable } from "./updatePolicies";
|
||||
import { configIcon } from "./configs";
|
||||
@@ -56,6 +43,7 @@ import { agentName } from "./agentConfig";
|
||||
import { archivedAgentSessions, closeAgentArchive } from "./agentRuns";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { toolWindowService } from "@/workbench/contributions";
|
||||
|
||||
function failed(s: RunSession): boolean {
|
||||
return s.status === "failed" || (s.status === "finished" && s.exitCode !== 0 && !s.stopped);
|
||||
@@ -290,7 +278,6 @@ function sessionItems(sessions: readonly RunSession[], targets: readonly RunTarg
|
||||
// An agent's command that ended, however it ended.
|
||||
dimmed: agentName(s.config) !== null && !isLive(s),
|
||||
closable: true,
|
||||
pinned: s.pinned,
|
||||
tooltip:
|
||||
s.status === "finished"
|
||||
? tx`Finished in ${formatDuration((s.endedAt ?? s.startedAt) - s.startedAt)}, exit code ${s.exitCode ?? "?"}`
|
||||
@@ -312,6 +299,14 @@ function currentTab(
|
||||
return traces.length ? { trace: traces[traces.length - 1]! } : null;
|
||||
}
|
||||
|
||||
/** Closes a session or stack trace tab; as in IDEA, the tool window goes away with its last tab. */
|
||||
export async function closeRunTab(id: string, traces: readonly StackTraceTab[]) {
|
||||
if (traces.some((t) => t.id === id)) closeStackTrace(id);
|
||||
else if (!(await closeSessionTab(id))) return;
|
||||
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length)
|
||||
toolWindowService().hide("run", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
/** Session (and stack trace) tabs in the tool window header. */
|
||||
export function RunTabs() {
|
||||
const sessions = useRun((s) => s.sessions);
|
||||
@@ -336,15 +331,7 @@ export function RunTabs() {
|
||||
items={items}
|
||||
activeId={activeId}
|
||||
onSelect={(id) => useRun.setState({ activeSession: id })}
|
||||
onClose={(id) => void closeRunTab(id)}
|
||||
onTogglePin={(id) => {
|
||||
const s = sessions.find((x) => x.id === id);
|
||||
if (s) pinSession(s.id, !s.pinned);
|
||||
}}
|
||||
onContextMenu={(id, e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(e, runTabMenu(id), { owner: e.currentTarget });
|
||||
}}
|
||||
onClose={(id) => void closeRunTab(id, traces)}
|
||||
panelIdPrefix="openidea-run"
|
||||
trailing={archived.length > 0 && <AgentArchive sessions={archived} activeId={activeId} />}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
|
||||
import { closeRunTab } from "./runTabs";
|
||||
import { closeRunTab } from "./RunView";
|
||||
import { useStackTraces } from "./stackTrace";
|
||||
import { useRun, type RunSession } from "./store";
|
||||
|
||||
@@ -20,9 +20,9 @@ it("hides the Run tool window once its last tab is closed", async () => {
|
||||
provideToolWindowService({ hide } as unknown as ToolWindowService);
|
||||
useRun.setState({ sessions: [finished("a"), finished("b")] });
|
||||
useStackTraces.setState({ tabs: [{ id: "t", title: "Trace", text: "" } as never] });
|
||||
await closeRunTab("a");
|
||||
await closeRunTab("t");
|
||||
await closeRunTab("a", useStackTraces.getState().tabs);
|
||||
await closeRunTab("t", useStackTraces.getState().tabs);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
await closeRunTab("b");
|
||||
await closeRunTab("b", useStackTraces.getState().tabs);
|
||||
expect(hide).toHaveBeenCalledWith("run", { removeFromStripe: true });
|
||||
});
|
||||
@@ -1,36 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
|
||||
import { canDebugProduced, choiceItems, contextMenuItems } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContextChoices } from "./producers";
|
||||
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
|
||||
import { useRun } from "./store";
|
||||
import type { RunTarget } from "./targets";
|
||||
import { TestResults } from "./testing";
|
||||
import { clearTestStates, recordTestStates } from "./testing/states";
|
||||
import { setInvokeRoute } from "@/platform/tauriCore";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tauri: { value: false },
|
||||
read: { value: null as string | null },
|
||||
toolEnv: { value: null as ((...args: unknown[]) => unknown) | null },
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => mocks.tauri.value };
|
||||
});
|
||||
|
||||
vi.mock("./runtimes", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./runtimes")>();
|
||||
return {
|
||||
...actual,
|
||||
toolEnv: (...args: Parameters<typeof actual.toolEnv>) =>
|
||||
mocks.toolEnv.value ? mocks.toolEnv.value(...args) : actual.toolEnv(...args),
|
||||
};
|
||||
});
|
||||
|
||||
const ROOT = "/work/app";
|
||||
const SCRATCHES = "/Users/me/scratches";
|
||||
@@ -224,23 +203,6 @@ describe("run gutter popup", () => {
|
||||
describe("Debug entry", () => {
|
||||
const config = (c: Partial<RunConfig>) =>
|
||||
({ id: "c", name: "c", command: "", args: [], cwd: "", env: {}, ...c }) as RunConfig;
|
||||
const MAIN_ZIG = [
|
||||
'const std = @import("std");',
|
||||
"pub fn main() !void {",
|
||||
' std.debug.print("hi\\n", .{});',
|
||||
"}",
|
||||
].join("\n");
|
||||
const CALC_ZIG = [
|
||||
'const std = @import("std");',
|
||||
'test "adds two numbers" {',
|
||||
" try std.testing.expect(true);",
|
||||
"}",
|
||||
].join("\n");
|
||||
const zigEnv: ToolEnv = {
|
||||
tool: (n) => (n === "zig" ? { path: "/bin/zig", version: "0.17.1" } : null),
|
||||
compileDir: "/tmp/openidea-run",
|
||||
};
|
||||
|
||||
it("is offered for Maven and Gradle tests, which run with a JDWP agent", () => {
|
||||
const mavenTest = config({ kind: "maven", command: "mvn", args: ["test", "-Dtest=A#b"], isTest: true });
|
||||
expect(canDebugProduced({ name: "A.b", scope: "element", config: mavenTest })).toBe(true);
|
||||
@@ -255,70 +217,6 @@ describe("Debug entry", () => {
|
||||
canDebugProduced({ name: "lint", scope: "file", config: config({ kind: "npm", args: ["run", "lint"] }) }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
|
||||
useRun.setState({ configs: [], loaded: true });
|
||||
mocks.tauri.value = true;
|
||||
mocks.toolEnv.value = () => zigEnv;
|
||||
// Bindings' `typedError` wraps the raw invoke result: `fs_read_text` resolves to its text.
|
||||
setInvokeRoute((cmd) =>
|
||||
cmd === "fs_read_text" ? Promise.resolve(mocks.read.value) : Promise.reject(new Error("not stubbed")),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
mocks.tauri.value = false;
|
||||
mocks.read.value = null;
|
||||
mocks.toolEnv.value = null;
|
||||
setInvokeRoute(null);
|
||||
useProject.setState({ project: null });
|
||||
useRun.setState({ configs: [], loaded: false });
|
||||
});
|
||||
|
||||
it("re-debug of a saved zig file config rebuilds the build-then-debug plan", async () => {
|
||||
mocks.read.value = MAIN_ZIG;
|
||||
const saved = config({
|
||||
id: "context:file:src/main.zig",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["run", "src/main.zig"],
|
||||
cwd: null,
|
||||
});
|
||||
const plan = await compiledDebugPlan(saved);
|
||||
expect(plan?.debug).toBeTruthy();
|
||||
expect(plan!.debug!.build.command).toMatch(
|
||||
/zig build-exe src\/main\.zig -femit-bin=\/tmp\/openidea-run\/main-\w+$/,
|
||||
);
|
||||
expect(plan!.debug!.config).toMatchObject({
|
||||
kind: "native",
|
||||
debugAdapter: "codelldb",
|
||||
params: { language: "zig" },
|
||||
});
|
||||
});
|
||||
|
||||
it("re-debug of a saved zig test config re-targets its test", async () => {
|
||||
mocks.read.value = CALC_ZIG;
|
||||
const saved = config({
|
||||
id: "context:file:src/calc.zig#adds two numbers",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["test", "src/calc.zig", "--test-filter", "adds two numbers"],
|
||||
cwd: null,
|
||||
});
|
||||
const plan = await compiledDebugPlan(saved);
|
||||
expect(plan?.debug).toBeTruthy();
|
||||
expect(plan!.debug!.build.command).toMatch(
|
||||
/zig test src\/calc\.zig --test-filter 'adds two numbers' --test-no-exec/,
|
||||
);
|
||||
expect(plan!.debug!.config.args).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves other configurations alone", async () => {
|
||||
expect(await compiledDebugPlan(config({ id: "c", kind: "shell", command: "make" }))).toBeNull();
|
||||
expect(
|
||||
await compiledDebugPlan(config({ id: "user:x", kind: "zig", command: "zig", args: ["run", "x.zig"], cwd: null })),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Run with Fuzzing", () => {
|
||||
|
||||
@@ -197,9 +197,9 @@ export async function compiledDebugPlan(config: RunConfig): Promise<Produced | n
|
||||
const input: ContextInput = { ...projectContext(), root, path, content };
|
||||
const env = await toolEnv(neededTools(input), path, root, false);
|
||||
if (m[2]) {
|
||||
// A test: find the target by name again (targets and the id carry the unescaped name).
|
||||
// A test: find the target by name again.
|
||||
if (config.kind === "zig") {
|
||||
const test = zigTargets(content ?? "").find((t) => t.name === m[2]);
|
||||
const test = zigTargets(content ?? "").find((t) => t.name.replace(/\\(.)/g, "$1") === m[2]);
|
||||
return test ? produceContext({ ...input, line: test.line }, env) : null;
|
||||
}
|
||||
const lines = (content ?? "").split("\n");
|
||||
@@ -365,7 +365,7 @@ function peekContent(path: string): string | undefined {
|
||||
/** Whether the file's runnability depends on its text (`package main`, `fn main`, `#!`…). */
|
||||
function needsContent(path: string): boolean {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
return /\.(go|rs|java|kt|c|cpp|cc|cxx|zig)$/.test(name) || !name.includes(".");
|
||||
return /\.(go|rs|java|kt|c|cpp|cc|cxx)$/.test(name) || !name.includes(".");
|
||||
}
|
||||
|
||||
export async function prepareMenu(_menu: ContextMenuId, ctx: MenuGroupContext): Promise<void> {
|
||||
|
||||
@@ -43,7 +43,6 @@ import { registerExternalTools } from "./externalTools";
|
||||
import { openImport } from "./importConfigs";
|
||||
import { registerComposerInstall } from "./composerInstall";
|
||||
import { registerGoActions } from "./goActions";
|
||||
import { registerRunTabActions } from "./runTabs";
|
||||
import { invalidateGoModules } from "./goModules";
|
||||
import { invalidatePythonPackages } from "./pythonPackages";
|
||||
import { RunWidget } from "./RunWidget";
|
||||
@@ -186,7 +185,7 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
return;
|
||||
}
|
||||
// A single compiled file (rustc / clang / zig): build with debug info, then debug the binary.
|
||||
// A single compiled file (rustc / clang): build with debug info, then debug the binary.
|
||||
const compiled = await compiledDebugPlan(config);
|
||||
if (compiled?.debug) {
|
||||
await launchProduced(compiled, true, show);
|
||||
@@ -404,7 +403,6 @@ export function activate(): () => void {
|
||||
registerBuiltinTypes(),
|
||||
registerRunConfigType(junitType),
|
||||
registerGoActions(),
|
||||
registerRunTabActions(),
|
||||
registerComposerInstall(),
|
||||
registerOverlay({ id: "run.chooser", component: ConfigChooserOverlay }),
|
||||
registerOverlay({
|
||||
|
||||
@@ -424,12 +424,7 @@ describe("single-file producers (scratches)", () => {
|
||||
expect(main.debug!.build.command).toMatch(
|
||||
/^mkdir -p \/tmp\/openidea-run && \/bin\/zig build-exe calc\.zig -femit-bin=\/tmp\/openidea-run\/calc-\w+$/,
|
||||
);
|
||||
expect(main.debug!.config).toMatchObject({
|
||||
kind: "native",
|
||||
debugAdapter: "codelldb",
|
||||
args: [],
|
||||
params: { language: "zig" },
|
||||
});
|
||||
expect(main.debug!.config).toMatchObject({ kind: "native", debugAdapter: "codelldb", args: [] });
|
||||
|
||||
const test = produceContext(scratch("calc.zig", src, 3), e)!;
|
||||
expect(test).toMatchObject({ name: "adds two numbers", scope: "element" });
|
||||
|
||||
@@ -660,15 +660,7 @@ function zigFile(input: ContextInput, env: ToolEnv, s: FileSite, test?: { name:
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
const binary: RunConfig = {
|
||||
...config,
|
||||
kind: "native",
|
||||
command: out,
|
||||
args: [],
|
||||
isTest: false,
|
||||
// Marks the debugged program as Zig: CodeLLDB's source mode stays off (see nativeLaunch).
|
||||
params: { language: "zig" },
|
||||
};
|
||||
const binary: RunConfig = { ...config, kind: "native", command: out, args: [], isTest: false };
|
||||
return { name, scope, config, debug: { build: buildConfig, config: binary } };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
runStart: vi.fn(async () => ({ status: "ok", data: 1 })),
|
||||
runStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: ((m: unknown) => void) | null = null;
|
||||
},
|
||||
}));
|
||||
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
provideNotificationService,
|
||||
provideToolWindowService,
|
||||
type ToolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import { resetRuns, startRun, useRun, type RunSession } from "./store";
|
||||
|
||||
const config = (id: string): RunConfig =>
|
||||
({ id, name: id, kind: "shell", command: "true", args: [], cwd: null, env: {} }) as unknown as RunConfig;
|
||||
const finished = (id: string, extra: Partial<RunSession> = {}): RunSession =>
|
||||
({
|
||||
id,
|
||||
config: config(id),
|
||||
runId: null,
|
||||
status: "finished",
|
||||
exitCode: 0,
|
||||
startedAt: 0,
|
||||
endedAt: 1,
|
||||
...extra,
|
||||
}) as RunSession;
|
||||
const tabs = () => useRun.getState().sessions.map((s) => `${s.id}:${s.config.id}${s.pinned ? "*" : ""}`);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useProject.setState({ settings: null });
|
||||
provideNotificationService({ notify: vi.fn() });
|
||||
provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService);
|
||||
});
|
||||
afterEach(() => resetRuns());
|
||||
|
||||
it("takes the place of the same configuration's finished tab, then the selected one, never a pinned one", async () => {
|
||||
useRun.setState({ sessions: [finished("a"), finished("b"), finished("c", { pinned: true })], activeSession: "b" });
|
||||
await startRun(config("a"), undefined, undefined, { prepared: true });
|
||||
expect(tabs()).toEqual(["a:a", "b:b", "c:c*"]);
|
||||
useRun.setState({ activeSession: "b" });
|
||||
await startRun(config("x"), undefined, undefined, { prepared: true });
|
||||
expect(tabs()).toEqual(["a:a", "b:x", "c:c*"]);
|
||||
});
|
||||
|
||||
it("opens a new tab when every finished tab is pinned, pinned when the setting asks", async () => {
|
||||
useProject.setState({ settings: { run: { pinTabs: true } } as never });
|
||||
useRun.setState({ sessions: [finished("a", { pinned: true })], activeSession: "a" });
|
||||
await startRun(config("a"), undefined, undefined, { prepared: true });
|
||||
expect(tabs()).toEqual(["a:a*", expect.stringMatching(/^run\d+:a\*$/)]);
|
||||
});
|
||||
|
||||
it("keeps an agent's commands out of other tabs", async () => {
|
||||
const agent = { ...config("agent:build"), params: { "mcp.agentRun": "build" } } as RunConfig;
|
||||
useRun.setState({ sessions: [finished("a")], activeSession: "a" });
|
||||
await startRun(agent, undefined, undefined, { prepared: true });
|
||||
expect(useRun.getState().sessions).toHaveLength(2);
|
||||
});
|
||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача