дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-18 15:46:14 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
74ed942f9c |
No files matched your search
@@ -42,7 +42,6 @@ Visual style: dark, low-contrast greys, one cool accent
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
|
||||
Створено
@@ -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>
|
||||
@@ -1861,24 +1861,12 @@ impl Task {
|
||||
let s = self.state.lock();
|
||||
s.busy && s.task.status == AgentStatus::Running
|
||||
};
|
||||
let Some((live, method)) = live
|
||||
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
|
||||
.and_then(|l| steer_method(&l.init).map(|m| (l, m)))
|
||||
else {
|
||||
let Some(live) = live.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images)) else {
|
||||
return Err(prompt);
|
||||
};
|
||||
let content = self.content(&live, &prompt).await;
|
||||
let sent: Result<Value, RpcError> =
|
||||
live.peer.request(method, json!({ "sessionId": live.session, "prompt": content }), None).await;
|
||||
// `_session/steering` answers with an outcome: only `injected` joined the turn
|
||||
// (`promptRequired`: no turn is running any more).
|
||||
let sent = match sent {
|
||||
Ok(reply) => match reply.get("outcome").and_then(Value::as_str) {
|
||||
None | Some("injected") => Ok(()),
|
||||
Some(outcome) => Err(reply.get("reason").and_then(Value::as_str).unwrap_or(outcome).to_owned()),
|
||||
},
|
||||
Err(e) => Err(e.to_string()),
|
||||
};
|
||||
live.peer.request("_openidea/steer", json!({ "sessionId": live.session, "prompt": content }), None).await;
|
||||
if let Err(e) = sent {
|
||||
// The turn ended meanwhile: the message waits for the next one instead.
|
||||
tracing::debug!("agent task {}: steering failed: {e}", self.id);
|
||||
@@ -2877,27 +2865,13 @@ fn shown_background(tasks: &[Value], known: &[AgentBackgroundTask]) -> Vec<Agent
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The method that adds a message to the running turn: OpenIDEA's own, or the
|
||||
/// `_session/steering` extension an agent advertises in the response's top-level `_meta`
|
||||
/// (OMP).
|
||||
fn steer_method(init: &acp::Negotiated) -> Option<&'static str> {
|
||||
let supported = |v: Option<&Value>| v.and_then(Value::as_bool) == Some(true);
|
||||
if supported(init.meta("/openidea/steer")) {
|
||||
Some("_openidea/steer")
|
||||
} else if supported(init.meta.as_ref().and_then(|m| m.pointer("/steering/supported"))) {
|
||||
Some("_session/steering")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
let meta = |p: &str| init.meta(p).and_then(Value::as_bool) == Some(true);
|
||||
let capabilities = AgentCapabilities {
|
||||
images: init.prompt("image"),
|
||||
fork: init.session("fork"),
|
||||
rollback: meta("/openidea/rollback"),
|
||||
steer: steer_method(init).is_some(),
|
||||
steer: meta("/openidea/steer"),
|
||||
background_tasks: meta("/openidea/backgroundTasks"),
|
||||
read_only: false,
|
||||
};
|
||||
|
||||
@@ -51,9 +51,6 @@ struct FakeAgent {
|
||||
/// Config options `session/new` reports after the model one (per-model efforts, say).
|
||||
extra_options: Mutex<Vec<Value>>,
|
||||
model_options: Mutex<HashMap<String, Vec<Value>>>,
|
||||
/// Advertises steering as OMP does (`_meta.steering` at the top of `initialize`)
|
||||
/// instead of `_meta.openidea.steer`.
|
||||
session_steering: bool,
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
@@ -159,10 +156,6 @@ impl Handler for FakeAgent {
|
||||
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
|
||||
self.calls.lock().push("subagents".into());
|
||||
}
|
||||
if self.session_steering {
|
||||
return Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true},
|
||||
"_meta": {"steering": {"supported": true}}}));
|
||||
}
|
||||
Ok(
|
||||
json!({"protocolVersion": 1, "authMethods": self.auth_methods, "agentCapabilities": {"loadSession": !self.no_load,
|
||||
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true, "backgroundTasks": true}}}}),
|
||||
@@ -190,13 +183,6 @@ impl Handler for FakeAgent {
|
||||
self.calls.lock().push(format!("{method} {detail}"));
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_session/steering" => {
|
||||
let text = params["prompt"][0]["text"].clone();
|
||||
self.calls.lock().push(format!("{method} {text}"));
|
||||
// OMP answers whether the message joined the turn rather than failing.
|
||||
let outcome = if text == "too late" { "promptRequired" } else { "injected" };
|
||||
Ok(json!({"outcome": outcome, "queue": "steering"}))
|
||||
}
|
||||
"session/load" => {
|
||||
self.say(&session, "replayed history");
|
||||
Ok(json!({}))
|
||||
@@ -1074,42 +1060,6 @@ fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn steers_through_session_steering() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent { session_steering: true, ..FakeAgent::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.steer);
|
||||
|
||||
mgr.prompt(&task.id, text("also this"), true).await.unwrap();
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "_session/steering \"also this\""));
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(matches!(entries.last(), Some(AgentEntry::User { steered: true, .. })));
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
|
||||
|
||||
// The agent didn't take it into the turn: the turn stops and it goes next, as without
|
||||
// steering (the fake agent's next turn asks for permission).
|
||||
mgr.prompt(&task.id, text("too late"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: false, .. } if text == "too late")));
|
||||
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: true, .. } if text == "too late")));
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1275,9 +1275,7 @@ impl Project {
|
||||
}
|
||||
let defaults = self.documents.file_defaults();
|
||||
let fallback = defaults.fallback_for(path);
|
||||
// The working file only when it is a regular file: a path that is a directory there
|
||||
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
|
||||
if path.is_file() {
|
||||
if path.exists() {
|
||||
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
|
||||
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
|
||||
|
||||
@@ -310,8 +310,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "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"
|
||||
|
||||
@@ -111,49 +111,3 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
|
||||
assert_eq!(vcs::vcs_file_at(&host, "main", utf8, None).await.unwrap().as_deref(), Some(old));
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// A committed symlink to a folder (#3528): its revision is the link target, even though the
|
||||
/// working path is a directory.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_directory_symlink_revision_is_its_target() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(root.join("target")).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["config", "user.name", "Test"]);
|
||||
git(&root, &["config", "user.email", "[email protected]"]);
|
||||
git(&root, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(root.join("target/file.txt"), "example\n").unwrap();
|
||||
std::os::unix::fs::symlink("target", root.join("dir-link")).unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "Add a directory symlink"]);
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if !project.repos().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let link = root.join("dir-link");
|
||||
assert!(link.is_dir());
|
||||
assert_eq!(
|
||||
vcs::vcs_file_at(&host, "main", link.clone(), Some("HEAD".into())).await.unwrap().as_deref(),
|
||||
Some("target")
|
||||
);
|
||||
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -78,8 +78,8 @@ impl Needle {
|
||||
let mut b = 0;
|
||||
if n.eq_ignore_ascii_case(q) {
|
||||
b += EXACT;
|
||||
} else if let Some(dot) = n.iter().position(|&b| b == b'.')
|
||||
&& n[..dot].eq_ignore_ascii_case(q)
|
||||
} else if let Some(dot) = name.find('.')
|
||||
&& name.as_bytes()[..dot].eq_ignore_ascii_case(q)
|
||||
{
|
||||
b += EXACT_STEM;
|
||||
} else if n.len() >= q.len() && n[..q.len()].eq_ignore_ascii_case(q) {
|
||||
@@ -97,31 +97,17 @@ fn hump_bonus(s: &str, indices: &[u32]) -> u32 {
|
||||
if indices.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
// One pass over `s`: `indices` is sorted, and whether position `i` is a
|
||||
// word start only needs the char before it, so no `Vec<char>` is collected.
|
||||
let is_start = |prev: Option<char>, c: char| match prev {
|
||||
None => true,
|
||||
Some(p) => {
|
||||
!p.is_alphanumeric()
|
||||
|| (p.is_lowercase() && c.is_uppercase())
|
||||
|| (!p.is_ascii_digit() && c.is_ascii_digit())
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let is_start = |i: usize| {
|
||||
if i == 0 {
|
||||
return true;
|
||||
}
|
||||
let (p, c) = (chars[i - 1], chars[i]);
|
||||
!p.is_alphanumeric() || (p.is_lowercase() && c.is_uppercase()) || (!p.is_ascii_digit() && c.is_ascii_digit())
|
||||
};
|
||||
let (mut humps, mut next, mut first_start) = (0u32, 0usize, false);
|
||||
let (mut prev, mut at) = (None, 0u32);
|
||||
for c in s.chars() {
|
||||
if next < indices.len() && indices[next] == at {
|
||||
let started = is_start(prev, c);
|
||||
humps += u32::from(started);
|
||||
if next == 0 {
|
||||
first_start = started;
|
||||
}
|
||||
next += 1;
|
||||
}
|
||||
prev = Some(c);
|
||||
at += 1;
|
||||
}
|
||||
humps * HUMP + u32::from(first_start) * FIRST_AT_START
|
||||
let humps = indices.iter().filter(|&&i| (i as usize) < chars.len() && is_start(i as usize)).count() as u32;
|
||||
let first = if is_start(indices[0] as usize) { FIRST_AT_START } else { 0 };
|
||||
humps * HUMP + first
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -170,11 +170,6 @@ pub struct LanguageServerConfig {
|
||||
/// basedpyright): only used while none of those is installed.
|
||||
#[serde(default)]
|
||||
pub fallback: bool,
|
||||
/// Names of servers listed after this one that it makes redundant (a PHP server
|
||||
/// with its own Laravel support replaces `laravel-lsp`): they aren't used while
|
||||
/// this one serves the file.
|
||||
#[serde(default)]
|
||||
pub replaces: Vec<String>,
|
||||
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
|
||||
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
|
||||
/// capabilities it announces are ignored, so a refactoring-only server next
|
||||
|
||||
@@ -758,10 +758,7 @@ mod tests {
|
||||
let cfg = reg.get(&LanguageId::new("php")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallback: hover, rename and symbols stay with Intelephense.
|
||||
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
|
||||
// Phoxite answers the Laravel strings itself.
|
||||
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
|
||||
assert_eq!(names, ["intelephense", "phpactor", "laravel-lsp"]);
|
||||
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
|
||||
assert_eq!(lsp.command.as_str(), "laravel-lsp");
|
||||
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -660,17 +660,15 @@ impl LspManager {
|
||||
/// The servers serving `path`: every regular one, and each `fallback` one
|
||||
/// only while all servers listed before it have given up (missing, not
|
||||
/// launchable, or crashed for good). One that requires a root marker serves
|
||||
/// only files below one, and stands in for no other. One that a server before
|
||||
/// it `replaces` is left out while that server serves the file.
|
||||
/// only files below one, and stands in for no other.
|
||||
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
|
||||
if let Some(servers) = self.arduino_servers(language, path) {
|
||||
return servers;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut available_before = false;
|
||||
let mut replaced: Vec<String> = Vec::new();
|
||||
for sc in &self.language_servers(language) {
|
||||
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
|
||||
if sc.fallback && available_before {
|
||||
continue;
|
||||
}
|
||||
if sc.require_root_marker
|
||||
@@ -680,9 +678,6 @@ impl LspManager {
|
||||
}
|
||||
let server = self.server_for(sc, language, path);
|
||||
available_before |= !sc.require_root_marker && !server.gave_up();
|
||||
if !server.gave_up() {
|
||||
replaced.extend(sc.replaces.iter().cloned());
|
||||
}
|
||||
out.push(server);
|
||||
}
|
||||
out
|
||||
@@ -870,7 +865,7 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Missing,
|
||||
Some(message),
|
||||
) {
|
||||
self.fallbacks_take_over().await;
|
||||
self.attach_fallbacks();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -883,7 +878,7 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Misconfigured,
|
||||
Some(message),
|
||||
) {
|
||||
self.fallbacks_take_over().await;
|
||||
self.attach_fallbacks();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -896,7 +891,7 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Crashed,
|
||||
Some(message),
|
||||
) {
|
||||
self.fallbacks_take_over().await;
|
||||
self.attach_fallbacks();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1044,7 +1039,7 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
// Gave up (crashed repeatedly, or its build expired): the fallbacks it hid take over.
|
||||
None => self.fallbacks_take_over().await,
|
||||
None => self.attach_fallbacks(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3469,10 +3464,7 @@ impl LspManager {
|
||||
virtual_doc::is_decompiled(&text)
|
||||
};
|
||||
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
|
||||
let mut detected = self.languages.detect(Path::new(&title), None);
|
||||
if let Some(stem) = title.strip_suffix(".class").filter(|_| virtual_doc::is_java_class_stub(&text)) {
|
||||
detected = self.languages.detect(Path::new(&format!("{stem}.java")), None);
|
||||
}
|
||||
let detected = self.languages.detect(Path::new(&title), None);
|
||||
let language_id = if detected == LanguageId::plain_text() {
|
||||
languages.first().cloned().unwrap_or(detected)
|
||||
} else {
|
||||
@@ -3836,16 +3828,8 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server gave up: its fallbacks take over the open documents, and the servers
|
||||
/// they replace leave.
|
||||
async fn fallbacks_take_over(&self) {
|
||||
self.attach_fallbacks();
|
||||
self.detach_shadowed_fallbacks().await;
|
||||
}
|
||||
|
||||
/// A server enabled again shadows the fallbacks attached in its place, and a
|
||||
/// fallback that took over may replace a server attached earlier: they leave the
|
||||
/// open documents, and stop once no document uses them.
|
||||
/// A server enabled again shadows the fallbacks attached in its place: they
|
||||
/// leave the open documents, and stop once no document uses them.
|
||||
async fn detach_shadowed_fallbacks(&self) {
|
||||
let open: Vec<(DocId, LanguageId, PathBuf)> =
|
||||
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
|
||||
@@ -3861,7 +3845,6 @@ impl LspManager {
|
||||
.filter(|a| {
|
||||
!wanted.iter().any(|w| w.id == a.server.id)
|
||||
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|
||||
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|
||||
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
|
||||
})
|
||||
.map(|a| a.server.id)
|
||||
|
||||
@@ -110,17 +110,6 @@ pub fn is_decompiled(text: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a `.class` stub is written in Java: its first `package` or `import` line ends with `;`.
|
||||
/// The Kotlin language server shows Java classes from jars as Java and Kotlin ones as Kotlin, under
|
||||
/// the same `.class` name.
|
||||
pub fn is_java_class_stub(text: &str) -> bool {
|
||||
text.lines()
|
||||
.take(200)
|
||||
.map(str::trim)
|
||||
.find(|line| line.starts_with("package ") || line.starts_with("import "))
|
||||
.is_some_and(|line| line.ends_with(';'))
|
||||
}
|
||||
|
||||
/// `scheme` of a URI (`jdt` for `jdt://…`).
|
||||
pub fn scheme(uri: &str) -> &str {
|
||||
uri.split_once(':').map(|(s, _)| s).unwrap_or("")
|
||||
@@ -216,17 +205,6 @@ mod tests {
|
||||
|
||||
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
|
||||
|
||||
#[test]
|
||||
fn class_stubs_in_java_or_kotlin() {
|
||||
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
|
||||
let kotlin = "// IntelliJ API Decompiler stub source generated from a class file\n// Implementation of methods is not available\n\npackage kotlin.collections\n\npublic fun <T> listOf(): List<T> { /* compiled code */ }\n";
|
||||
let imports_only = "import java.util.List;\n\npublic class A {}\n";
|
||||
assert!(is_java_class_stub(java));
|
||||
assert!(is_java_class_stub(imports_only));
|
||||
assert!(!is_java_class_stub(kotlin));
|
||||
assert!(!is_java_class_stub("public class A {}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharp_metadata_titles_and_kinds() {
|
||||
for (uri, expected) in [
|
||||
|
||||
@@ -264,7 +264,6 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
install_hint: Some(format!("install {name}")),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -3287,67 +3286,6 @@ async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
/// A server that `replaces` another (a PHP server with its own Laravel support and
|
||||
/// `laravel-lsp`) keeps it away while it serves, and only then.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_replaced_server_stays_away_while_its_replacement_serves() {
|
||||
let servers = [("main", incremental_caps()), ("alt", incremental_caps()), ("framework", incremental_caps())];
|
||||
let configure = |cfg: &mut LanguageServerConfig| match cfg.name.as_str() {
|
||||
"alt" => {
|
||||
cfg.fallback = true;
|
||||
cfg.replaces = vec!["framework".into()];
|
||||
}
|
||||
"framework" => cfg.require_root_marker = true,
|
||||
_ => {}
|
||||
};
|
||||
let h = harness_configured("mock", "mk", &servers, configure);
|
||||
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
|
||||
{
|
||||
let disabled = disabled.clone();
|
||||
h.mgr.set_servers_hook(Box::new(move |_, defined| {
|
||||
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
|
||||
}));
|
||||
}
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
let (_, path) = h.open("a.mk", "x");
|
||||
let uri = uri_of(&path);
|
||||
|
||||
// The preferred server serves: the framework's server joins it, the alternative stays away.
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
h.wait_status("framework", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("framework").docs.lock().contains_key(&uri)).await;
|
||||
assert!(h.statuses("alt").is_empty());
|
||||
|
||||
// The alternative takes over: the server it replaces closes the document and stops.
|
||||
disabled.lock().push("main".into());
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
|
||||
assert!(!h.launcher.state("framework").notified("textDocument/didClose").is_empty());
|
||||
assert_eq!(h.statuses("framework").last(), Some(&ServerStatus::Stopped));
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
|
||||
|
||||
// The preferred server again: the framework's server comes back with it.
|
||||
disabled.lock().clear();
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
eventually(|| h.statuses("framework").last() == Some(&ServerStatus::Ready)).await;
|
||||
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
|
||||
|
||||
// A preferred server that is not installed: the alternative replaces the framework's
|
||||
// server although that one attached first.
|
||||
let servers = [("ghost", json!({})), ("alt", incremental_caps()), ("framework", incremental_caps())];
|
||||
let h = harness_configured("mock", "mk", &servers, configure);
|
||||
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
let (_, path) = h.open("a.mk", "x");
|
||||
let uri = uri_of(&path);
|
||||
h.wait_status("ghost", ServerStatus::Missing).await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
|
||||
eventually(|| !h.mgr.servers().iter().any(|s| s.name == "framework")).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
|
||||
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
|
||||
|
||||
@@ -419,7 +419,6 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
install_hint: Some("npm i -g nope-ls".into()),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -693,7 +692,6 @@ async fn typescript_language_server_end_to_end() {
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -747,7 +745,6 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
|
||||
@@ -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 {
|
||||
@@ -1306,7 +1300,6 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
}),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
|
||||
@@ -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())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -1590,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 }
|
||||
}
|
||||
|
||||
|
||||
@@ -170,28 +170,6 @@ mod tests {
|
||||
assert_eq!(select_asset(&["laravel-lsp"], rules, LINUX_X64), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phoxite_assets() {
|
||||
let names = [
|
||||
"phoxite-lsp-aarch64-apple-darwin",
|
||||
"phoxite-lsp-x86_64-apple-darwin",
|
||||
"phoxite-lsp-aarch64-unknown-linux-gnu",
|
||||
"phoxite-lsp-x86_64-unknown-linux-gnu",
|
||||
"phoxite-lsp-x86_64-pc-windows-msvc.exe",
|
||||
// Not for any platform here: the musl build, the checksums, the VS Code packages.
|
||||
"phoxite-lsp-x86_64-unknown-linux-musl",
|
||||
"phoxite-lsp-x86_64-unknown-linux-gnu.sha256",
|
||||
"phoxite-lsp-x86_64-pc-windows-msvc.exe.sha256",
|
||||
"phoxite-linux-x64-0.2.1.vsix",
|
||||
];
|
||||
let rules = crate::registry::find("phoxite").unwrap().asset_rules();
|
||||
assert_eq!(select_asset(&names, rules, MAC_ARM), Some(names[0]));
|
||||
assert_eq!(select_asset(&names, rules, MAC_X64), Some(names[1]));
|
||||
assert_eq!(select_asset(&names, rules, LINUX_ARM), Some(names[2]));
|
||||
assert_eq!(select_asset(&names, rules, LINUX_X64), Some(names[3]));
|
||||
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kmp_lsp_assets_include_the_native_jar_indexer() {
|
||||
let names = [
|
||||
|
||||
@@ -458,38 +458,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/laravel/lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phoxite",
|
||||
display: "Phoxite",
|
||||
kind: LanguageServer,
|
||||
commands: &["phoxite-lsp"],
|
||||
// Plain binaries per platform (`phoxite-lsp-<target triple>[.exe]`), each with a
|
||||
// `.sha256` beside it.
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "samehelhawary/phoxite" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "phoxite-lsp-aarch64-apple-darwin"),
|
||||
rule(Mac, X64, "phoxite-lsp-x86_64-apple-darwin"),
|
||||
rule(Linux, Arm64, "phoxite-lsp-aarch64-unknown-linux-gnu"),
|
||||
rule(Linux, X64, "phoxite-lsp-x86_64-unknown-linux-gnu"),
|
||||
rule(Windows, Arm64, "phoxite-lsp-aarch64-pc-windows-msvc.exe"),
|
||||
rule(Windows, X64, "phoxite-lsp-x86_64-pc-windows-msvc.exe"),
|
||||
],
|
||||
locate: &[
|
||||
"phoxite-lsp",
|
||||
"phoxite-lsp-aarch64-apple-darwin",
|
||||
"phoxite-lsp-x86_64-apple-darwin",
|
||||
"phoxite-lsp-aarch64-unknown-linux-gnu",
|
||||
"phoxite-lsp-x86_64-unknown-linux-gnu",
|
||||
"phoxite-lsp-aarch64-pc-windows-msvc",
|
||||
"phoxite-lsp-x86_64-pc-windows-msvc",
|
||||
],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("phoxite-lsp"),
|
||||
homepage: "https://github.com/samehelhawary/phoxite",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "gopls",
|
||||
display: "gopls",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -146,8 +146,7 @@ Closing a selected result activates its left neighbor, or its right neighbor if
|
||||
**Edit Data** (`F4`) opens a table in an editor tab with server-side paging (100 to 5,000 rows), a `WHERE` filter and an `ORDER BY` field (both with completion). Click a column header to sort; `Shift`-click to add more sort columns.
|
||||
|
||||
- Double-click, `Enter` or `F2` edits a cell; `Shift+Enter` opens a larger editor. Pasting tab-separated text fills several cells.
|
||||
- **Add Row** (`⌘N` / `Alt+Insert`), **Delete Rows** (`Ctrl+Y` on Windows and Linux), **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
|
||||
- **Reload Page** (`⌘R` / `Ctrl+F5`), **Previous Page** and **Next Page** (`⌘⌥↑` / `⌘⌥↓`, `Ctrl+Alt+Up` / `Ctrl+Alt+Down`). These, the copy commands and **Export Data** are actions: find them with **Find Action** and assign shortcuts in **Settings › Keymap**.
|
||||
- **Add Row**, **Delete Rows**, **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
|
||||
- **Submit** (`⌘Enter` / `Ctrl+Enter`) sends all pending changes in one transaction; **Revert** (`⌘⌥Z` / `Ctrl+Alt+Z`) discards them.
|
||||
|
||||
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
|
||||
|
||||
@@ -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**.
|
||||
|
||||
|
||||
@@ -101,7 +101,6 @@ Each entry starts one LSP server. Servers are listed in order; all regular serve
|
||||
| `settings` | table | Answers the server's `workspace/configuration` requests. Without it, the requested sections are looked up in `initialization-options`. |
|
||||
| `install-hint` | string | Shown when the server is missing and the IDE cannot install it. |
|
||||
| `fallback` | bool | An alternative to the servers listed before it; used only while none of them is installed. |
|
||||
| `replaces` | string array | Names of servers listed after this one that it makes redundant. They are not used while this server serves the file. Use it for an alternative that covers what an added server does. |
|
||||
| `features` | string array | Use the server only for these features; empty means everything. Values: `completion`, `inline-completion`, `hover`, `signature-help`, `definition`, `declaration`, `type-definition`, `implementation`, `references`, `document-highlight`, `document-symbol`, `workspace-symbol`, `code-action`, `code-lens`, `rename`, `formatting`, `inlay-hint`, `semantic-tokens`, `document-link`, `call-hierarchy`, `type-hierarchy`, `folding-range`, `selection-range`, `diagnostics`. |
|
||||
| `code-action-kinds` | string array | Keep only these code action kinds, matched by prefix (`refactor` keeps `refactor.extract`); empty keeps all. |
|
||||
| `connect` | string | `host:port` of a server that speaks LSP over TCP. See [TCP servers](#tcp-servers). |
|
||||
|
||||
@@ -148,7 +148,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
|
||||
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
|
||||
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
|
||||
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
|
||||
|
||||
@@ -7,14 +7,11 @@ OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.p
|
||||
|
||||
## Language servers
|
||||
|
||||
| Server | When it runs |
|
||||
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
|
||||
| `phpactor` | Fallback: used only while Intelephense is not installed. |
|
||||
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
|
||||
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
|
||||
|
||||
While Phoxite serves a project, `laravel-lsp` is not started: Phoxite answers the Laravel strings itself.
|
||||
| Server | When it runs |
|
||||
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
|
||||
| `phpactor` | Fallback: used only while Intelephense is not installed. |
|
||||
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
|
||||
|
||||
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
|
||||
|
||||
@@ -28,7 +25,6 @@ When a `.php` file opens and Intelephense is missing, a notification offers **In
|
||||
| ------------------ | ---------------------------------------------------------------------- |
|
||||
| Intelephense | npm (`intelephense`) |
|
||||
| Laravel LSP | GitHub release (`laravel/lsp`) |
|
||||
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
|
||||
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
|
||||
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
|
||||
|
||||
@@ -81,12 +77,12 @@ See [Debugging](/en/guide/debugging).
|
||||
|
||||
## Framework support
|
||||
|
||||
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
|
||||
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration.
|
||||
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
|
||||
|
||||
## Limitations
|
||||
|
||||
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
|
||||
- No Blade or Twig template support; only `.php` files get PHP code insight.
|
||||
- phpactor is not installed by the IDE.
|
||||
- Run with Coverage is not available for PHPUnit.
|
||||
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
|
||||
@@ -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>`。
|
||||
|
||||
@@ -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`。
|
||||
|
||||
@@ -145,8 +145,7 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
|
||||
**编辑数据**(`F4`)在编辑器标签页中打开表,服务器端分页(每页 100 到 5,000 行),并提供 `WHERE` 过滤和 `ORDER BY` 字段(都支持补全)。点击列标题排序,按住 `Shift` 点击可以追加排序列。
|
||||
|
||||
- 双击、`Enter` 或 `F2` 编辑单元格;`Shift+Enter` 打开更大的编辑框。粘贴制表符分隔的文本可以一次填写多个单元格。
|
||||
- **添加行**(`⌘N` / `Alt+Insert`)、**删除行**(Windows 和 Linux 上为 `Ctrl+Y`)、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
|
||||
- **重新加载页面**(`⌘R` / `Ctrl+F5`)、**上一页** 和 **下一页**(`⌘⌥↑` / `⌘⌥↓`,`Ctrl+Alt+Up` / `Ctrl+Alt+Down`)。这些命令、各种复制命令和 **导出数据** 都是操作:可以在 **查找操作** 中找到,并在 **设置 › 按键映射** 中设置快捷键。
|
||||
- **添加行**、**删除行**、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
|
||||
- **提交**(`⌘Enter` / `Ctrl+Enter`)在一个事务中提交所有待定更改;**还原**(`⌘⌥Z` / `Ctrl+Alt+Z`)放弃更改。
|
||||
|
||||
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
|
||||
|
||||
@@ -47,7 +47,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
| **将光标移至代码块开头** / **末尾** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
|
||||
| **切换插入/改写** | `Insert` | `Insert` |
|
||||
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行重新排序,默认没有快捷键。
|
||||
|
||||
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
|
||||
|
||||
|
||||
@@ -101,7 +101,6 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
|
||||
| `settings` | 表 | 用于响应服务器的 `workspace/configuration` 请求。不写时,从 `initialization-options` 中查找请求的配置节。 |
|
||||
| `install-hint` | 字符串 | 服务器缺失且 IDE 无法安装时显示的提示。 |
|
||||
| `fallback` | 布尔 | 作为前面服务器的备选,只在它们都未安装时使用。 |
|
||||
| `replaces` | 字符串数组 | 排在它后面、因它而变得多余的服务器名称。它为文件提供服务时,这些服务器不会被使用。用于能覆盖附加服务器功能的备选服务器。 |
|
||||
| `features` | 字符串数组 | 只把服务器用于这些功能;为空表示全部。可选值:`completion`、`inline-completion`、`hover`、`signature-help`、`definition`、`declaration`、`type-definition`、`implementation`、`references`、`document-highlight`、`document-symbol`、`workspace-symbol`、`code-action`、`code-lens`、`rename`、`formatting`、`inlay-hint`、`semantic-tokens`、`document-link`、`call-hierarchy`、`type-hierarchy`、`folding-range`、`selection-range`、`diagnostics`。 |
|
||||
| `code-action-kinds` | 字符串数组 | 只保留这些种类的代码操作,按前缀匹配(`refactor` 包含 `refactor.extract`);为空则全部保留。 |
|
||||
| `connect` | 字符串 | 通过 TCP 提供 LSP 的服务器地址 `host:port`,见 [TCP 服务器](#tcp-服务器)。 |
|
||||
|
||||
@@ -143,7 +143,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
|
||||
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
|
||||
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
|
||||
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
|
||||
|
||||
@@ -7,14 +7,11 @@ OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老
|
||||
|
||||
## 语言服务器
|
||||
|
||||
| 服务器 | 启用条件 |
|
||||
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
|
||||
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
|
||||
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
|
||||
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
|
||||
|
||||
Phoxite 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由 Phoxite 自己处理。
|
||||
| 服务器 | 启用条件 |
|
||||
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
|
||||
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
|
||||
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
|
||||
|
||||
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
|
||||
|
||||
@@ -28,7 +25,6 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
|
||||
| ------------------ | -------------------------------------------------- |
|
||||
| Intelephense | npm(`intelephense`) |
|
||||
| Laravel LSP | GitHub release(`laravel/lsp`) |
|
||||
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
|
||||
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
|
||||
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
|
||||
|
||||
@@ -81,12 +77,12 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
|
||||
|
||||
## 框架支持
|
||||
|
||||
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
|
||||
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。
|
||||
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
|
||||
- 不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。
|
||||
- IDE 不会安装 phpactor。
|
||||
- PHPUnit 不支持使用覆盖率运行。
|
||||
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -26,17 +26,6 @@ args = ["language-server"]
|
||||
root-markers = ["composer.json", ".phpactor.json"]
|
||||
install-hint = "Install phpactor (https://phpactor.readthedocs.io/en/master/usage/standalone.html)"
|
||||
|
||||
# Alternative with its own Laravel and Blade support. https://github.com/samehelhawary/phoxite
|
||||
[[language-servers]]
|
||||
name = "phoxite"
|
||||
fallback = true
|
||||
command = "phoxite-lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
# It answers the Laravel strings itself.
|
||||
replaces = ["laravel-lsp"]
|
||||
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
|
||||
|
||||
# Laravel projects only: hover, definition and completion inside
|
||||
# config('…'), route('…') and view('…'). Last: Intelephense keeps PHP hover,
|
||||
# rename and symbols. https://github.com/laravel/lsp
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -72,7 +72,6 @@ cancel_task always project_host bin
|
||||
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
|
||||
@@ -176,7 +175,6 @@ deploy_server_root trusted project_host bin
|
||||
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
|
||||
|
||||
+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 {
|
||||
|
||||
@@ -290,20 +290,6 @@ export const documentSynced = Facet.define<() => Promise<void>, (() => Promise<v
|
||||
combine: (values) => values[0] ?? null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Undo / Redo of an editor whose history is kept outside CodeMirror (notebook cells share
|
||||
* the notebook's backend history). Commands that would call CodeMirror's history (Vim's
|
||||
* `u` / `Ctrl-R`) go through it instead.
|
||||
*/
|
||||
export interface ExternalHistory {
|
||||
undo(): void;
|
||||
redo(): void;
|
||||
}
|
||||
|
||||
export const externalHistory = Facet.define<ExternalHistory, ExternalHistory | null>({
|
||||
combine: (values) => values[0] ?? null,
|
||||
});
|
||||
|
||||
export function whenSynced(view: EditorView): Promise<void> {
|
||||
return view.state.facet(documentSynced)?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ import { resetAllEditorsFontZoom, stepAllEditorsFontZoom } from "./cm/prefs";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { menuGroupItems, notifications } from "@/workbench/contributions";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { toggleReadOnly } from "./fileAttributes";
|
||||
@@ -529,29 +529,7 @@ function copyReference(reference: Promise<string>) {
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { doc, selection } = view.state;
|
||||
const line = doc.lineAt(selection.main.head).number;
|
||||
const { from, to } = selection.main;
|
||||
// The selected lines, leaving out the one a selection ends at the start of.
|
||||
const first = doc.lineAt(from).number;
|
||||
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
line: first - 1,
|
||||
endLine: last > first ? last - 1 : undefined,
|
||||
}).flatMap((item) =>
|
||||
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
preview: item.preview,
|
||||
shortcut: shortcutLabel(item.id),
|
||||
run: item.run,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
const line = view.state.doc.lineAt(view.state.selection.main.head).number;
|
||||
const flavours = [
|
||||
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
|
||||
{ id: "project.copyFileName", label: "File Name", value: pathToCopy("name", path) },
|
||||
@@ -579,7 +557,6 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
void executeAction(f.id, f.id === "editor.copyPathWithLineNumber" ? f.value : path);
|
||||
},
|
||||
})),
|
||||
...contributed,
|
||||
{
|
||||
id: "editor.copyReference",
|
||||
label: tx("Reference"),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { tags as t, type styleTags } from "@lezer/highlight";
|
||||
|
||||
/**
|
||||
* @lezer/javascript styles `.` as a deref operator, but not `?.`; it tags `this` as `self` (Python's
|
||||
* `self` colour) and `super` as an atom, which WebStorm colours as keywords.
|
||||
*/
|
||||
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator, "this super": t.keyword };
|
||||
/** @lezer/javascript styles `.` as a deref operator, but not `?.`. */
|
||||
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator };
|
||||
@@ -270,31 +270,6 @@ describe("language modes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("colours `this` and `super` as keywords in Java, JavaScript, TypeScript and C++", async () => {
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.self, class: "self" },
|
||||
{ tag: t.atom, class: "atom" },
|
||||
]);
|
||||
for (const [mode, path, doc, expected] of [
|
||||
["Java", "/p/A.java", "class A extends B { A() { super(); this.a = 1; } }", ["super", "this"]],
|
||||
["JavaScript", "/p/a.js", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
|
||||
["TypeScript", "/p/a.ts", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
|
||||
["C++", "/p/a.cpp", "void A::m() { this->a = 1; }", ["this"]],
|
||||
] as const) {
|
||||
const support = await loadSupport(findLanguageDescription(mode, path)!);
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
|
||||
found.push([doc.slice(from, to), style]),
|
||||
);
|
||||
const words = new Set<string>(expected);
|
||||
expect(
|
||||
found.filter(([text]) => words.has(text)),
|
||||
mode,
|
||||
).toEqual(expected.map((word) => [word, "keyword"]));
|
||||
}
|
||||
});
|
||||
|
||||
it("recognizes go.mod and go.work files by mode and filename", async () => {
|
||||
for (const [mode, path] of [
|
||||
["GoMod", "/project/go.mod"],
|
||||
|
||||
@@ -293,11 +293,9 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
|
||||
"ClassName IdName PseudoClassName ColorLiteral CallTag": t.tagName,
|
||||
};
|
||||
|
||||
// @lezer/java tags annotations as plain identifiers, and `this` as `self` (Python's `self` colour);
|
||||
// IntelliJ colours `this` as a keyword.
|
||||
// @lezer/java tags annotations as plain identifiers.
|
||||
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
|
||||
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
|
||||
this: t.keyword,
|
||||
};
|
||||
|
||||
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
|
||||
@@ -308,8 +306,6 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
|
||||
JSX: JS_TAGS,
|
||||
TSX: JS_TAGS,
|
||||
Java: JAVA_TAGS,
|
||||
// CLion colours `this` as a keyword.
|
||||
"C++": { this: t.keyword },
|
||||
PHP: {
|
||||
"; ,": t.separator,
|
||||
"ClassDeclaration/Name BaseClause/Name InterfaceClause/Name": t.className,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { LspPopups } from "@/editor/lsp/Popups";
|
||||
import { registerProjectActions } from "@/features/project-tree/actions";
|
||||
import { useProjectTree } from "@/features/project-tree/store";
|
||||
import { useContextMenuStore } from "@/ui";
|
||||
import { provideNotificationService, registerMenuGroup, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import * as controller from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { registerEditorActions } from "./actions";
|
||||
@@ -189,44 +189,6 @@ describe("editor Copy Path/Reference chooser", () => {
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
});
|
||||
|
||||
it("lists contributed links before Reference, for the selected lines", async () => {
|
||||
const contexts: MenuGroupContext[] = [];
|
||||
const run = vi.fn();
|
||||
disposers.push(
|
||||
registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, ctx) => {
|
||||
contexts.push(ctx);
|
||||
return [{ id: "test.copyLink", label: "Host Link", verbatim: true, preview: "https://host/a#L1", run }];
|
||||
},
|
||||
}),
|
||||
);
|
||||
const view = ctrl.activeSlot!.view!;
|
||||
await executeAction("editor.copyPathReference");
|
||||
expect(
|
||||
popup()
|
||||
.items.map((item) => item.label)
|
||||
.slice(-2),
|
||||
).toEqual(["Host Link", "Reference"]);
|
||||
expect(popup().items.at(-2)).toMatchObject({
|
||||
preview: "https://host/a#L1",
|
||||
shortcut: shortcutLabel("test.copyLink"),
|
||||
});
|
||||
await popup().items.at(-2)!.run();
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
// From the first line into the second; then ending at the start of the second line.
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
expect(contexts.map(({ paths, line, endLine }) => [paths, line, endLine])).toEqual([
|
||||
[[path], 1, undefined],
|
||||
[[path], 0, 1],
|
||||
[[path], 0, undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds the chooser to Copy / Paste Special", () => {
|
||||
vi.spyOn(ctrl.activeSlot!.view!, "posAtCoords").mockReturnValue(null);
|
||||
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 0 6px 0 8px;
|
||||
}
|
||||
.pin {
|
||||
@@ -89,7 +89,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
min-height: 36px;
|
||||
padding: 0 12px;
|
||||
background: var(--bg-editor-banner, color-mix(in srgb, var(--accent) 7%, var(--bg-editor, var(--bg-elev))));
|
||||
@@ -133,8 +133,8 @@
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 420px) auto 1fr;
|
||||
align-items: center;
|
||||
column-gap: var(--space-1-5);
|
||||
row-gap: var(--space-1-5);
|
||||
column-gap: 6px;
|
||||
row-gap: 6px;
|
||||
padding: 6px 8px 6px 10px;
|
||||
background: var(--bg-editor-inline, var(--bg-elev));
|
||||
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
|
||||
@@ -155,7 +155,7 @@
|
||||
.findButtons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.findCount {
|
||||
font-size: var(--fs-ui);
|
||||
@@ -173,14 +173,14 @@
|
||||
.replaceButtons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* Go to line */
|
||||
.gotoBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
padding: 8px 16px 0;
|
||||
}
|
||||
.gotoHint {
|
||||
@@ -316,7 +316,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
height: 26px;
|
||||
padding: 0 8px;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -115,7 +115,7 @@ function EmptyEditorArea() {
|
||||
return (
|
||||
<div ref={ref} className={styles.area}>
|
||||
<EmptyEditor />
|
||||
{over && <div className={styles.dropZone} aria-hidden="true" />}
|
||||
{over && <div className={clsx(styles.dropZone, styles["drop-center"])} aria-hidden="true" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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)} />
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
border-radius: var(--radius-row);
|
||||
@@ -87,7 +87,7 @@
|
||||
.childHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
margin-bottom: 2px;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
padding: 0 12px;
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 600;
|
||||
@@ -96,7 +96,7 @@
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
font-size: var(--fs-ui);
|
||||
@@ -263,7 +263,7 @@
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 2px 6px;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
background: var(--bg-popup);
|
||||
@@ -283,7 +283,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 0 6px 0 12px;
|
||||
background: var(--bg-popup-inline, var(--bg-elev));
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
@@ -342,7 +342,7 @@
|
||||
height: var(--h-row);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
padding: 0 14px;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
@@ -368,7 +368,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 10px 14px 0;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-muted);
|
||||
@@ -421,7 +421,7 @@
|
||||
border: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.reformatLegend {
|
||||
margin-bottom: 6px;
|
||||
@@ -432,21 +432,21 @@
|
||||
.reformatOption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.pasteImports {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.pasteImportList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.targets {
|
||||
@@ -41,7 +41,7 @@
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 110px;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
padding: 0 8px;
|
||||
min-height: var(--h-list-row);
|
||||
}
|
||||
@@ -88,6 +88,6 @@
|
||||
.busy {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
@@ -35,7 +35,7 @@
|
||||
.agentRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0 8px;
|
||||
@@ -69,7 +69,7 @@
|
||||
.registryState {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
@@ -79,7 +79,7 @@
|
||||
.customActions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
@@ -116,7 +116,7 @@
|
||||
.facts {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
margin-top: 2px;
|
||||
color: var(--fg-muted);
|
||||
@@ -143,12 +143,12 @@
|
||||
.actions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.progress {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
max-width: 360px;
|
||||
margin: 10px 0 0 34px;
|
||||
}
|
||||
@@ -182,7 +182,7 @@
|
||||
}
|
||||
.links {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
}
|
||||
.link {
|
||||
padding: 0;
|
||||
@@ -209,7 +209,7 @@
|
||||
.sectionTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
height: 22px;
|
||||
margin-bottom: 4px;
|
||||
color: var(--fg-strong);
|
||||
@@ -244,7 +244,7 @@
|
||||
grid-template-columns: minmax(150px, max-content) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
column-gap: 10px;
|
||||
row-gap: var(--space-1);
|
||||
row-gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.label {
|
||||
@@ -278,7 +278,7 @@
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
@@ -575,7 +575,7 @@ function Details({
|
||||
{job && (
|
||||
<div className={styles.progress}>
|
||||
<ProgressBar value={job.fraction} aria-label={tx`Installing ${agent.name}`} />
|
||||
<span>{job.message}</span>
|
||||
<span className={styles.hint}>{job.message}</span>
|
||||
</div>
|
||||
)}
|
||||
{!job && installed && update && <p className={styles.notice}>{tx`${update} is available`}</p>}
|
||||
|
||||
@@ -18,14 +18,14 @@
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.column {
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-control);
|
||||
@@ -42,7 +42,7 @@
|
||||
min-height: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 4px 8px;
|
||||
background: var(--bg-hover);
|
||||
background: var(--bg-subtle);
|
||||
border-radius: var(--radius-control);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
@@ -65,7 +65,7 @@
|
||||
.add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.input {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -31,7 +31,7 @@
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
@@ -105,7 +105,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
padding: 24px 12px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
@@ -154,7 +154,7 @@
|
||||
.dockedBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 2px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
@@ -215,7 +215,7 @@
|
||||
padding: 4px 12px 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
}
|
||||
.external > .row {
|
||||
flex: none;
|
||||
@@ -225,7 +225,7 @@
|
||||
.chooser {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
.chooserList {
|
||||
height: 312px;
|
||||
@@ -242,14 +242,14 @@
|
||||
.chooserRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.chooserFooter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
}
|
||||
.chooserFolder {
|
||||
flex: 0 0 auto;
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
border-radius: inherit;
|
||||
background: color-mix(in srgb, var(--bg-popup) 82%, transparent);
|
||||
color: var(--fg-strong);
|
||||
@@ -85,7 +85,7 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 4px 6px 6px;
|
||||
cursor: default;
|
||||
}
|
||||
@@ -95,13 +95,13 @@
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
}
|
||||
/* Attach/reference buttons share the send button's 24px footprint and chrome. */
|
||||
@@ -135,7 +135,7 @@
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 80px) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.settingsLabel {
|
||||
@@ -147,7 +147,7 @@
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: var(--h-control);
|
||||
min-width: 0;
|
||||
padding: 0 4px 0 6px;
|
||||
@@ -229,7 +229,7 @@
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
}
|
||||
.effortValue {
|
||||
color: var(--fg-strong);
|
||||
@@ -295,7 +295,7 @@
|
||||
.modeOption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: 24px;
|
||||
margin: 0 6px;
|
||||
padding: 0 8px;
|
||||
@@ -318,7 +318,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
margin-top: 6px;
|
||||
padding: 8px 14px 2px;
|
||||
border-top: 1px solid var(--border);
|
||||
@@ -329,7 +329,7 @@
|
||||
.bar {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.toolbar {
|
||||
flex-wrap: nowrap;
|
||||
@@ -392,7 +392,7 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 8px 10px 0;
|
||||
cursor: default;
|
||||
}
|
||||
@@ -539,7 +539,7 @@
|
||||
.popupFooter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) 14px;
|
||||
gap: 4px 14px;
|
||||
padding: 5px 12px 6px;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-subtle);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
width: min(var(--agent-conversation-width), 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
.fitWidth .inner {
|
||||
width: 100%;
|
||||
@@ -35,7 +35,7 @@
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
/* The chips' own padding spaces them. */
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 0 2px;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -66,7 +66,7 @@
|
||||
padding: 16px 12px 12px;
|
||||
}
|
||||
.docked .inner {
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
.docked .where {
|
||||
flex-wrap: nowrap;
|
||||
@@ -95,7 +95,7 @@
|
||||
.notes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
height: 0;
|
||||
}
|
||||
.docked .notes {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -10,13 +10,13 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.title {
|
||||
@@ -52,7 +52,7 @@
|
||||
.error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-control);
|
||||
background: color-mix(in srgb, var(--danger) 12%, transparent);
|
||||
@@ -63,7 +63,7 @@
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--accent-soft);
|
||||
@@ -89,13 +89,13 @@
|
||||
justify-content: space-between;
|
||||
min-height: 32px;
|
||||
padding: 2px 4px;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sectionToggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 4px 2px;
|
||||
@@ -143,6 +143,12 @@
|
||||
padding: 2px 0 6px;
|
||||
}
|
||||
|
||||
.emptySection {
|
||||
padding: 6px 24px 8px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.sectionNote {
|
||||
margin: 0;
|
||||
padding: 2px 24px 6px;
|
||||
@@ -155,7 +161,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
padding: 6px 8px 6px 22px;
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
@@ -167,7 +173,7 @@
|
||||
.rowMain {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
@@ -191,7 +197,7 @@
|
||||
.rowActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -200,7 +206,7 @@
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 10px var(--space-3);
|
||||
gap: 10px 12px;
|
||||
padding: 12px 16px 4px;
|
||||
}
|
||||
|
||||
@@ -217,7 +223,7 @@
|
||||
.formControl {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
height: 20px;
|
||||
padding: 0 6px 0 4px;
|
||||
@@ -126,7 +126,7 @@
|
||||
.cardHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 6px 10px;
|
||||
}
|
||||
.cardPath {
|
||||
@@ -201,7 +201,7 @@
|
||||
.codeHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: 26px;
|
||||
padding: 0 4px 0 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
|
||||
@@ -91,7 +91,7 @@
|
||||
flex-wrap: wrap;
|
||||
/* The changes chip sits above the line; the facts stay on that line's baseline. */
|
||||
align-items: flex-end;
|
||||
gap: var(--space-0-5) var(--space-1-5);
|
||||
gap: 2px 6px;
|
||||
min-width: 0;
|
||||
padding: 0 2px;
|
||||
overflow: hidden;
|
||||
@@ -104,7 +104,7 @@
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
min-width: 0;
|
||||
color: var(--fg-secondary);
|
||||
@@ -122,7 +122,7 @@
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
/* The chips' own padding spaces them. */
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -144,7 +144,7 @@
|
||||
flex: 1 1 auto;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
gap: 2px 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* Shrinks before the terminal buttons do: in a narrow docked session the meters clip, not the controls. */
|
||||
@@ -154,7 +154,7 @@
|
||||
margin-left: auto;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
@@ -163,13 +163,13 @@
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
/* What changed (files, commits) above the meters; both open the Changes pane. */
|
||||
.statusChips {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -177,7 +177,7 @@
|
||||
composes: surface from "../../ui/Chip.module.css";
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0 8px;
|
||||
@@ -207,31 +207,6 @@
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
/* The archived-task notice: an editor notification banner above the conversation. */
|
||||
.banner {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
min-height: 36px;
|
||||
padding: 9px 12px;
|
||||
background: var(--bg-feedback-warning);
|
||||
border-bottom: 1px solid var(--border-feedback-warning);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.bannerText {
|
||||
flex: 1 1 240px;
|
||||
min-width: 0;
|
||||
max-height: 33vh;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.bannerSpacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* The conversation with its find bar. */
|
||||
.streamArea {
|
||||
min-width: 0;
|
||||
@@ -345,7 +320,7 @@
|
||||
.messageFooter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
min-height: var(--h-control-small);
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
@@ -403,7 +378,7 @@
|
||||
}
|
||||
.messageActions {
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
opacity: 0;
|
||||
@@ -467,7 +442,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
@@ -523,14 +498,14 @@
|
||||
.editBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.editButtons {
|
||||
display: flex;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@@ -760,7 +735,7 @@
|
||||
.thought summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
height: var(--h-row);
|
||||
color: var(--fg-muted);
|
||||
@@ -798,7 +773,7 @@
|
||||
.tool {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
min-height: var(--h-row);
|
||||
@@ -853,7 +828,7 @@
|
||||
.processSummary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
@@ -901,7 +876,7 @@
|
||||
.processBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
max-height: calc(var(--h-row) * 16);
|
||||
overflow-y: auto;
|
||||
margin-top: 2px;
|
||||
@@ -925,7 +900,7 @@
|
||||
|
||||
.plan {
|
||||
display: grid;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.planTitle {
|
||||
font-weight: 600;
|
||||
@@ -934,7 +909,7 @@
|
||||
.planItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.planDone {
|
||||
color: var(--fg-muted);
|
||||
@@ -1042,7 +1017,7 @@
|
||||
|
||||
.error {
|
||||
display: flex;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
align-items: flex-start;
|
||||
color: var(--danger);
|
||||
white-space: pre-wrap;
|
||||
@@ -1052,20 +1027,10 @@
|
||||
.working {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
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);
|
||||
}
|
||||
@@ -1074,7 +1039,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
align-self: center;
|
||||
width: 100%;
|
||||
max-width: calc(var(--session-content-width) + var(--space-3) * 2);
|
||||
@@ -1085,12 +1050,12 @@
|
||||
.background {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.backgroundTask {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
min-height: 24px;
|
||||
padding: 0 4px 0 8px;
|
||||
border-radius: var(--radius-row);
|
||||
@@ -1110,12 +1075,12 @@
|
||||
.queue {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.queued {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
min-height: 28px;
|
||||
padding: 0 4px 0 8px;
|
||||
border-radius: var(--radius-row);
|
||||
@@ -1170,7 +1135,7 @@
|
||||
.images {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.imageItem {
|
||||
@@ -1210,14 +1175,14 @@
|
||||
.attachments {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) var(--space-1-5);
|
||||
gap: 4px 6px;
|
||||
margin-top: 4px;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.attachment {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.changes {
|
||||
@@ -1250,7 +1215,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
padding: 0 6px 0 10px;
|
||||
@@ -1295,7 +1260,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
}
|
||||
.changeName {
|
||||
flex: 0 1 auto;
|
||||
@@ -1327,7 +1292,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.changeGroupName {
|
||||
min-width: 0;
|
||||
@@ -1342,7 +1307,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.changeCommitHash {
|
||||
flex: none;
|
||||
@@ -1373,7 +1338,7 @@
|
||||
.subagent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
@@ -1382,7 +1347,7 @@
|
||||
.subagentHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.subagentOpen {
|
||||
@@ -1390,7 +1355,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
padding: 2px 4px;
|
||||
margin: -2px -4px;
|
||||
border: 0;
|
||||
@@ -1466,7 +1431,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: 30px;
|
||||
padding: 0 8px 0 6px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
@@ -1477,7 +1442,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.crumb {
|
||||
@@ -1523,12 +1488,12 @@
|
||||
.subagentStrip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
}
|
||||
.subagentChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
max-width: 240px;
|
||||
height: 22px;
|
||||
padding: 0 8px;
|
||||
@@ -1556,7 +1521,7 @@
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
/* The composer's width, so the card sits exactly over the box it belongs to. */
|
||||
@@ -1598,7 +1563,7 @@
|
||||
.question {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
@@ -1632,7 +1597,7 @@
|
||||
.questionChoices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.question .questionChoices > * {
|
||||
border: 1px solid var(--border);
|
||||
@@ -1658,7 +1623,7 @@
|
||||
.questionChoice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
.questionOptionText {
|
||||
display: flex;
|
||||
@@ -1688,19 +1653,19 @@
|
||||
.questionBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.questionChoices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
@container question-card (min-width: 640px) {
|
||||
.questionBodyWithPreview {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
gap: 12px;
|
||||
align-items: start;
|
||||
}
|
||||
.questionBodyWithPreview .questionPreview {
|
||||
@@ -1716,7 +1681,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
grid-area: 1 / 1;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
visibility: hidden;
|
||||
}
|
||||
@@ -1749,12 +1714,12 @@
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
gap: 8px;
|
||||
}
|
||||
.questionPager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
}
|
||||
.questionPage {
|
||||
color: var(--fg-subtle);
|
||||
@@ -1796,7 +1761,7 @@
|
||||
.tray {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
}
|
||||
.tray:empty {
|
||||
display: none;
|
||||
@@ -1808,12 +1773,12 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
gap: 4px;
|
||||
}
|
||||
.trayChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: 6px;
|
||||
height: var(--h-row);
|
||||
padding: 0 var(--space-2);
|
||||
border: none;
|
||||
@@ -1832,7 +1797,7 @@
|
||||
.trayPlan {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
gap: 2px;
|
||||
padding: 2px var(--space-2) 4px calc(var(--space-2) * 2);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
@@ -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: var(--space-2);
|
||||
}
|
||||
|
||||
.after {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.seconds {
|
||||
width: 64px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.items {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
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: var(--space-1-5);
|
||||
padding: 4px 8px;
|
||||
background: var(--bg-hover);
|
||||
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: var(--space-1-5);
|
||||
}
|
||||
|
||||
.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 = {
|
||||
|
||||
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача