дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
104
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
e6e2bdb80d | ||
|
|
6e5f91f7fd | ||
|
|
e38599b82b | ||
|
|
437008c517 | ||
|
|
5947204022 | ||
|
|
d4a2a84c36 | ||
|
|
1c94aeb476 | ||
|
|
b9014f34cf | ||
|
|
0920f189d6 | ||
|
|
a3c7591624 | ||
|
|
1ba9ace7e2 | ||
|
|
d8e58296be | ||
|
|
196057019f | ||
|
|
272a183442 | ||
|
|
cd57b7f053 | ||
|
|
45dd96cdeb | ||
|
|
22db3ab9c3 | ||
|
|
343dd51082 | ||
|
|
75c57e2691 | ||
|
|
856fc3009e | ||
|
|
3f7a072fa1 | ||
|
|
c9a2b6200e | ||
|
|
c1d552e578 | ||
|
|
02d22fe658 | ||
|
|
7f9a618cac | ||
|
|
1877d8c1a1 | ||
|
|
839da450f7 | ||
|
|
ba42061885 | ||
|
|
2b359f9a98 | ||
|
|
b83c1a60c2 | ||
|
|
f213999338 | ||
|
|
920e321109 | ||
|
|
ede0705bd5 | ||
|
|
a75c332905 | ||
|
|
954180beb0 | ||
|
|
eb6483030c | ||
|
|
6c9c02417e | ||
|
|
9e7f842caf | ||
|
|
0bda7b194b | ||
|
|
9ab90941ef | ||
|
|
1dc1c67095 | ||
|
|
6f7c8e246f | ||
|
|
5638f8d04e | ||
|
|
f156baa976 | ||
|
|
d41bccc50c | ||
|
|
9087fa61d9 | ||
|
|
6404c30718 | ||
|
|
66a765664c | ||
|
|
fe1b5eacf8 | ||
|
|
21c4b08a5d | ||
|
|
f8e0ad57ff | ||
|
|
72e1d6afc1 | ||
|
|
8ffd6c9e2c | ||
|
|
dbfec0c433 | ||
|
|
1bdd5b4094 | ||
|
|
88eba9f3bd | ||
|
|
8044948178 | ||
|
|
0425004ecd | ||
|
|
c1b45b037d | ||
|
|
f5732dd706 | ||
|
|
e86e28ae63 | ||
|
|
82fdd97588 | ||
|
|
1757d26e78 | ||
|
|
766e1edc0c | ||
|
|
fc52975be0 | ||
|
|
c3726daed6 | ||
|
|
69c9521e85 | ||
|
|
fc60719d4b | ||
|
|
e35ba7d805 | ||
|
|
fa0783ab03 | ||
|
|
5338a34008 | ||
|
|
1d3547a953 | ||
|
|
14ed7aa647 | ||
|
|
27164e8919 | ||
|
|
62bac6ec8c | ||
|
|
17a32e0c1f | ||
|
|
e0ed6a0a3b | ||
|
|
db0cdccd66 | ||
|
|
4237117f2c | ||
|
|
26edc6d826 | ||
|
|
92c71837cb | ||
|
|
0791e73974 | ||
|
|
a8773a196c | ||
|
|
5f50469d7e | ||
|
|
9e4fbe863d | ||
|
|
7fdd39a628 | ||
|
|
9d8fdab75e | ||
|
|
f09d51bd49 | ||
|
|
00aef16862 | ||
|
|
87b659b3ac | ||
|
|
709cde907e | ||
|
|
6a69707220 | ||
|
|
e30651473d | ||
|
|
8397e5e2a3 | ||
|
|
890fade636 | ||
|
|
dfe4784874 | ||
|
|
43c9053624 | ||
|
|
05c64c2475 | ||
|
|
3334d1016b | ||
|
|
637e227efa | ||
|
|
5432d7f288 | ||
|
|
2fdc024358 | ||
|
|
84267f44ed | ||
|
|
e08e455fe5 |
No files matched your search
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 192 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 179 KiB |
@@ -47,7 +47,7 @@ on:
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "src/assets/openidea-logo.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Створено
+11
@@ -4672,6 +4672,7 @@ dependencies = [
|
||||
"tree-sitter-css",
|
||||
"tree-sitter-dart",
|
||||
"tree-sitter-elixir",
|
||||
"tree-sitter-fsharp",
|
||||
"tree-sitter-gdscript",
|
||||
"tree-sitter-go",
|
||||
"tree-sitter-graphql",
|
||||
@@ -10395,6 +10396,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-fsharp"
|
||||
version = "0.3.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "248fccdffd6f029b4932cf2c619b0a40ccaeab3c32764c237316a717c0c72aa2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-gdscript"
|
||||
version = "6.1.0"
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-5.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).
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -288,6 +288,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## tree-sitter-fsharp queries
|
||||
|
||||
`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's
|
||||
`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp)
|
||||
0.3.13 (the grammar itself is a Cargo dependency).
|
||||
|
||||
### MIT License (tree-sitter-fsharp)
|
||||
|
||||
Copyright (c) 2023 Nikolaj Sidorenco
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -19,6 +19,7 @@ mod external;
|
||||
pub mod hermes;
|
||||
mod images;
|
||||
pub mod mcp;
|
||||
pub mod mcp_registry;
|
||||
pub mod memory;
|
||||
mod model;
|
||||
mod native;
|
||||
@@ -36,6 +37,10 @@ pub use automation::*;
|
||||
pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use mcp_registry::{
|
||||
DEFAULT_MCP_REGISTRY_URL, McpRegistryInputField, McpRegistryInputKind, McpRegistryInstallOption, McpRegistryPage,
|
||||
McpRegistryServer, OFFICIAL_MCP_REGISTRY_URL,
|
||||
};
|
||||
pub use model::*;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
@@ -155,6 +160,8 @@ const FLUSH_DELAY: Duration = Duration::from_millis(40);
|
||||
const SAVE_DELAY: Duration = Duration::from_millis(250);
|
||||
/// Updates that arrive this late after `session/load` returns are still replayed history.
|
||||
const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// Agents whose recorded sessions can become tasks (import, fork).
|
||||
const RECORDED_SESSION_AGENTS: [&str; 3] = ["claude", "codex", "copilot"];
|
||||
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
|
||||
/// can trail its `session/prompt` response by this much.
|
||||
const TURN_GRACE: Duration = Duration::from_millis(100);
|
||||
@@ -273,6 +280,9 @@ pub struct SkillsPolicy {
|
||||
pub workspace_roots: Vec<PathBuf>,
|
||||
/// Validated `<dir>` folders contributed by live OpenIDEA plugins (`[[contributes.skills]]`).
|
||||
pub plugin_dirs: Vec<PathBuf>,
|
||||
/// Non-ignored `SKILL.md` file paths surfaced by the project file index, enabling discovery
|
||||
/// of deeply nested workspace skills beyond the 2-level direct directory walk.
|
||||
pub indexed_skill_files: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for SkillsPolicy {
|
||||
@@ -283,6 +293,7 @@ impl Default for SkillsPolicy {
|
||||
workspace_trusted: true,
|
||||
workspace_roots: Vec::new(),
|
||||
plugin_dirs: Vec::new(),
|
||||
indexed_skill_files: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -718,6 +729,9 @@ struct ForkStart {
|
||||
source: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
target: Option<String>,
|
||||
/// The source's turns the fork keeps; the agent drops the rest as it forks.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turns: Option<u32>,
|
||||
}
|
||||
|
||||
/// A canonical lowercase UUID, the only session id shape either native agent writes.
|
||||
@@ -1015,6 +1029,8 @@ struct Task {
|
||||
/// The task has a session but none of its history (an imported session): the next load's
|
||||
/// replay becomes the task's history instead of being dropped.
|
||||
adopting_replay: AtomicBool,
|
||||
/// A background load of the recorded session started in this run (see `load_recorded_session`).
|
||||
recorded_load_started: AtomicBool,
|
||||
/// The saved session failed to load and the user was told: the next start opens a new one.
|
||||
start_fresh: AtomicBool,
|
||||
/// The current turn is being cancelled to send the first queued message right away.
|
||||
@@ -1509,6 +1525,7 @@ impl AgentManager {
|
||||
};
|
||||
let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots };
|
||||
let plugin_dirs = policy.plugin_dirs;
|
||||
let indexed_skill_files = policy.indexed_skill_files;
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
let cmd_provider = provider.clone();
|
||||
blocking(move || {
|
||||
@@ -1520,7 +1537,13 @@ impl AgentManager {
|
||||
plugins::resolve_plugins(plugins::discover_plugins(&roots, home.as_deref()), &p_pol, None);
|
||||
let projected = plugins::projected_skill_roots(&p_states, Some(&cmd_provider));
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills_with_agent_plugins(&roots, home.as_deref(), &plugin_dirs, &projected),
|
||||
skills::discover_skills_with_indexed_files(
|
||||
&roots,
|
||||
home.as_deref(),
|
||||
&plugin_dirs,
|
||||
&projected,
|
||||
&indexed_skill_files,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -1545,9 +1568,13 @@ impl AgentManager {
|
||||
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
|
||||
}
|
||||
|
||||
/// The entries of the task's conversation, or of its subagent `subagent`'s.
|
||||
/// The entries of the task's conversation, or of its subagent `subagent`'s. A task that
|
||||
/// holds a recorded session without its history starts loading it.
|
||||
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
let task = self.task(id)?;
|
||||
if subagent.is_none() && task.awaits_recorded_history() {
|
||||
task.load_recorded_session(self.shared.shutdown_epoch());
|
||||
}
|
||||
let s = task.state.lock();
|
||||
let timeline =
|
||||
s.history.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
|
||||
@@ -1586,7 +1613,7 @@ impl AgentManager {
|
||||
|
||||
/// Imports an external session as a task, loading it in the background to show its history (#312).
|
||||
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
if !RECORDED_SESSION_AGENTS.contains(&provider) {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
@@ -1662,13 +1689,7 @@ impl AgentManager {
|
||||
};
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session(epoch).await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
handle.load_recorded_session(epoch);
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -1676,7 +1697,7 @@ impl AgentManager {
|
||||
/// recording as the agent's own fork, under an id the host chooses. The session must
|
||||
/// belong to this project and have been recorded in `cwd`.
|
||||
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
if !RECORDED_SESSION_AGENTS.contains(&provider) {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
@@ -1754,7 +1775,7 @@ impl AgentManager {
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }),
|
||||
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target, turns: None }),
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
let epoch = {
|
||||
@@ -1765,13 +1786,7 @@ impl AgentManager {
|
||||
};
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session(epoch).await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
handle.load_recorded_session(epoch);
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -2295,9 +2310,17 @@ impl AgentManager {
|
||||
/// its first message.
|
||||
pub async fn fork(&self, id: &str, turns: Option<u32>) -> IdeResult<AgentTask> {
|
||||
let source = self.task(id)?;
|
||||
if source.state.lock().busy {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
// While a turn runs, the copy stops before it.
|
||||
let running = {
|
||||
let s = source.state.lock();
|
||||
let turn_runs =
|
||||
matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
|
||||
&& running_turn(&s.history.conversation.main.entries).is_some();
|
||||
if s.busy && !turn_runs {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
s.busy
|
||||
};
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
|
||||
// It can also fork a recorded thread whose writer is held by another process.
|
||||
@@ -2311,11 +2334,15 @@ impl AgentManager {
|
||||
None
|
||||
};
|
||||
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
|
||||
let keep = turns.unwrap_or(total).min(total);
|
||||
let done = total - u32::from(running);
|
||||
let keep = turns.unwrap_or(done).min(done);
|
||||
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
|
||||
if !capabilities.fork || (keep < total && !capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
}
|
||||
if keep == 0 && running {
|
||||
return Err(IdeError::invalid("wait until the agent finishes its first turn"));
|
||||
}
|
||||
let session = if let Some(live) = &live {
|
||||
let (cwd, provider_id, mcp_overrides, project_root) = {
|
||||
let s = source.state.lock();
|
||||
@@ -2340,19 +2367,19 @@ impl AgentManager {
|
||||
&roots,
|
||||
);
|
||||
params["sessionId"] = json!(live.session);
|
||||
set_openidea_meta(&mut params, "forkTurns", json!(keep));
|
||||
params
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(source.describe(e)))?;
|
||||
Some(
|
||||
reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
|
||||
.to_owned(),
|
||||
)
|
||||
let id = reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
|
||||
.to_owned();
|
||||
Some((id, forked_turns(&reply) == Some(keep)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -2380,6 +2407,10 @@ impl AgentManager {
|
||||
automation: None,
|
||||
..s.task.clone()
|
||||
};
|
||||
let (session, cut) = match session {
|
||||
Some((id, cut)) => (Some(id), cut),
|
||||
None => (None, false),
|
||||
};
|
||||
TaskFile {
|
||||
task,
|
||||
session_id: session,
|
||||
@@ -2394,10 +2425,10 @@ impl AgentManager {
|
||||
turn: None,
|
||||
turns: Vec::new(),
|
||||
subagents: s.history.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
pending_rollback: if cut { 0 } else { total - keep },
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
|
||||
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None, turns: Some(keep) }),
|
||||
}
|
||||
};
|
||||
// Copying may have started the source's agent: it stops again once idle.
|
||||
@@ -3750,7 +3781,13 @@ impl Task {
|
||||
};
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills_with_agent_plugins(&roots, home.as_deref(), &policy.plugin_dirs, &[]),
|
||||
skills::discover_skills_with_indexed_files(
|
||||
&roots,
|
||||
home.as_deref(),
|
||||
&policy.plugin_dirs,
|
||||
&[],
|
||||
&policy.indexed_skill_files,
|
||||
),
|
||||
Some(&overrides),
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -3905,6 +3942,7 @@ impl Task {
|
||||
next_permission: AtomicU32::new(1),
|
||||
replaying: AtomicBool::new(false),
|
||||
adopting_replay: AtomicBool::new(adopt),
|
||||
recorded_load_started: AtomicBool::new(false),
|
||||
start_fresh: AtomicBool::new(false),
|
||||
send_now: AtomicBool::new(false),
|
||||
cancel_pending: AtomicBool::new(false),
|
||||
@@ -5407,7 +5445,39 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// A task holding a recorded session but none of its history (an import whose load failed or
|
||||
/// was cut short) that is idle and not yet loading it in this run.
|
||||
fn awaits_recorded_history(&self) -> bool {
|
||||
if self.recorded_load_started.load(Ordering::Acquire) || !self.adopts_replay() || self.live.lock().is_some() {
|
||||
return false;
|
||||
}
|
||||
let s = self.state.lock();
|
||||
!s.busy
|
||||
&& s.session_id.is_some()
|
||||
&& s.pending_native_fork.is_none()
|
||||
&& RECORDED_SESSION_AGENTS.contains(&s.task.provider.as_str())
|
||||
}
|
||||
|
||||
/// Opens the recorded session in the background, once per run: its replay shows the history
|
||||
/// before a first message (#312).
|
||||
fn load_recorded_session(self: &Arc<Self>, epoch: u64) {
|
||||
if self.recorded_load_started.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
let task = self.clone();
|
||||
self.shared.runtime.spawn(async move {
|
||||
match task.ensure_session_for(epoch, OpenFor::History).await {
|
||||
Ok(_) => task.release_when_idle(),
|
||||
Err(e) => tracing::warn!("agent task {}: loading its recorded session failed: {e}", task.id),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn ensure_session(self: &Arc<Self>, epoch: u64) -> Result<Live, String> {
|
||||
self.ensure_session_for(epoch, OpenFor::Message).await
|
||||
}
|
||||
|
||||
async fn ensure_session_for(self: &Arc<Self>, epoch: u64, open_for: OpenFor) -> Result<Live, String> {
|
||||
let _guard = self.connecting.lock().await;
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return Err("The agent manager shut down.".into());
|
||||
@@ -5417,9 +5487,9 @@ impl Task {
|
||||
{
|
||||
return Ok(live);
|
||||
}
|
||||
let (provider_id, cwd, saved, pending) = {
|
||||
let (provider_id, saved, pending) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), s.pending_model.clone())
|
||||
(s.task.provider.clone(), s.session_id.clone(), s.pending_model.clone())
|
||||
};
|
||||
let pending_model = pending.as_ref();
|
||||
let raw_spec = self.shared.spec(&provider_id).ok_or_else(|| format!("unknown agent {provider_id}"))?;
|
||||
@@ -5431,7 +5501,7 @@ impl Task {
|
||||
raw_spec.clone()
|
||||
};
|
||||
let opened =
|
||||
match self.open_session(&provider_id, primary_spec, &cwd, saved.clone(), pending_model, epoch).await {
|
||||
match self.open_session(&provider_id, primary_spec, open_for, saved.clone(), pending_model, epoch).await {
|
||||
Ok(live) => Ok(live),
|
||||
Err(err) if can_fallback && err.allow_acp_fallback && !self.shared.shut_down_since(epoch) => {
|
||||
tracing::warn!(
|
||||
@@ -5441,7 +5511,7 @@ impl Task {
|
||||
);
|
||||
self.shared.mark_copilot_acp_fallback(&raw_spec);
|
||||
let acp_spec = native::copilot::acp_fallback_spec(&raw_spec);
|
||||
self.open_session(&provider_id, acp_spec, &cwd, saved, pending_model, epoch).await
|
||||
self.open_session(&provider_id, acp_spec, open_for, saved, pending_model, epoch).await
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
@@ -5477,7 +5547,7 @@ impl Task {
|
||||
self: &Arc<Self>,
|
||||
provider_id: &str,
|
||||
spec: provider::ProviderSpec,
|
||||
_cwd: &Path,
|
||||
open_for: OpenFor,
|
||||
saved: Option<String>,
|
||||
pending_model: Option<&PendingModel>,
|
||||
epoch: u64,
|
||||
@@ -5614,14 +5684,10 @@ impl Task {
|
||||
let mut params = opening_params.clone();
|
||||
params["sessionId"] = json!(&fork.source);
|
||||
if let Some(target) = &fork.target {
|
||||
match params["_meta"].as_object_mut() {
|
||||
Some(meta) => {
|
||||
if let Some(openidea) = meta.entry("openidea").or_insert_with(|| json!({})).as_object_mut() {
|
||||
openidea.insert("forkSessionId".into(), json!(target));
|
||||
}
|
||||
}
|
||||
None => params["_meta"] = json!({ "openidea": { "forkSessionId": target } }),
|
||||
}
|
||||
set_openidea_meta(&mut params, "forkSessionId", json!(target));
|
||||
}
|
||||
if let Some(turns) = fork.turns {
|
||||
set_openidea_meta(&mut params, "forkTurns", json!(turns));
|
||||
}
|
||||
let reply = self
|
||||
.request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params)
|
||||
@@ -5635,6 +5701,9 @@ impl Task {
|
||||
allow_acp_fallback: false,
|
||||
})?
|
||||
.to_owned();
|
||||
if fork.turns.is_some() && forked_turns(&reply) == fork.turns {
|
||||
self.state.lock().pending_rollback = 0;
|
||||
}
|
||||
session = Some((id, reply));
|
||||
} else {
|
||||
let start_fresh = self.start_fresh.load(Ordering::Acquire);
|
||||
@@ -5680,13 +5749,15 @@ impl Task {
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
}
|
||||
// Warm-up, timeouts and writer conflicts can clear before the next attempt.
|
||||
// Warm-up, timeouts and writer conflicts can clear before the next attempt,
|
||||
// and only a message whose failure the user sees may give up the session.
|
||||
let writer_conflict = spec.driver == provider::Driver::Codex
|
||||
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"));
|
||||
if acp::service_warming_up(&e)
|
||||
|| matches!(e, RpcError::Timeout)
|
||||
|| writer_conflict
|
||||
|| pending_model.is_some()
|
||||
|| open_for == OpenFor::History
|
||||
{
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
@@ -7042,6 +7113,28 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The turn running now: the last message that started one, until the turn ends.
|
||||
fn running_turn(entries: &[AgentEntry]) -> Option<usize> {
|
||||
let last = *turn_starts(entries).last()?;
|
||||
matches!(entries[last], AgentEntry::User { done_ms: None, .. }).then_some(last)
|
||||
}
|
||||
|
||||
/// The source turns a `session/fork` kept, when the agent cut the copy itself.
|
||||
fn forked_turns(reply: &Value) -> Option<u32> {
|
||||
reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
|
||||
}
|
||||
|
||||
/// Sets `_meta.openidea.<key>` on request params.
|
||||
fn set_openidea_meta(params: &mut Value, key: &str, value: Value) {
|
||||
if !params["_meta"].is_object() {
|
||||
params["_meta"] = json!({});
|
||||
}
|
||||
if !params["_meta"]["openidea"].is_object() {
|
||||
params["_meta"]["openidea"] = json!({});
|
||||
}
|
||||
params["_meta"]["openidea"][key] = value;
|
||||
}
|
||||
|
||||
/// The MCP servers of a session, and the names of the ones off for it.
|
||||
struct McpForSession {
|
||||
servers: Vec<Value>,
|
||||
@@ -7468,6 +7561,13 @@ struct SessionOpenError {
|
||||
allow_acp_fallback: bool,
|
||||
}
|
||||
|
||||
/// Why a session opens: for a message, whose failure the user sees, or to show the recorded history.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum OpenFor {
|
||||
Message,
|
||||
History,
|
||||
}
|
||||
|
||||
/// Registers an opening peer on `task.connecting_peer` so `kill()` can terminate it
|
||||
/// mid-handshake, and kills it on early error return.
|
||||
struct OpeningPeer<'a> {
|
||||
|
||||
@@ -70,6 +70,8 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: cfg.registry_name.clone(),
|
||||
registry_url: cfg.registry_url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +256,28 @@ pub fn apply_save(
|
||||
if input.scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
|
||||
let map = match prev_scope {
|
||||
McpScope::User => &*user,
|
||||
McpScope::Workspace => &*workspace,
|
||||
};
|
||||
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
|
||||
});
|
||||
let registry_name = input
|
||||
.registry_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
|
||||
let registry_url = input
|
||||
.registry_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
|
||||
|
||||
let cfg = match input.transport {
|
||||
McpTransport::Stdio => {
|
||||
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
|
||||
@@ -277,6 +301,8 @@ pub fn apply_save(
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
@@ -301,6 +327,8 @@ pub fn apply_save(
|
||||
url: Some(url.to_owned()),
|
||||
headers,
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1018,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1272,6 +1302,8 @@ mod tests {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1327,6 +1359,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1347,6 +1381,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1367,6 +1403,8 @@ mod tests {
|
||||
url: Some("https://example.com/mcp".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
|
||||
agents: vec!["claude".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1058,6 +1058,14 @@ pub struct McpServer {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1084,6 +1092,14 @@ pub struct McpServerInput {
|
||||
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
|
||||
#[serde(default)]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -1673,6 +1689,12 @@ pub struct AgentMarketplaceCandidate {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
@@ -1761,6 +1783,12 @@ pub struct AgentPluginPreview {
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
|
||||
@@ -209,6 +209,17 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
|
||||
Ok(parent(first_dropped).map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Where to fork `chain` to keep only its first `turns` turns: the entry the last kept
|
||||
/// turn ends with, as [`cut`] reports it. `None` when the chain has fewer turns.
|
||||
pub(super) fn keep(chain: &[&Value], turns: usize) -> Option<Option<String>> {
|
||||
let total = chain.iter().filter(|e| is_turn_start(e)).count();
|
||||
if turns > total {
|
||||
return None;
|
||||
}
|
||||
// A turn that runs now is in the chain up to where it got: it is dropped like any other.
|
||||
cut(chain, total - turns).ok()
|
||||
}
|
||||
|
||||
/// The newest title Claude Code gave the session.
|
||||
pub(crate) fn title(entries: &[Value]) -> Option<String> {
|
||||
entries
|
||||
|
||||
@@ -347,6 +347,24 @@ impl Shim {
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
/// `start` (a fork's) cut after the source's first `turns` turns; `None` when the
|
||||
/// transcript can't be read or has fewer turns.
|
||||
fn pin_fork(&self, cwd: &Path, start: &Start, id: &str, turns: usize) -> Option<Start> {
|
||||
let chain = match self.base_chain(cwd, start) {
|
||||
Ok(chain) => chain,
|
||||
Err(e) => {
|
||||
tracing::debug!("Claude Code fork {id}: can't read the source transcript: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let refs: Vec<&Value> = chain.iter().collect();
|
||||
Some(match (start, history::keep(&refs, turns)?) {
|
||||
(_, None) => Start::New { id: id.to_owned() },
|
||||
(Start::Fork { from, .. }, Some(at)) => Start::Fork { from: from.clone(), id: id.to_owned(), at: Some(at) },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
Start::New { .. } => return Ok(Vec::new()),
|
||||
@@ -509,11 +527,28 @@ impl Shim {
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
// Pinned now: the source may go on (or be running a turn) before the fork starts.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let mut kept = None;
|
||||
let start = match wanted {
|
||||
Some(turns) => match self.pin_fork(&cwd, &start, &id, turns as usize) {
|
||||
Some(pinned) => {
|
||||
kept = Some(turns);
|
||||
pinned
|
||||
}
|
||||
None => start,
|
||||
},
|
||||
None => start,
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
"session/set_config_option" | "session/set_mode" => {
|
||||
let session = self.session(¶ms)?;
|
||||
@@ -947,7 +982,7 @@ impl Session {
|
||||
fn steer(&self, prompt: Value) -> Result<(), String> {
|
||||
let uuid = new_uuid(true);
|
||||
let mut message = user_message(&prompt, &uuid, true);
|
||||
message["priority"] = json!("now");
|
||||
message["priority"] = json!("next");
|
||||
let mut st = self.st.lock();
|
||||
let proc = st.proc.clone().ok_or("Claude Code is not running")?;
|
||||
let turn = st.turn.as_mut().filter(|t| !t.cancelled).ok_or("no turn is running")?;
|
||||
|
||||
@@ -212,6 +212,30 @@ async fn steer(h: &Harness) -> (Outcome, String) {
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
/// Stops the turn while a steered message waits for the running tool.
|
||||
async fn steer_stop(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
let prompt = h.prompt(&s, "Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.");
|
||||
let steer_and_stop = async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
let steered = h
|
||||
.request(
|
||||
"_openidea/steer",
|
||||
json!({ "sessionId": s, "prompt": [{ "type": "text", "text": "Also end your answer with the word BANANA." }] }),
|
||||
)
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
h.client.notify("session/cancel", json!({ "sessionId": s })).unwrap();
|
||||
steered
|
||||
};
|
||||
let (r, steered) = tokio::join!(prompt, steer_and_stop);
|
||||
if h.recording {
|
||||
// Long enough for the CLI to run the steered message, had it kept it.
|
||||
tokio::time::sleep(Duration::from_secs(8)).await;
|
||||
}
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
async fn subagent(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
h.answer(&[Some("allow"), Some("allow")]);
|
||||
@@ -253,6 +277,7 @@ const SCENARIOS: &[(&str, ScenarioFn)] = &[
|
||||
("tool_approval", |h| Box::pin(tool_approval(h))),
|
||||
("interrupt", |h| Box::pin(interrupt(h))),
|
||||
("steer", |h| Box::pin(steer(h))),
|
||||
("steer_stop", |h| Box::pin(steer_stop(h))),
|
||||
("subagent", |h| Box::pin(subagent(h))),
|
||||
("resume", |h| Box::pin(resume(h))),
|
||||
];
|
||||
@@ -620,10 +645,20 @@ async fn replay_steer() {
|
||||
assert_eq!(r.stop("prompt"), "end_turn");
|
||||
assert!(r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let steer = r.sent(0).into_iter().filter(|m| m["type"] == "user").nth(1).unwrap();
|
||||
assert_eq!(steer["priority"], "now");
|
||||
assert_eq!(steer["priority"], "next");
|
||||
assert!(steer["uuid"].as_str().unwrap().ends_with(history::STEER_MARK));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_steer_stop() {
|
||||
let r = replay("steer_stop").await;
|
||||
assert!(r.result("steer").is_ok(), "{:?}", r.result("steer"));
|
||||
assert_eq!(r.stop("prompt"), "cancelled");
|
||||
assert!(!r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let interrupt = r.sent(0).into_iter().find(|m| m["request"]["subtype"] == "interrupt").unwrap();
|
||||
assert_eq!(interrupt["request"]["cancel_queued"], true);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_subagent() {
|
||||
let r = replay("subagent").await;
|
||||
@@ -695,6 +730,73 @@ async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_pins_the_cut_to_the_kept_turns() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
// Two finished turns and a third still running.
|
||||
let dir = config.path().join("projects").join(history::escape(&h.cwd));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut parent = Value::Null;
|
||||
let mut lines = String::new();
|
||||
for (uuid, kind, text) in [
|
||||
("u1", "user", "one"),
|
||||
("a1", "assistant", "1"),
|
||||
("u2", "user", "two"),
|
||||
("a2", "assistant", "2"),
|
||||
("u3", "user", "three"),
|
||||
("a3", "assistant", "partial"),
|
||||
] {
|
||||
let entry = json!({"type": kind, "uuid": uuid, "parentUuid": parent,
|
||||
"message": {"role": kind, "content": [{"type": "text", "text": text}]}});
|
||||
lines += &format!("{entry}\n");
|
||||
parent = json!(uuid);
|
||||
}
|
||||
std::fs::write(dir.join(format!("{source}.jsonl")), lines).unwrap();
|
||||
|
||||
let fork = |target: &'static str, turns: u64| {
|
||||
h.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target, "forkTurns": turns } }
|
||||
}),
|
||||
)
|
||||
};
|
||||
let saved = |target: &str| -> Value {
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = fork(target, 2).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), Some(&json!(2)));
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": "a2" }));
|
||||
|
||||
// More turns than the transcript holds: left to the host to settle.
|
||||
let target = "33333333-3333-4333-8333-333333333333";
|
||||
let reply = fork(target, 4).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), None);
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
@@ -799,7 +901,14 @@ fn scrub(frame: &mut Value) -> bool {
|
||||
json!([{ "name": "review", "description": "Review a pull request", "argumentHint": "" },
|
||||
{ "name": "init", "description": "Write a CLAUDE.md", "argumentHint": "" }]),
|
||||
);
|
||||
for k in ["agents", "account", "available_output_styles", "user_output_styles_dir", "output_style"] {
|
||||
for k in [
|
||||
"agents",
|
||||
"account",
|
||||
"stored_login_organization_uuid",
|
||||
"available_output_styles",
|
||||
"user_output_styles_dir",
|
||||
"output_style",
|
||||
] {
|
||||
o.remove(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(1);
|
||||
/// How long the client's connection outlives codex.
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
/// How often running background terminals are listed again: codex announces neither a
|
||||
/// terminal that outlives its turn nor its end.
|
||||
#[cfg(not(test))]
|
||||
const TERMINAL_POLL: Duration = Duration::from_secs(3);
|
||||
#[cfg(test)]
|
||||
const TERMINAL_POLL: Duration = Duration::from_millis(20);
|
||||
/// How long closing the connection waits for codex to stop the background terminals.
|
||||
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
|
||||
/// What a thread's name is asked for with, after its first turn.
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
@@ -187,6 +195,10 @@ fn attach(
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
to_client.closed().await;
|
||||
// Background terminals run in process groups of their own: stopping codex alone
|
||||
// would leave them running with nothing left to report or stop them.
|
||||
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
|
||||
shim.clean_terminals(&threads).await;
|
||||
codex.kill();
|
||||
});
|
||||
Ok(ours)
|
||||
@@ -248,6 +260,14 @@ struct Thread {
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// Running background terminals of this session and its subagents, by task id:
|
||||
/// `(thread, processId)`.
|
||||
terminals: HashMap<String, (String, String)>,
|
||||
/// The background tasks reported last.
|
||||
shown_tasks: Vec<Value>,
|
||||
/// The background terminals are being followed; `relist` asks for another listing.
|
||||
watching: bool,
|
||||
relist: bool,
|
||||
/// A name is being asked for.
|
||||
naming: bool,
|
||||
}
|
||||
@@ -416,6 +436,7 @@ impl CodexShim {
|
||||
"session/prompt" => self.prompt(¶ms).await,
|
||||
"_openidea/steer" => self.steer(¶ms).await,
|
||||
"_openidea/rollback" => self.rollback(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
@@ -439,7 +460,7 @@ impl CodexShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
"authMethods": [],
|
||||
@@ -568,9 +589,26 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
|
||||
let mut kept = None;
|
||||
if let (Some(turns), Some(held)) = (wanted, held)
|
||||
&& turns <= held
|
||||
{
|
||||
let dropped = held - turns;
|
||||
if dropped > 0 {
|
||||
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
|
||||
}
|
||||
kept = Some(turns);
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
@@ -915,6 +953,16 @@ impl CodexShim {
|
||||
/// Stops following the session's thread (codex unloads it once nothing follows it).
|
||||
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect()
|
||||
};
|
||||
self.clean_terminals(&threads).await;
|
||||
let known = self.state.lock().threads.remove(session).is_some();
|
||||
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
|
||||
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
|
||||
@@ -922,6 +970,129 @@ impl CodexShim {
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Follows the background terminals of `session` and its subagents until none runs:
|
||||
/// codex keeps them running after the turn that started them.
|
||||
fn watch_terminals(self: &Arc<Self>, session: &str) {
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if state.gone {
|
||||
return;
|
||||
}
|
||||
let Some(t) = state.threads.get_mut(session) else { return };
|
||||
if t.watching {
|
||||
t.relist = true;
|
||||
return;
|
||||
}
|
||||
t.watching = true;
|
||||
}
|
||||
let (shim, session) = (self.clone(), session.to_owned());
|
||||
self.runtime.spawn(async move {
|
||||
loop {
|
||||
let running = shim.list_terminals(&session).await;
|
||||
let relist = {
|
||||
let mut state = shim.state.lock();
|
||||
let Some(t) = state.threads.get_mut(&session) else { return };
|
||||
let relist = std::mem::take(&mut t.relist);
|
||||
if !relist && !running {
|
||||
t.watching = false;
|
||||
return;
|
||||
}
|
||||
relist
|
||||
};
|
||||
if !relist {
|
||||
tokio::time::sleep(TERMINAL_POLL).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Reports the running background terminals of `session` and its subagents as the
|
||||
/// session's background tasks; whether any runs. A codex without the (experimental)
|
||||
/// listing has none to report.
|
||||
async fn list_terminals(&self, session: &str) -> bool {
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
|
||||
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
|
||||
};
|
||||
let mut terminals = HashMap::new();
|
||||
let mut tasks = Vec::new();
|
||||
for thread in &threads {
|
||||
let listed = match self.terminals_of(thread).await {
|
||||
Ok(listed) => listed,
|
||||
Err(e) => {
|
||||
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (process, description) in listed {
|
||||
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
|
||||
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
|
||||
terminals.insert(id, (thread.clone(), process));
|
||||
}
|
||||
}
|
||||
let running = !tasks.is_empty();
|
||||
let changed = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(t) = state.threads.get_mut(session) else { return false };
|
||||
t.terminals = terminals;
|
||||
let changed = t.shown_tasks != tasks;
|
||||
if changed {
|
||||
t.shown_tasks = tasks.clone();
|
||||
}
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
/// The running background terminals of `thread`, as `(processId, description)`.
|
||||
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
|
||||
let mut all = Vec::new();
|
||||
let mut cursor = Value::Null;
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
let page =
|
||||
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
|
||||
all.extend(translate::background_terminals(&page));
|
||||
match page.get("nextCursor").and_then(Value::as_str) {
|
||||
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
|
||||
_ => return Ok(all),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_openidea/stop_task`: stops one background terminal.
|
||||
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let task = str_param(params, "taskId")?;
|
||||
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
|
||||
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
|
||||
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
|
||||
self.list_terminals(session).await;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Stops the background terminals of `threads`; a codex without the (experimental)
|
||||
/// method has none.
|
||||
async fn clean_terminals(&self, threads: &[String]) {
|
||||
if threads.is_empty() || self.state.lock().gone {
|
||||
return;
|
||||
}
|
||||
let clean = async {
|
||||
for thread in threads {
|
||||
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
|
||||
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
|
||||
tracing::warn!("codex: stopping the background terminals timed out");
|
||||
}
|
||||
}
|
||||
|
||||
/// `session/cancel`: interrupts the session's turn, or the one about to start.
|
||||
fn cancel(&self, session: &str) {
|
||||
let mut state = self.state.lock();
|
||||
@@ -1261,6 +1432,19 @@ impl CodexShim {
|
||||
t.turn = None;
|
||||
}
|
||||
t.completed = Some(id.to_owned());
|
||||
// A command still open when its turn completed goes on in the background (a
|
||||
// background terminal): its call returned, so it didn't fail with the turn. Its
|
||||
// own completion reports how it ended. Sent before the prompt's answer settles the
|
||||
// turn.
|
||||
if completed {
|
||||
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
|
||||
for id in commands.filter_map(|i| i["id"].as_str()) {
|
||||
self.emit(
|
||||
thread,
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
t.items.clear();
|
||||
t.last_chunk = None;
|
||||
let error = t.error.take();
|
||||
@@ -1275,6 +1459,7 @@ impl CodexShim {
|
||||
t.naming |= name;
|
||||
(t.parent.clone(), (answer, error), name)
|
||||
};
|
||||
self.watch_terminals(parent.as_deref().unwrap_or(thread));
|
||||
if name {
|
||||
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
|
||||
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
|
||||
|
||||
@@ -1020,10 +1020,12 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
// Older recordings predate config inspection, skill discovery, thread naming and
|
||||
// background terminals; play an unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|
||||
|| method.starts_with("thread/backgroundTerminals/");
|
||||
if unrecorded && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -1163,6 +1165,60 @@ impl Handler for TrustServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forks a thread holding two finished turns and one cut off by the fork.
|
||||
#[derive(Default)]
|
||||
struct ForkServer {
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for ForkServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" | "thread/rollback" => Ok(json!({})),
|
||||
"model/list" | "skills/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
|
||||
{"id": "t1", "status": "completed"},
|
||||
{"id": "t2", "status": "completed"},
|
||||
{"id": "t3", "status": "interrupted"},
|
||||
]}})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
|
||||
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
|
||||
let server = Arc::new(ForkServer::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(Arc::new(Client::default()), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let params = json!({"cwd": "/tmp", "sessionId": "source", "mcpServers": [],
|
||||
"_meta": {"openidea": {"forkTurns": turns}}});
|
||||
let reply = request(&acp, "session/fork", params).await.unwrap();
|
||||
assert_eq!(reply["sessionId"], "copy");
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
|
||||
let rollbacks: Vec<Value> =
|
||||
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
|
||||
assert_eq!(
|
||||
rollbacks,
|
||||
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
|
||||
);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
@@ -1244,7 +1300,10 @@ async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
let init = result(&results, "initialize").as_ref().unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["loadSession"], true);
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
|
||||
assert_eq!(
|
||||
init["agentCapabilities"]["_meta"]["openidea"],
|
||||
json!({"rollback": true, "steer": true, "backgroundTasks": true})
|
||||
);
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let new = result(&results, "new").as_ref().unwrap();
|
||||
let categories: Vec<&str> =
|
||||
@@ -2216,3 +2275,179 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/// A codex whose background terminals listings come from `pages` (an empty list after
|
||||
/// them); `None` answers like a codex without the method.
|
||||
struct TerminalServer {
|
||||
pages: Mutex<VecDeque<Value>>,
|
||||
supported: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl TerminalServer {
|
||||
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
|
||||
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
|
||||
}
|
||||
|
||||
fn calls_of(&self, method: &str) -> Vec<Value> {
|
||||
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for TerminalServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
"thread/unsubscribe" => Ok(json!({})),
|
||||
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
|
||||
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
|
||||
}
|
||||
"thread/backgroundTerminals/list" => {
|
||||
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
|
||||
}
|
||||
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
|
||||
"thread/backgroundTerminals/clean" => Ok(json!({})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal(process: &str, command: &str) -> Value {
|
||||
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
|
||||
}
|
||||
|
||||
/// A session over a codex playing `server`; the codex peer and the ACP peer.
|
||||
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server, Framing::Lines);
|
||||
let acp = attach(client, |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
let init = request(&acp, "initialize", json!({})).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
|
||||
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
|
||||
(native, acp)
|
||||
}
|
||||
|
||||
fn shown_tasks(client: &Client) -> Vec<Value> {
|
||||
client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
|
||||
.map(|u| u["tasks"].clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
for _ in 0..200 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
|
||||
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
|
||||
assert_eq!(
|
||||
shown_tasks(&client),
|
||||
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
|
||||
);
|
||||
let listed = server.calls_of("thread/backgroundTerminals/list").len();
|
||||
assert!(listed >= 4, "listed until none ran, got {listed}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
|
||||
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running; 1000], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
|
||||
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
|
||||
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
|
||||
acp.kill();
|
||||
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_a_session_stops_its_background_terminals() {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client).await;
|
||||
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
|
||||
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
|
||||
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
|
||||
assert!(clean < unsubscribe);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_codex_without_background_terminals_reports_none() {
|
||||
let server = TerminalServer::new(Vec::new(), false);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
|
||||
assert!(shown_tasks(&client).is_empty());
|
||||
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
|
||||
for (status, settled) in [("completed", true), ("interrupted", false)] {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server, client.clone()).await;
|
||||
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
|
||||
"cwd": "/w", "status": "inProgress", "commandActions": []});
|
||||
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
|
||||
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let updates: Vec<Value> = client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
|
||||
.collect();
|
||||
let expected = if settled {
|
||||
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(updates, expected, "turn {status}");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -881,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One page of `thread/backgroundTerminals/list`: the running terminals as
|
||||
/// `(processId, description)`.
|
||||
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
|
||||
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
data.iter()
|
||||
.filter_map(|t| {
|
||||
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
|
||||
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
|
||||
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
|
||||
Some((process.to_owned(), description))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
|
||||
fn shell_unwrapped(argv: &[&str]) -> String {
|
||||
match argv {
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//!
|
||||
//! A shim speaks ACP v1 as the agent side, plus:
|
||||
//! - `agentCapabilities.sessionCapabilities.fork` and `session/fork`
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy);
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy). With
|
||||
//! `_meta.openidea.forkTurns`, the copy keeps only the source's first that many turns;
|
||||
//! the result repeats it in its `_meta.openidea.forkTurns` when the shim cut the copy;
|
||||
//! - `agentCapabilities._meta.openidea.rollback` and `_openidea/rollback`
|
||||
//! (`{ sessionId, turns }`: drops the last `turns` user turns from the session);
|
||||
//! - `agentCapabilities._meta.openidea.steer` and `_openidea/steer`
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use base64::Engine as _;
|
||||
use ide_core::settings::{AgentMcpServer, AgentPluginEntryPolicy, AgentPluginSettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -46,6 +47,37 @@ const MARKETPLACE_MANIFEST_PATHS: &[&str] = &[
|
||||
".github/plugin/marketplace.json",
|
||||
];
|
||||
|
||||
/// Maximum local icon file size inlined as a base64 `data:` URI (64 KiB).
|
||||
const MAX_INLINE_ICON_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Conventional icon file locations checked inside a plugin directory when no explicit icon is declared.
|
||||
const CONVENTIONAL_ICON_PATHS: &[&str] = &[
|
||||
".claude-plugin/icon.png",
|
||||
".claude-plugin/icon.svg",
|
||||
".claude-plugin/icon.webp",
|
||||
".plugin/icon.png",
|
||||
".plugin/icon.svg",
|
||||
".plugin/icon.webp",
|
||||
".github/plugin/icon.png",
|
||||
".github/plugin/icon.svg",
|
||||
".github/plugin/icon.webp",
|
||||
".codex-plugin/icon.png",
|
||||
".codex-plugin/icon.svg",
|
||||
".codex-plugin/icon.webp",
|
||||
"assets/logo.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.webp",
|
||||
"assets/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.webp",
|
||||
"icon.png",
|
||||
"icon.svg",
|
||||
"icon.webp",
|
||||
"logo.png",
|
||||
"logo.svg",
|
||||
"logo.webp",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstalledPluginProvenance {
|
||||
@@ -1461,6 +1493,8 @@ pub fn projected_mcp_servers(
|
||||
unapproved: false,
|
||||
plugin_id: Some(state.plugin.id.clone()),
|
||||
plugin_name: Some(state.plugin.display_name.clone()),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1551,6 +1585,7 @@ pub fn browse_marketplace(
|
||||
let tree = fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
|
||||
|
||||
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref };
|
||||
let tree_paths: HashSet<&str> = tree.tree.iter().filter(|e| e.kind == "blob").map(|e| e.path.as_str()).collect();
|
||||
|
||||
// 1. Check for a `marketplace.json` manifest in the repository (under `parsed.subpath` if given, or root).
|
||||
let sub_prefix = parsed.subpath.as_deref().map(|s| format!("{s}/")).unwrap_or_default();
|
||||
@@ -1561,10 +1596,9 @@ pub fn browse_marketplace(
|
||||
let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("marketplace.json is not UTF-8"))?;
|
||||
let (mkt_name, candidates) = parse_marketplace_json_remote(
|
||||
&text,
|
||||
&parsed.owner,
|
||||
&parsed.repo,
|
||||
&git_ref,
|
||||
target,
|
||||
parsed.subpath.as_deref(),
|
||||
&tree_paths,
|
||||
user_home,
|
||||
workspace_root,
|
||||
)?;
|
||||
@@ -1614,6 +1648,7 @@ pub fn browse_marketplace(
|
||||
let mut description = String::new();
|
||||
let mut author = None;
|
||||
let mut keywords = Vec::new();
|
||||
let mut manifest_val: Option<Value> = None;
|
||||
|
||||
for (manifest_rel, _) in MANIFEST_CANDIDATES {
|
||||
let p = format!("{prefix}{manifest_rel}");
|
||||
@@ -1644,10 +1679,18 @@ pub fn browse_marketplace(
|
||||
if keywords.is_empty() {
|
||||
keywords = extract_string_array(val.get("keywords"));
|
||||
}
|
||||
manifest_val = Some(val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let (icon_url, icon_dark_url) = resolve_remote_plugin_icons(
|
||||
manifest_val.as_ref(),
|
||||
Some((&parsed.owner, &parsed.repo, &git_ref, root_dir.as_str(), Some(&tree_paths))),
|
||||
None,
|
||||
Some(&parsed.owner),
|
||||
);
|
||||
|
||||
let source_spec = if root_dir.is_empty() {
|
||||
format!("{}/{}#{git_ref}", parsed.owner, parsed.repo)
|
||||
} else {
|
||||
@@ -1661,6 +1704,8 @@ pub fn browse_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath: root_dir,
|
||||
keywords,
|
||||
@@ -1717,7 +1762,7 @@ pub fn preview_plugin(
|
||||
}
|
||||
let scanned = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
|
||||
let inspected =
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"))?;
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"), None)?;
|
||||
let marketplace_source = marketplace
|
||||
.and_then(|name| local_marketplace_source(&local_dir, name))
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
@@ -1746,6 +1791,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1764,7 +1811,11 @@ pub fn preview_plugin(
|
||||
let scanned =
|
||||
fetch_and_scan_subtree(fetcher, target, &subpath, None, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin", cancel)?;
|
||||
let fallback_name = subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(&parsed.repo);
|
||||
let inspected = inspect_fetched_subtree(&scanned, fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(
|
||||
&scanned,
|
||||
fallback_name,
|
||||
Some((&parsed.owner, &parsed.repo, &commit_sha, scanned.normalized_subpath.as_str())),
|
||||
)?;
|
||||
let targets = plugin_install_targets(
|
||||
&inspected.name,
|
||||
inspected.version.as_deref(),
|
||||
@@ -1791,6 +1842,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1919,7 +1972,7 @@ pub fn install_plugin(
|
||||
));
|
||||
}
|
||||
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name, None)?;
|
||||
if let Some(reason) = plugin_install_blocker(
|
||||
source,
|
||||
&inspected.formats,
|
||||
@@ -2057,16 +2110,23 @@ struct InspectedSubtreeMeta {
|
||||
display_name: String,
|
||||
version: Option<String>,
|
||||
description: String,
|
||||
icon_url: Option<String>,
|
||||
icon_dark_url: Option<String>,
|
||||
formats: Vec<AgentPluginFormat>,
|
||||
capabilities: AgentPluginCapabilities,
|
||||
}
|
||||
|
||||
fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> IdeResult<InspectedSubtreeMeta> {
|
||||
fn inspect_fetched_subtree(
|
||||
scanned: &FetchedSubtree,
|
||||
fallback_name: &str,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> IdeResult<InspectedSubtreeMeta> {
|
||||
let mut formats = Vec::new();
|
||||
let mut name: Option<String> = None;
|
||||
let mut display_name: Option<String> = None;
|
||||
let mut version: Option<String> = None;
|
||||
let mut description = String::new();
|
||||
let mut primary_manifest: Option<Value> = None;
|
||||
let mut native_harnesses = BTreeSet::new();
|
||||
|
||||
let file_map: BTreeMap<String, &[u8]> =
|
||||
@@ -2108,6 +2168,9 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
{
|
||||
description = d.trim().to_owned();
|
||||
}
|
||||
if primary_manifest.is_none() {
|
||||
primary_manifest = Some(val);
|
||||
}
|
||||
}
|
||||
|
||||
let mut skill_names = Vec::new();
|
||||
@@ -2158,12 +2221,15 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
|
||||
let final_name = name.unwrap_or_else(|| sanitize_plugin_slug(fallback_name));
|
||||
let final_display = display_name.unwrap_or_else(|| final_name.clone());
|
||||
let (icon_url, icon_dark_url) = resolve_subtree_icons(primary_manifest.as_ref(), &file_map, remote_repo);
|
||||
|
||||
Ok(InspectedSubtreeMeta {
|
||||
name: final_name,
|
||||
display_name: final_display,
|
||||
version,
|
||||
description,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
formats,
|
||||
capabilities: AgentPluginCapabilities {
|
||||
skill_count: skill_names.len() as u32,
|
||||
@@ -3654,6 +3720,13 @@ fn browse_local_marketplace(
|
||||
if source_spec.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let local_plugin_dir = Path::new(&source_spec);
|
||||
let (icon_url, icon_dark_url) = if local_plugin_dir.is_dir() {
|
||||
resolve_local_plugin_icons(Some(item), local_plugin_dir)
|
||||
} else {
|
||||
let ext_repo = source_spec.split('#').next();
|
||||
resolve_remote_plugin_icons(Some(item), None, ext_repo, None)
|
||||
};
|
||||
let (already_user, already_ws) =
|
||||
plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
candidates.push(AgentMarketplaceCandidate {
|
||||
@@ -3663,6 +3736,8 @@ fn browse_local_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3685,6 +3760,11 @@ fn browse_local_marketplace(
|
||||
// Direct local plugin folder. The source only selects how metadata is read; the target
|
||||
// harness is chosen at install time.
|
||||
if let Some(plug) = inspect_plugin_dir(local_path, AgentPluginSource::CopilotUser, McpScope::User, None, true) {
|
||||
let manifest_val = MANIFEST_CANDIDATES.iter().find_map(|(rel, _)| {
|
||||
let text = std::fs::read_to_string(local_path.join(rel)).ok()?;
|
||||
parse_jsonc(&text).ok()
|
||||
});
|
||||
let (icon_url, icon_dark_url) = resolve_local_plugin_icons(manifest_val.as_ref(), local_path);
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&plug.name, None, user_home, workspace_root);
|
||||
return Ok(AgentMarketplaceBrowseResult {
|
||||
source: raw_source.to_owned(),
|
||||
@@ -3700,6 +3780,8 @@ fn browse_local_marketplace(
|
||||
description: plug.description,
|
||||
author: plug.author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec: local_path.to_string_lossy().into_owned(),
|
||||
subpath: String::new(),
|
||||
keywords: Vec::new(),
|
||||
@@ -3836,13 +3918,13 @@ fn safe_marketplace_repo(raw: &str) -> Option<String> {
|
||||
|
||||
fn parse_marketplace_json_remote(
|
||||
text: &str,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
git_ref: &str,
|
||||
target: RepoRef<'_>,
|
||||
base_subpath: Option<&str>,
|
||||
tree_paths: &HashSet<&str>,
|
||||
user_home: Option<&Path>,
|
||||
workspace_root: Option<&Path>,
|
||||
) -> IdeResult<(String, Vec<AgentMarketplaceCandidate>)> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
let val = parse_jsonc(text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
|
||||
let mkt_name =
|
||||
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
|
||||
@@ -3872,7 +3954,7 @@ fn parse_marketplace_json_remote(
|
||||
let author = extract_author(item);
|
||||
let keywords = extract_string_array(item.get("keywords"));
|
||||
|
||||
let (source_spec, subpath) = match item.get("source") {
|
||||
let (source_spec, subpath, ext_repo_owner, in_marketplace_repo) = match item.get("source") {
|
||||
Some(Value::String(rel)) => {
|
||||
let Some(clean) = safe_marketplace_subpath(rel) else { continue };
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
@@ -3891,7 +3973,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
Some(Value::Object(obj)) => match obj.get("source").and_then(Value::as_str).unwrap_or_default() {
|
||||
"local" => {
|
||||
@@ -3916,7 +3998,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
"github" => {
|
||||
let Some(ext_repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) else {
|
||||
@@ -3926,9 +4008,9 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, String::new())
|
||||
(spec, String::new(), Some(ext_repo), false)
|
||||
}
|
||||
"git-subdir" => {
|
||||
let Some(ext_repo) = obj
|
||||
@@ -3949,15 +4031,19 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, sub)
|
||||
(spec, sub, Some(ext_repo), false)
|
||||
}
|
||||
_ => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let in_repo_ctx = in_marketplace_repo.then_some((owner, repo, git_ref, subpath.as_str(), Some(tree_paths)));
|
||||
let (icon_url, icon_dark_url) =
|
||||
resolve_remote_plugin_icons(Some(item), in_repo_ctx, ext_repo_owner.as_deref(), Some(owner));
|
||||
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
out.push(AgentMarketplaceCandidate {
|
||||
name,
|
||||
@@ -3966,6 +4052,8 @@ fn parse_marketplace_json_remote(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3977,6 +4065,302 @@ fn parse_marketplace_json_remote(
|
||||
Ok((mkt_name, out))
|
||||
}
|
||||
|
||||
fn safe_https_icon_url(raw: &str) -> Option<String> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed.strip_prefix("https://")?;
|
||||
if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return None;
|
||||
}
|
||||
let authority = rest.split('/').next().unwrap_or_default();
|
||||
if authority.is_empty() || authority.contains('@') {
|
||||
return None;
|
||||
}
|
||||
Some(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn icon_mime_for_path(path: &str) -> Option<&'static str> {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".png") {
|
||||
Some("image/png")
|
||||
} else if lower.ends_with(".svg") {
|
||||
Some("image/svg+xml")
|
||||
} else if lower.ends_with(".webp") {
|
||||
Some("image/webp")
|
||||
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
|
||||
Some("image/jpeg")
|
||||
} else if lower.ends_with(".ico") {
|
||||
Some("image/x-icon")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_data_uri(mime: &str, bytes: &[u8]) -> Option<String> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_INLINE_ICON_BYTES {
|
||||
return None;
|
||||
}
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
Some(format!("data:{mime};base64,{b64}"))
|
||||
}
|
||||
|
||||
fn percent_encode_path_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.bytes() {
|
||||
let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
|
||||
if unreserved {
|
||||
out.push(byte as char);
|
||||
} else {
|
||||
out.push('%');
|
||||
let hi = byte >> 4;
|
||||
let lo = byte & 0x0f;
|
||||
out.push(if hi < 10 { (b'0' + hi) as char } else { (b'A' + hi - 10) as char });
|
||||
out.push(if lo < 10 { (b'0' + lo) as char } else { (b'A' + lo - 10) as char });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn github_raw_file_url(owner: &str, repo: &str, git_ref: &str, repo_path: &str) -> String {
|
||||
let enc_ref = git_ref.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
let enc_path = repo_path.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
format!("https://raw.githubusercontent.com/{owner}/{repo}/{enc_ref}/{enc_path}")
|
||||
}
|
||||
|
||||
fn is_valid_github_owner(owner: &str) -> bool {
|
||||
!owner.is_empty()
|
||||
&& owner.len() <= 39
|
||||
&& owner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
&& !owner.starts_with('-')
|
||||
&& !owner.ends_with('-')
|
||||
}
|
||||
|
||||
fn github_owner_from_url(raw: &str) -> Option<&str> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed
|
||||
.strip_prefix("https://github.com/")
|
||||
.or_else(|| trimmed.strip_prefix("http://github.com/"))
|
||||
.or_else(|| trimmed.strip_prefix("https://www.github.com/"))?;
|
||||
let owner = rest.split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_from_repo_slug(slug: &str) -> Option<&str> {
|
||||
let owner = slug.trim().split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_avatar(val: Option<&Value>, ext_repo: Option<&str>, fallback_owner: Option<&str>) -> Option<String> {
|
||||
if let Some(owner) = ext_repo.and_then(github_owner_from_repo_slug) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
if let Some(v) = val {
|
||||
let candidate_urls = [
|
||||
v.get("repository").and_then(|r| r.get("url").or(Some(r))).and_then(Value::as_str),
|
||||
v.get("homepage").and_then(Value::as_str),
|
||||
v.pointer("/author/url").and_then(Value::as_str),
|
||||
];
|
||||
for raw_url in candidate_urls.into_iter().flatten() {
|
||||
if let Some(owner) = github_owner_from_url(raw_url) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(owner) = fallback_owner.filter(|o| is_valid_github_owner(o)) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Resolves explicit icon references `(light, dark)` from a marketplace entry or plugin manifest,
|
||||
/// skipping any invalid/unresolvable entries before picking light/dark variants.
|
||||
fn resolve_manifest_icon_refs(
|
||||
val: &Value,
|
||||
resolve: impl Fn(&str) -> Option<String>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(icons) = val.get("icons").and_then(Value::as_array) {
|
||||
let mut light: Option<String> = None;
|
||||
let mut dark: Option<String> = None;
|
||||
let mut unthemed: Option<String> = None;
|
||||
let mut first: Option<String> = None;
|
||||
for item in icons {
|
||||
let Some(obj) = item.as_object() else { continue };
|
||||
let Some(src) = obj.get("src").and_then(Value::as_str).and_then(&resolve) else {
|
||||
continue;
|
||||
};
|
||||
if first.is_none() {
|
||||
first = Some(src.clone());
|
||||
}
|
||||
match obj.get("theme").and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() {
|
||||
Some("light") if light.is_none() => light = Some(src),
|
||||
Some("dark") if dark.is_none() => dark = Some(src),
|
||||
None | Some("") if unthemed.is_none() => unthemed = Some(src),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let resolved_light = light.or_else(|| unthemed.clone()).or(first);
|
||||
if resolved_light.is_some() {
|
||||
let resolved_dark = dark.or(unthemed).filter(|d| Some(d.as_str()) != resolved_light.as_deref());
|
||||
return (resolved_light, resolved_dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(icon) = val.get("icon") {
|
||||
if let Some(resolved) = icon.as_str().and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
if let Some(obj) = icon.as_object() {
|
||||
let light = obj.get("light").and_then(Value::as_str).and_then(&resolve);
|
||||
let dark = obj.get("dark").and_then(Value::as_str).and_then(&resolve);
|
||||
if light.is_some() || dark.is_some() {
|
||||
let eff_light = light.or_else(|| dark.clone());
|
||||
let eff_dark = dark.filter(|d| Some(d.as_str()) != eff_light.as_deref());
|
||||
return (eff_light, eff_dark);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for candidate in [
|
||||
val.get("logo"),
|
||||
val.pointer("/interface/logo"),
|
||||
val.pointer("/interface/composerIcon"),
|
||||
val.get("iconUrl"),
|
||||
val.get("icon_url"),
|
||||
] {
|
||||
if let Some(resolved) = candidate.and_then(Value::as_str).and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
}
|
||||
|
||||
(None, None)
|
||||
}
|
||||
|
||||
fn join_repo_subpath(subpath: &str, rel: &str) -> String {
|
||||
if subpath.is_empty() { rel.to_owned() } else { format!("{subpath}/{rel}") }
|
||||
}
|
||||
|
||||
type RemoteRepoIconContext<'a> = (&'a str, &'a str, &'a str, &'a str, Option<&'a HashSet<&'a str>>);
|
||||
|
||||
fn resolve_remote_icon_ref(raw: &str, in_repo: Option<RemoteRepoIconContext<'_>>) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let (owner, repo, git_ref, subpath, tree_paths) = in_repo?;
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
icon_mime_for_path(clean)?;
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
if let Some(paths) = tree_paths
|
||||
&& !paths.contains(full.as_str())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(github_raw_file_url(owner, repo, git_ref, &full))
|
||||
}
|
||||
|
||||
fn resolve_remote_plugin_icons(
|
||||
val: Option<&Value>,
|
||||
in_repo: Option<RemoteRepoIconContext<'_>>,
|
||||
ext_repo: Option<&str>,
|
||||
fallback_owner: Option<&str>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_remote_icon_ref(r, in_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((owner, repo, git_ref, subpath, Some(tree_paths))) = in_repo {
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
if tree_paths.contains(full.as_str()) {
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, ext_repo, fallback_owner), None)
|
||||
}
|
||||
|
||||
fn resolve_local_icon_ref(raw: &str, plugin_dir: &Path) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let path = contained_join(plugin_dir, clean).ok()?;
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_INLINE_ICON_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(&path).ok()?;
|
||||
encode_data_uri(mime, &bytes)
|
||||
}
|
||||
|
||||
fn resolve_local_plugin_icons(val: Option<&Value>, plugin_dir: &Path) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_local_icon_ref(r, plugin_dir));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(data_uri) = resolve_local_icon_ref(rel, plugin_dir) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, None, None), None)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icon_ref(
|
||||
raw: &str,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let bytes = file_map.get(clean)?;
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
return Some(github_raw_file_url(owner, repo, git_ref, &full));
|
||||
}
|
||||
encode_data_uri(mime, bytes)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icons(
|
||||
val: Option<&Value>,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_subtree_icon_ref(r, file_map, remote_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(bytes) = file_map.get(*rel)
|
||||
&& let Some(mime) = icon_mime_for_path(rel)
|
||||
{
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
if let Some(data_uri) = encode_data_uri(mime, bytes) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fallback_owner = remote_repo.map(|(owner, _, _, _)| owner);
|
||||
(github_owner_avatar(val, None, fallback_owner), None)
|
||||
}
|
||||
|
||||
const INSTALL_SOURCES: [AgentPluginSource; 4] = [
|
||||
AgentPluginSource::ClaudeUser,
|
||||
AgentPluginSource::CopilotUser,
|
||||
@@ -5553,7 +5937,7 @@ mod tests {
|
||||
|
||||
let on_disk = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
|
||||
let scanned = scan_local_subtree(&dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked", None).unwrap();
|
||||
for hooks in [&on_disk.capabilities.hook_files, &preview.capabilities.hook_files] {
|
||||
assert!(hooks.contains(&".claude-plugin/plugin.json#hooks".to_owned()), "{hooks:?}");
|
||||
assert!(hooks.contains(&"config/copilot-hooks.json".to_owned()), "{hooks:?}");
|
||||
@@ -5698,19 +6082,19 @@ mod tests {
|
||||
{"name":"gh-bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#x"}},
|
||||
{"name":"sub-bad","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}}
|
||||
]}"##;
|
||||
let (_, candidates) =
|
||||
parse_marketplace_json_remote(manifest, "acme", "repo", "main", None, None, None).unwrap();
|
||||
let empty_tree = HashSet::new();
|
||||
let target = RepoRef { owner: "acme", repo: "repo", git_ref: "main" };
|
||||
let (_, candidates) = parse_marketplace_json_remote(manifest, target, None, &empty_tree, None, None).unwrap();
|
||||
let specs: Vec<_> = candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect();
|
||||
assert_eq!(specs, [("ok", "acme/repo/plugins/ok#main"), ("gh-ok", "acme/tools#v1.2")]);
|
||||
assert!(
|
||||
parse_marketplace_json_remote(
|
||||
r#"{"metadata":{"pluginRoot":"../up"},"plugins":[]}"#,
|
||||
"acme",
|
||||
"repo",
|
||||
"main",
|
||||
target,
|
||||
None,
|
||||
&empty_tree,
|
||||
None,
|
||||
None,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
@@ -5828,4 +6212,112 @@ mod tests {
|
||||
&& plugin.scope == McpScope::Workspace
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marketplace_browse_and_preview_resolve_explicit_bundled_local_and_avatar_icons() {
|
||||
let cancel = CancellationToken::new();
|
||||
let marketplace_json = br#"{
|
||||
"name": "claude-plugins-official",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "themed-ext",
|
||||
"description": "Explicit light/dark icons",
|
||||
"source": "./plugins/themed-ext",
|
||||
"icons": [
|
||||
{ "src": "javascript:alert(1)", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/light.png", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/dark.png", "theme": "dark" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "champion-kit",
|
||||
"description": "Bundled .claude-plugin/icon.png",
|
||||
"source": "./plugins/champion-kit"
|
||||
},
|
||||
{
|
||||
"name": "adobe-for-creativity",
|
||||
"description": "External git-subdir plugin",
|
||||
"source": {
|
||||
"source": "git-subdir",
|
||||
"url": "https://github.com/adobe/skills.git",
|
||||
"path": "plugins/creative-cloud/adobe-for-creativity"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "first-party",
|
||||
"description": "Falls back to marketplace repo owner avatar",
|
||||
"source": "./plugins/first-party"
|
||||
},
|
||||
{
|
||||
"name": "unsafe-icon",
|
||||
"description": "Rejects http:// and escaping relative paths",
|
||||
"source": "./plugins/unsafe-icon",
|
||||
"icon": "../escape.png"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let gh = FakeGitHub::new(
|
||||
&[
|
||||
(".claude-plugin/marketplace.json", marketplace_json.as_slice(), "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/plugin.json", br#"{"name":"champion-kit"}"#, "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/icon.png", b"\x89PNG\r\n\x1a\n", "100644"),
|
||||
("plugins/first-party/.claude-plugin/plugin.json", br#"{"name":"first-party"}"#, "100644"),
|
||||
],
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
);
|
||||
|
||||
let browse = browse_marketplace(&gh, "anthropics/claude-plugins-official", None, None, &cancel).unwrap();
|
||||
let by = |name: &str| browse.candidates.iter().find(|c| c.name == name).unwrap();
|
||||
|
||||
assert_eq!(by("themed-ext").icon_url.as_deref(), Some("https://cdn.example.com/light.png"));
|
||||
assert_eq!(by("themed-ext").icon_dark_url.as_deref(), Some("https://cdn.example.com/dark.png"));
|
||||
assert_eq!(
|
||||
by("champion-kit").icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
assert_eq!(by("adobe-for-creativity").icon_url.as_deref(), Some("https://github.com/adobe.png?size=64"));
|
||||
assert_eq!(by("first-party").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
assert_eq!(by("unsafe-icon").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
|
||||
// Remote preview also resolves bundled icons to raw.githubusercontent.com at commit_sha.
|
||||
let remote_preview = preview_plugin(
|
||||
&gh,
|
||||
"anthropics/claude-plugins-official/plugins/champion-kit#main",
|
||||
None,
|
||||
Some("claude-plugins-official"),
|
||||
None,
|
||||
None,
|
||||
&cancel,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
remote_preview.icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
|
||||
// Local marketplace & preview inline small local PNG icons as data URIs.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let local_plugin = tmp.path().join("my-local-plugin");
|
||||
write(
|
||||
&local_plugin.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"my-local-plugin","interface":{"logo":"./assets/logo.png"}}"#,
|
||||
);
|
||||
std::fs::create_dir_all(local_plugin.join("assets")).unwrap();
|
||||
std::fs::write(local_plugin.join("assets/logo.png"), b"\x89PNG\r\n\x1a\n").unwrap();
|
||||
|
||||
let local_browse = browse_marketplace(&gh, local_plugin.to_str().unwrap(), None, None, &cancel).unwrap();
|
||||
assert_eq!(local_browse.candidates.len(), 1);
|
||||
assert!(
|
||||
local_browse.candidates[0].icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,"))
|
||||
);
|
||||
|
||||
let local_preview =
|
||||
preview_plugin(&gh, local_plugin.to_str().unwrap(), None, None, None, None, &cancel).unwrap();
|
||||
assert!(local_preview.icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,")));
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -230,7 +231,9 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
if let Some(builtin) = builtin_spec(&self.id)
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
@@ -597,6 +600,13 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
|
||||
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
|
||||
/// to a registry install.
|
||||
fn registry_uses_separate_binary(id: &str) -> bool {
|
||||
id == "antigravity-acp"
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
@@ -1064,7 +1074,9 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
Some(existing) => {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
}
|
||||
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
|
||||
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
|
||||
// `driver`; upgrade them in place to the native headless driver (which
|
||||
@@ -1133,6 +1145,55 @@ mod tests {
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antigravity_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("antigravity-acp").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
assert!(!is_builtin("antigravity-acp"));
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
|
||||
assert!(info.command_editable);
|
||||
assert_eq!(info.additional_args, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
|
||||
}
|
||||
.write(&dir.path().join("antigravity-acp.toml"))
|
||||
.unwrap();
|
||||
|
||||
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
|
||||
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
|
||||
assert_eq!(describe(®).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
|
||||
assert!(reg.login_launch(dir.path(), None).is_none());
|
||||
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
|
||||
assert_eq!(terminal_launch.program, bin);
|
||||
assert_eq!(terminal_launch.args, ["--login"]);
|
||||
|
||||
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
|
||||
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(builtin.source, AgentSource::Builtin);
|
||||
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1185,6 +1246,7 @@ mod tests {
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
@@ -1311,10 +1373,10 @@ mod tests {
|
||||
for p in &defaults {
|
||||
assert_eq!(p.source, AgentSource::Builtin);
|
||||
assert!(p.default_program.is_some());
|
||||
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
|
||||
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
|
||||
assert_eq!(
|
||||
p.command_read_only_reason,
|
||||
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
);
|
||||
}
|
||||
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
|
||||
|
||||
@@ -296,6 +296,24 @@ pub fn discover_skills_with_agent_plugins(
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
|
||||
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
|
||||
///
|
||||
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
|
||||
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
|
||||
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
|
||||
/// shallowest to deepest and deduplicated by canonical path.
|
||||
pub fn discover_skills_with_indexed_files(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
indexed_skill_files: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -321,6 +339,13 @@ pub fn discover_skills_with_agent_plugins(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
|
||||
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
@@ -413,6 +438,74 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
|
||||
///
|
||||
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
|
||||
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
|
||||
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
|
||||
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
|
||||
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
|
||||
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
|
||||
if workspaces.is_empty() || indexed_skill_files.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
|
||||
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
|
||||
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
|
||||
for file in indexed_skill_files {
|
||||
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
|
||||
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
|
||||
if rel.components().any(|c| match c {
|
||||
std::path::Component::Normal(seg) => {
|
||||
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
|
||||
}
|
||||
_ => true,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if !pkg_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
candidates.push((rel.components().count(), pkg_root));
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
candidates.dedup_by(|a, b| a.1 == b.1);
|
||||
candidates.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
|
||||
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
|
||||
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
|
||||
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
|
||||
return None;
|
||||
}
|
||||
let mut cur = skill_md.parent()?;
|
||||
for _ in 0..=2 {
|
||||
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
|
||||
&& let Some(dot_dir) = cur.parent()
|
||||
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
|
||||
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
|
||||
&& let Some(pkg_root) = dot_dir.parent()
|
||||
{
|
||||
return Some(pkg_root.to_path_buf());
|
||||
}
|
||||
cur = cur.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
|
||||
let pick_shortest =
|
||||
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
|
||||
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
|
||||
if let Some(rel) = pick_shortest(&mut direct) {
|
||||
return Some(rel);
|
||||
}
|
||||
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
|
||||
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
|
||||
pick_shortest(&mut canonical)
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
@@ -1469,4 +1562,65 @@ mod tests {
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
|
||||
let deep_grafana =
|
||||
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
|
||||
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
|
||||
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
|
||||
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
|
||||
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
|
||||
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
|
||||
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
|
||||
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
|
||||
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
|
||||
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
|
||||
|
||||
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
|
||||
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
|
||||
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
|
||||
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
|
||||
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
|
||||
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
|
||||
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
|
||||
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
|
||||
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
|
||||
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
|
||||
|
||||
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
|
||||
let shallow_only = discover_skills(&ws, None);
|
||||
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
|
||||
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
|
||||
|
||||
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
|
||||
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
|
||||
let indexed = vec![
|
||||
depth4_clash,
|
||||
depth3_clash,
|
||||
deep_clash,
|
||||
deep_grafana,
|
||||
deep_category,
|
||||
deep_named_skills,
|
||||
fixture_skill,
|
||||
hidden_dir_skill,
|
||||
target_dir_skill,
|
||||
];
|
||||
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
|
||||
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
|
||||
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
|
||||
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
|
||||
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
|
||||
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
|
||||
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
|
||||
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
|
||||
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
|
||||
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,8 @@ struct FakeAgent {
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The params of every `session/fork`, in order.
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// Cuts a fork at `_meta.openidea.forkTurns` itself, as the native agents do.
|
||||
cuts_forks: bool,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
@@ -230,7 +232,13 @@ impl Handler for FakeAgent {
|
||||
"session/fork" => {
|
||||
self.forks.lock().push(params.clone());
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
|
||||
let mut reply = json!({ "sessionId": requested.unwrap_or("s2") });
|
||||
if self.cuts_forks
|
||||
&& let Some(turns) = params.pointer("/_meta/openidea/forkTurns")
|
||||
{
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
@@ -3482,6 +3490,62 @@ fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forks_a_running_task_up_to_its_finished_turns() {
|
||||
for cuts_forks in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent { cuts_forks, ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
|
||||
// The running turn stays behind, whatever was asked for.
|
||||
for turns in [None, Some(2)] {
|
||||
let copy = mgr.fork(&task.id, turns).await.unwrap();
|
||||
assert_eq!(copy.status, AgentStatus::Ready);
|
||||
let entries = mgr.entries(©.id, None).unwrap();
|
||||
assert_eq!(turn_starts(&entries).len(), 1);
|
||||
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, .. } if text == "wait")));
|
||||
let pending = mgr.task(©.id).unwrap().state.lock().pending_rollback;
|
||||
assert_eq!(pending, if cuts_forks { 0 } else { 1 });
|
||||
assert_eq!(agent.forks.lock().last().unwrap().pointer("/_meta/openidea/forkTurns"), Some(&json!(1)));
|
||||
}
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Running);
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_running_first_turn_cannot_be_forked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
assert!(mgr.fork(&task.id, None).await.is_err());
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3578,6 +3642,79 @@ async fn imports_copilot_sessions_and_loads_their_history() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn session_calls(agent: &FakeAgent) -> Vec<String> {
|
||||
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
|
||||
}
|
||||
|
||||
/// Imports a claude session whose load fails, which leaves what a quit during the load leaves
|
||||
/// too: a task that holds the recorded session but no conversation.
|
||||
async fn import_without_history(dir: &Path) -> String {
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INTERNAL_ERROR, "Claude Code exited".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(dir, agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
plant_claude_session(&mgr, dir, NATIVE_SOURCE);
|
||||
let id = mgr.import_session("claude", NATIVE_SOURCE).unwrap().id;
|
||||
for _ in 0..300 {
|
||||
if !session_calls(&agent).is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(session_calls(&agent), ["session/load"]);
|
||||
assert_eq!(saved_task(&task_file(dir, &id)).unwrap().1, 0);
|
||||
id
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_imported_task_without_its_history_loads_it_when_shown() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let id = import_without_history(tmp.path()).await;
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
for _ in 0..300 {
|
||||
if !mgr.entries(&id, None).unwrap().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert!(matches!(&entries[0], AgentEntry::User { text, .. } if text == "earlier question"), "{entries:?}");
|
||||
assert_eq!(session_calls(&agent), ["session/load"], "loaded once, however often it is shown");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_history_load_leaves_the_new_session_to_the_user() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let id = import_without_history(tmp.path()).await;
|
||||
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INTERNAL_ERROR, "no conversation found".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.entries(&id, None).unwrap();
|
||||
for _ in 0..300 {
|
||||
if !session_calls(&agent).is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
mgr.entries(&id, None).unwrap();
|
||||
assert_eq!(session_calls(&agent), ["session/load"], "tried once in this run");
|
||||
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &id, AgentStatus::Failed).await;
|
||||
assert_eq!(session_calls(&agent), ["session/load", "session/load"], "no new session behind the user's back");
|
||||
assert!(mgr.entries(&id, None).unwrap().iter().any(|e| matches!(e,
|
||||
AgentEntry::Error { message } if message.contains("Send the message again"))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -6366,6 +6503,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
@@ -6382,6 +6521,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
]
|
||||
}));
|
||||
|
||||
+107
-111
@@ -1,112 +1,108 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
|
||||
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
|
||||
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
|
||||
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
|
||||
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
|
||||
@@ -0,0 +1,34 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
|
||||
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
|
||||
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
|
||||
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
|
||||
@@ -359,16 +359,14 @@ pub(super) fn maven_steps(
|
||||
};
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
}
|
||||
};
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
if module == top_dir {
|
||||
return Ok(vec![step(top, &[])]);
|
||||
if let Some(pl) = maven::module_selector(root, top, target) {
|
||||
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
|
||||
}
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
|
||||
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
|
||||
Ok(vec![step(top, &[])])
|
||||
}
|
||||
|
||||
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
@@ -571,6 +569,27 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let (Some(dir), Some(name), true) =
|
||||
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
|
||||
else {
|
||||
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
// Verbose output names the files it changed; verifying changes none.
|
||||
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
|
||||
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
|
||||
step.args.extend(options.iter().map(|o| (*o).to_owned()));
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
@@ -959,17 +978,7 @@ pub fn has_non_java_sources(module: &Path) -> bool {
|
||||
}
|
||||
|
||||
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
maven::reactor_projects(m, top)
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
@@ -995,7 +1004,7 @@ pub(crate) fn reactor_projects_of<'a>(
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
maven::reactor_for_dir(m, module)
|
||||
}
|
||||
|
||||
/// Launch module first, followed by its upstream modules in the same Maven reactor.
|
||||
@@ -2062,6 +2071,34 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_launch_uses_relative_module_selector() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
|
||||
);
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].cwd, root.join("parent"));
|
||||
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
|
||||
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -2231,4 +2268,60 @@ mod tests {
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_format_runs_on_the_given_solution_or_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
|
||||
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
|
||||
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
|
||||
}
|
||||
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
|
||||
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for args in [
|
||||
&["new", "console", "-n", "App", "-o", "App"][..],
|
||||
&["new", "sln", "-n", "Sln", "--format", "slnx"],
|
||||
&["new", "sln", "-n", "Classic", "--format", "sln"],
|
||||
&["sln", "Sln.slnx", "add", "App/App.csproj"],
|
||||
&["sln", "Classic.sln", "add", "App/App.csproj"],
|
||||
] {
|
||||
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
|
||||
}
|
||||
let source = root.join("App").join("中 A.cs");
|
||||
let messy = "class A{void M( ){var x=1;}}\n";
|
||||
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
|
||||
std::fs::write(&source, messy).unwrap();
|
||||
let run = |verify| {
|
||||
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
|
||||
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
|
||||
};
|
||||
let verified = run(true);
|
||||
assert!(!verified.success, "{target}");
|
||||
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
|
||||
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
|
||||
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(false).success, "{target}");
|
||||
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,15 +72,19 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
fn selection(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
reactor: &[&maven::MavenProject],
|
||||
affected: &HashSet<String>,
|
||||
) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.filter_map(|p| maven::module_selector(root, top, p))
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
@@ -130,8 +134,12 @@ pub(super) fn narrowed_maven_steps(
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
let pl = selection(root, top, &reactor, &affected);
|
||||
if pl.is_empty() {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
@@ -405,4 +413,36 @@ mod tests {
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_narrows_with_relative_module_selectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
|
||||
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "parent"));
|
||||
assert_eq!(pl_arg(&steps[0]), "../app,../common");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
}
|
||||
@@ -143,8 +143,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let module = subdir(root, &project.dir);
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
@@ -164,8 +163,7 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
|
||||
@@ -543,15 +543,11 @@ fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<Pa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
|
||||
fn debug_args(c: &CompilerConfig) -> Vec<String> {
|
||||
if c.debug == Some(false) {
|
||||
return vec!["-g:none".into()];
|
||||
}
|
||||
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
Some(level) => vec![format!("-g:{level}")],
|
||||
None => vec!["-g".into()],
|
||||
}
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
fn is_debug_option(arg: &str) -> bool {
|
||||
arg == "-g" || arg.starts_with("-g:")
|
||||
}
|
||||
|
||||
/// The JDK feature version of `release` / `source` (`1.8` → 8).
|
||||
@@ -587,7 +583,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
|
||||
args.push(format!("-proc:{proc}"));
|
||||
}
|
||||
args.extend(debug_args(&c));
|
||||
args.push("-g".into());
|
||||
if c.parameters == Some(true) {
|
||||
args.push("-parameters".into());
|
||||
}
|
||||
@@ -616,15 +612,19 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
}
|
||||
}
|
||||
for (key, value) in &c.compiler_arguments {
|
||||
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
|
||||
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
|
||||
if is_debug_option(&key) {
|
||||
continue;
|
||||
}
|
||||
args.push(key);
|
||||
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
|
||||
args.push(value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(argument) = &c.compiler_argument {
|
||||
args.extend(argument.split_whitespace().map(str::to_owned));
|
||||
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
|
||||
}
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
|
||||
args
|
||||
}
|
||||
|
||||
@@ -960,6 +960,7 @@ impl JavaBuild<'_> {
|
||||
for project in &reactor_model.projects {
|
||||
for test in [false, true] {
|
||||
let stamp = resource_stamp(project.set(test), cancel)?;
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
}
|
||||
@@ -1027,11 +1028,42 @@ impl JavaBuild<'_> {
|
||||
}));
|
||||
}
|
||||
for (project, test, stamp) in changed {
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Removes what the sources no longer have from a source set's output: the resources step
|
||||
/// copies and overwrites, it never deletes, so a file deleted from the sources would stay on
|
||||
/// the launch's classpath (a stale `META-INF/spring.factories` then fails the application).
|
||||
fn prune_resources(
|
||||
&self,
|
||||
dir: &Path,
|
||||
project: &ProjectModel,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
let expected = resource_outputs(set, cancel)?;
|
||||
let recorded: BTreeSet<PathBuf> = std::fs::read(state_path(dir, project, test, "resource-outputs"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
for stale in recorded.difference(&expected) {
|
||||
let _ = std::fs::remove_file(stale);
|
||||
// The folders a removed resource leaves empty are not part of the output either.
|
||||
let mut parent = stale.parent();
|
||||
while let Some(folder) = parent.filter(|d| d.starts_with(&set.output) && *d != set.output) {
|
||||
if std::fs::remove_dir(folder).is_err() {
|
||||
break;
|
||||
}
|
||||
parent = folder.parent();
|
||||
}
|
||||
}
|
||||
model::write_json(&state_path(dir, project, test, "resource-outputs"), &expected)
|
||||
}
|
||||
|
||||
/// Removes the classes of a source set and its record: the next build compiles it from scratch.
|
||||
fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
@@ -1228,5 +1260,35 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
|
||||
/// the root's target path, then the path under the root, filtered by its includes and excludes.
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
continue;
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -416,6 +416,104 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
/// #7743: a dependency's own dependencies come before its next sibling on the classpath, as in
|
||||
/// `mvn compile`, so of two artifacts with the same classes (`dom4j:dom4j` 1.x and
|
||||
/// `org.dom4j:dom4j` 2.x) javac sees the one Maven does.
|
||||
#[test]
|
||||
fn maven_classpath_lists_dependencies_in_maven_order() {
|
||||
let module = |name: &str, deps: &[&str]| {
|
||||
let deps: String = deps
|
||||
.iter()
|
||||
.map(|d| {
|
||||
format!("<dependency><groupId>t</groupId><artifactId>{d}</artifactId><version>1</version></dependency>")
|
||||
})
|
||||
.collect();
|
||||
format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId>\
|
||||
<version>1</version></parent><artifactId>{name}</artifactId><dependencies>{deps}</dependencies></project>"
|
||||
)
|
||||
};
|
||||
let root = ROOT_POM.replace(
|
||||
"<module>lib</module>",
|
||||
"<module>newdom</module><module>olddom</module><module>x</module><module>lib</module>",
|
||||
);
|
||||
let (newdom, olddom, x, lib) =
|
||||
(module("newdom", &[]), module("olddom", &[]), module("x", &["newdom"]), module("lib", &["x", "olddom"]));
|
||||
let Some(f) = Fixture::new(&[
|
||||
("pom.xml", &root),
|
||||
("newdom/pom.xml", &newdom),
|
||||
("olddom/pom.xml", &olddom),
|
||||
("x/pom.xml", &x),
|
||||
("lib/pom.xml", &lib),
|
||||
("newdom/src/main/java/d/Element.java", "package d;\npublic class Element { public void fresh() {} }\n"),
|
||||
("olddom/src/main/java/d/Element.java", "package d;\npublic class Element {}\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { void f() { new d.Element().fresh(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let built = f.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
let position = |name: &str| built.class_paths.iter().position(|p| *p == f.out(&format!("t.{name}/classes")));
|
||||
assert!(position("newdom") < position("olddom"), "{:?}", built.class_paths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_resources_to_the_output_paths_the_build_tool_writes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&root, "src/main/resources/app.properties", "a=1");
|
||||
write(&root, "src/main/resources/notes.txt", "n");
|
||||
write(&root, "src/main/resources/deep/app.properties", "b=2");
|
||||
let resources = root.join("src/main/resources");
|
||||
let output = root.join("out/classes");
|
||||
let set = SourceSet {
|
||||
output: output.clone(),
|
||||
resources: vec![
|
||||
ResourceRoot { directory: resources.clone(), ..Default::default() },
|
||||
// A `<targetPath>` and an `<includes>` pattern, as a POM can configure them.
|
||||
ResourceRoot {
|
||||
directory: resources,
|
||||
target_path: Some("META-INF".into()),
|
||||
includes: vec!["*.properties".into()],
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resource_outputs(&set, &CancellationToken::new()).unwrap(),
|
||||
BTreeSet::from([
|
||||
output.join("app.properties"),
|
||||
output.join("notes.txt"),
|
||||
output.join("deep/app.properties"),
|
||||
output.join("META-INF/app.properties"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletes_the_output_of_a_resource_removed_from_the_sources() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/main/resources/META-INF/spring.factories", "a.A\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/META-INF/spring.factories")).unwrap(), "a.A\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// A deleted resource leaves no copy behind: the launch would read a file the sources no longer have.
|
||||
fs::remove_file(f.root.join("app/src/main/resources/META-INF/spring.factories")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert!(!f.out("t.app/classes/META-INF/spring.factories").exists(), "the removed resource stays on the classpath");
|
||||
// The resource that is still there keeps its copy, and a launch with nothing changed runs nothing.
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -592,7 +690,7 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-g",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
@@ -607,6 +705,28 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_always_keep_debug_info() {
|
||||
// `<debug>false</debug>` makes Maven pass `-g:none`; the IDE's build still emits the line
|
||||
// numbers and variables the debugger needs (#7786).
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
debug: Some(false),
|
||||
debuglevel: Some("source".into()),
|
||||
compiler_args: vec!["-g:none".into(), "-Xlint:all".into()],
|
||||
compiler_argument: Some("-g:source -Xlint:none".into()),
|
||||
compiler_arguments: [("g:none".to_owned(), None)].into(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[], Path::new("/gen"), Some(21));
|
||||
let debug: Vec<_> = args.iter().filter(|a| a.starts_with("-g")).collect();
|
||||
assert_eq!(debug, ["-g"], "{args:?}");
|
||||
assert!(args.iter().any(|a| a == "-Xlint:all") && args.iter().any(|a| a == "-Xlint:none"), "{args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
|
||||
@@ -92,6 +92,100 @@ impl MavenProject {
|
||||
}
|
||||
}
|
||||
|
||||
/// All projects belonging to the Maven reactor rooted at `top`, traversed through `<modules>`.
|
||||
pub(crate) fn reactor_projects<'a>(m: &'a MavenModel, top: &'a MavenProject) -> Vec<&'a MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
fn reactor_for<'a>(m: &'a MavenModel, target: &'a MavenProject) -> &'a MavenProject {
|
||||
if !target.aggregated {
|
||||
return target;
|
||||
}
|
||||
let mut matches =
|
||||
m.projects.iter().filter(|top| !top.aggregated && reactor_projects(m, top).iter().any(|p| p.pom == target.pom));
|
||||
let first = matches.next();
|
||||
let ancestor = first
|
||||
.into_iter()
|
||||
.chain(matches)
|
||||
.filter(|top| top.dir.is_empty() || target.dir == top.dir || target.dir.starts_with(&format!("{}/", top.dir)))
|
||||
.max_by_key(|top| top.dir.len());
|
||||
ancestor.or(first).unwrap_or(target)
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `pom` (project-relative).
|
||||
pub(crate) fn reactor_for_pom<'a>(m: &'a MavenModel, pom: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.pom == pom).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `dir` (project-relative).
|
||||
pub(crate) fn reactor_for_dir<'a>(m: &'a MavenModel, dir: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.dir == dir).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// `/`-separated relative path from `from` to `to`, supporting sibling (`../app`) and parent (`..`)
|
||||
/// module layouts. Returns `None` when the paths do not share a root/drive.
|
||||
pub(crate) fn relative_module_path(from: &Path, to: &Path) -> Option<String> {
|
||||
use std::path::Component;
|
||||
let from = crate::gradle::normalize(from);
|
||||
let to = crate::gradle::normalize(to);
|
||||
let from_comps: Vec<_> = from.components().collect();
|
||||
let to_comps: Vec<_> = to.components().collect();
|
||||
let common = from_comps.iter().zip(&to_comps).take_while(|(a, b)| a == b).count();
|
||||
let mut parts = Vec::new();
|
||||
for comp in &from_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(_) => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
for comp in &to_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
|
||||
Component::ParentDir => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
Some(parts.join("/"))
|
||||
}
|
||||
|
||||
/// Maven `-pl` selector for `module` when invoked from reactor `top` (`None` when `module` is `top`).
|
||||
pub(crate) fn module_selector(root: &Path, top: &MavenProject, module: &MavenProject) -> Option<String> {
|
||||
if top.pom == module.pom {
|
||||
return None;
|
||||
}
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
let resolve_dir = |dir: &str| {
|
||||
let raw = if dir.is_empty() { base.clone() } else { base.join(dir) };
|
||||
dunce::canonicalize(&raw).unwrap_or(raw)
|
||||
};
|
||||
let from = resolve_dir(&top.dir);
|
||||
let to = resolve_dir(&module.dir);
|
||||
if let Some(rel) = relative_module_path(&from, &to)
|
||||
&& !rel.is_empty()
|
||||
{
|
||||
return Some(rel);
|
||||
}
|
||||
if !module.group_id.is_empty() && !module.artifact_id.is_empty() {
|
||||
Some(format!("{}:{}", module.group_id, module.artifact_id))
|
||||
} else if !module.artifact_id.is_empty() {
|
||||
Some(format!(":{}", module.artifact_id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MavenPlugin {
|
||||
@@ -1340,6 +1434,22 @@ pub fn external_pom_dirs(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Linked POMs inside the opened root that a folder scan doesn't reach: it stops at the
|
||||
/// first folder with a `pom.xml` and follows only that project's modules, so a POM linked
|
||||
/// below another Maven project's folder (a deployable module its parent doesn't list) is
|
||||
/// never found. jdtls imports this way.
|
||||
pub fn linked_poms_below_projects(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
linked_poms(root, linked)
|
||||
.into_iter()
|
||||
.filter(|pom| {
|
||||
let Some(dir) = pom.parent() else { return false };
|
||||
dir.starts_with(&base)
|
||||
&& dir.ancestors().skip(1).take_while(|d| d.starts_with(&base)).any(|d| is_pom_file(&d.join("pom.xml")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
type FileStamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
fn file_stamp(path: &Path) -> FileStamp {
|
||||
|
||||
@@ -110,27 +110,15 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
}
|
||||
fs::write(cache.join("artifact-id.txt"), id)?;
|
||||
if let Some(pom) = id.strip_prefix("maven:") {
|
||||
let p = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let projects = &model.maven.as_ref().unwrap().projects;
|
||||
let top = projects
|
||||
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let p = maven
|
||||
.projects
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
|
||||
})
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.unwrap_or(p);
|
||||
.find(|p| p.pom == pom && p.packaging == "war")
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
|
||||
let mut args = top.options.clone();
|
||||
if top.pom != p.pom {
|
||||
let module = root
|
||||
.join(&p.dir)
|
||||
.strip_prefix(root.join(&top.dir))
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
if let Some(module) = crate::maven::module_selector(root, top, p) {
|
||||
args.extend(["-pl".into(), module, "-am".into()]);
|
||||
}
|
||||
// help:evaluate runs once, in the reactor's first project. Query the selected
|
||||
@@ -316,4 +304,90 @@ mod tests {
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common", "app"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let a = artifacts(root, &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_eq!(a[0].id, "maven:app/pom.xml");
|
||||
|
||||
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
|
||||
let (probe, _) = plan.maven_project.as_ref().unwrap();
|
||||
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let settings =
|
||||
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
|
||||
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
|
||||
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_independent_sibling_wars_keep_own_reactor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["a", "b"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
fs::write(
|
||||
root.join(dir).join("pom.xml"),
|
||||
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
for dir in ["a", "b"] {
|
||||
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, dir);
|
||||
assert!(!plan.args.contains(&"-pl".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,6 +447,8 @@ pub enum LspRefreshKind {
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
/// Spring bean markers of open documents may have changed.
|
||||
SpringBeanMarkers,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -162,6 +162,9 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mcp_registry_url: String,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
@@ -211,6 +214,7 @@ impl Default for AgentSettings {
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
mcp_registry_url: String::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
@@ -253,6 +257,14 @@ pub struct AgentMcpServer {
|
||||
/// empty means enabled for all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMcpServer {
|
||||
@@ -266,6 +278,8 @@ impl Default for AgentMcpServer {
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1347,6 +1361,7 @@ pub struct FileIconThemeOptions {
|
||||
pub hollow_folders: bool,
|
||||
pub hide_ui_icons: bool,
|
||||
pub hide_psi_icons: bool,
|
||||
pub file_icons_for_code: bool,
|
||||
pub monochrome: Option<String>,
|
||||
pub saturation: Option<u8>,
|
||||
pub opacity: Option<u8>,
|
||||
@@ -2594,12 +2609,12 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"fileIconTheme":"p/t"}}"#).unwrap();
|
||||
assert!(old.appearance.file_icon_theme_options.is_empty());
|
||||
let json = serde_json::json!({"appearance":{"fileIconThemeOptions":{"p/t":{
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,"fileIconsForCode":true,
|
||||
"monochrome":"#546e7a","saturation":5,"opacity":80,"iconSize":20,"rowHeight":30,"accent":"#009688"}}}});
|
||||
let settings: Settings = serde_json::from_value(json.clone()).unwrap();
|
||||
let options = &settings.appearance.file_icon_theme_options["p/t"];
|
||||
assert!(options.hide_files && options.hollow_folders && !options.hide_folders);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons && options.file_icons_for_code);
|
||||
assert!(options.groups["tests"]);
|
||||
assert_eq!(options.choices["arrows"], "plusminus");
|
||||
assert_eq!(
|
||||
@@ -2615,6 +2630,7 @@ mod tests {
|
||||
assert_eq!(plain["hideFiles"], false);
|
||||
assert_eq!(plain["hideUiIcons"], false);
|
||||
assert_eq!(plain["hidePsiIcons"], false);
|
||||
assert_eq!(plain["fileIconsForCode"], false);
|
||||
assert_eq!(plain["monochrome"], serde_json::Value::Null);
|
||||
assert_eq!(plain["groups"], serde_json::json!({}));
|
||||
}
|
||||
|
||||
@@ -8,6 +8,21 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Why netcoredbg can't be installed here, for the two platforms Samsung publishes no build
|
||||
/// for; the tool installer and the debugger's "not found" error both say it.
|
||||
pub fn netcoredbg_no_prebuilt(intel_mac: bool, windows_arm64: bool) -> Option<String> {
|
||||
let platform = match (intel_mac, windows_arm64) {
|
||||
(true, _) => "Intel Macs",
|
||||
(_, true) => "Windows on ARM64",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!(
|
||||
"Samsung publishes no prebuilt netcoredbg for {platform}. Build it from source \
|
||||
(https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on PATH \
|
||||
or set its executable path in Settings › Languages & Frameworks › Language Servers"
|
||||
))
|
||||
}
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
@@ -133,6 +148,7 @@ fn search_dirs(
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
dirs.extend(RUSTUP_PROXY_DIRS.iter().map(PathBuf::from));
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
@@ -165,6 +181,11 @@ const USER_DIRS: &[&str] = &[
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
/// Homebrew's `rustup` keeps its toolchain proxies (`cargo`, `rust-analyzer`, …) in its own
|
||||
/// prefix, off `PATH` unless the shell adds it: these play the part of `~/.cargo/bin`.
|
||||
pub const RUSTUP_PROXY_DIRS: &[&str] =
|
||||
&["/opt/homebrew/opt/rustup/bin", "/usr/local/opt/rustup/bin", "/home/linuxbrew/.linuxbrew/opt/rustup/bin"];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
|
||||
@@ -250,13 +271,16 @@ mod tests {
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
|
||||
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
|
||||
// Homebrew rustup's proxies, after rustup-init's.
|
||||
assert!(at("/home/me/.cargo/bin") < at("/opt/homebrew/opt/rustup/bin"));
|
||||
assert!(at("/opt/homebrew/opt/rustup/bin") < at("/opt/homebrew/bin"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home/a:b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -613,11 +613,20 @@ pub fn not_standalone(spec: &AdapterSpec) -> IdeError {
|
||||
}
|
||||
|
||||
pub fn missing(spec: &AdapterSpec) -> IdeError {
|
||||
let no_prebuilt = ide_core::tool_path::netcoredbg_no_prebuilt(
|
||||
cfg!(all(target_os = "macos", target_arch = "x86_64")),
|
||||
cfg!(all(windows, target_arch = "aarch64")),
|
||||
)
|
||||
.filter(|_| spec.adapter == "netcoredbg");
|
||||
missing_with(spec, no_prebuilt.as_deref().or(spec.install_hint.as_deref()))
|
||||
}
|
||||
|
||||
fn missing_with(spec: &AdapterSpec, hint: Option<&str>) -> IdeError {
|
||||
let mut msg = format!(
|
||||
"debug adapter `{}` not found (`{}` is neither installed by OpenIDEA nor on PATH)",
|
||||
spec.adapter, spec.command
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
if let Some(hint) = hint {
|
||||
msg.push_str(". ");
|
||||
msg.push_str(hint);
|
||||
}
|
||||
@@ -1205,6 +1214,17 @@ mod tests {
|
||||
assert!(err.message.contains("Settings › Languages & Frameworks › Language Servers"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_netcoredbg_without_a_build_says_how_to_get_one() {
|
||||
let spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
|
||||
let hint = ide_core::tool_path::netcoredbg_no_prebuilt(true, false).unwrap();
|
||||
let message = missing_with(&spec, Some(&hint)).message;
|
||||
assert!(message.starts_with("debug adapter `netcoredbg` not found"), "{message}");
|
||||
assert!(message.contains("no prebuilt netcoredbg for Intel Macs"), "{message}");
|
||||
assert!(message.contains("on PATH"), "{message}");
|
||||
assert_eq!(ide_core::tool_path::netcoredbg_no_prebuilt(false, false), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn process_launcher_reports_missing_binary() {
|
||||
let mut spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
|
||||
|
||||
@@ -805,7 +805,7 @@ macro_rules! backend_id {
|
||||
mod cursor;
|
||||
mod pg_read_only;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
pub(crate) use pg_read_only::validate as validate_pg_read_only;
|
||||
pub(crate) use pg_read_only::{leading_word, validate as validate_pg_read_only};
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
@@ -1058,7 +1058,8 @@ impl Pool {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
// sqlx opens connections for a pool only, so console sessions count here.
|
||||
.max_connections(MAX + crate::console_session::MAX_SESSIONS)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
@@ -1428,6 +1429,7 @@ impl Pool {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
conn.release_after(sql, self.driver()).await;
|
||||
r
|
||||
}
|
||||
|
||||
@@ -1513,13 +1515,38 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection taken out of a pool: for one statement, or held by a
|
||||
/// manual-commit console across statements with its transaction open.
|
||||
/// A connection of a pool, or one opened beside it that closes when dropped.
|
||||
pub enum Lease<M: ManageConnection> {
|
||||
Pooled(bb8::PooledConnection<'static, M>),
|
||||
Own(M::Connection),
|
||||
}
|
||||
|
||||
impl<M: ManageConnection> std::ops::Deref for Lease<M> {
|
||||
type Target = M::Connection;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
Lease::Pooled(c) => c,
|
||||
Lease::Own(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M: ManageConnection> std::ops::DerefMut for Lease<M> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
match self {
|
||||
Lease::Pooled(c) => c,
|
||||
Lease::Own(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection taken out of a pool: for one statement, or held by a console
|
||||
/// across statements (its manual transaction or its session).
|
||||
pub enum Held {
|
||||
Sqlite(PoolConnection<Sqlite>),
|
||||
Postgres(Box<bb8::PooledConnection<'static, PgManager>>),
|
||||
Mysql(Box<bb8::PooledConnection<'static, MysqlManager>>),
|
||||
SqlServer(Box<bb8::PooledConnection<'static, MssqlConnectionManager>>),
|
||||
Postgres(Box<Lease<PgManager>>),
|
||||
Mysql(Box<Lease<MysqlManager>>),
|
||||
SqlServer(Box<Lease<MssqlConnectionManager>>),
|
||||
Clickhouse(crate::clickhouse::ClickhousePool),
|
||||
Oracle(Box<crate::oracle::OracleConnection>),
|
||||
/// The shared session, and the schema this holder's statements run in.
|
||||
@@ -1531,9 +1558,11 @@ impl Held {
|
||||
Ok(match pool {
|
||||
Pool::Jdbc(_) => return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")),
|
||||
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)),
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)),
|
||||
Pool::SqlServer(p) => Held::SqlServer(Box::new(p.get_owned().await.map_err(mssql_pool_err)?)),
|
||||
Pool::Postgres(p) => Held::Postgres(Box::new(Lease::Pooled(p.get().await?))),
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Pooled(p.get().await?))),
|
||||
Pool::SqlServer(p) => {
|
||||
Held::SqlServer(Box::new(Lease::Pooled(p.get_owned().await.map_err(mssql_pool_err)?)))
|
||||
}
|
||||
Pool::Clickhouse(p) => {
|
||||
if p.is_closed() {
|
||||
return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed"));
|
||||
@@ -1550,6 +1579,47 @@ impl Held {
|
||||
})
|
||||
}
|
||||
|
||||
/// A connection that takes none of the pool's; [`discard`](Self::discard) it when done.
|
||||
pub(crate) async fn acquire_own(pool: &Pool) -> IdeResult<Self> {
|
||||
Ok(match pool {
|
||||
Pool::Postgres(p) => {
|
||||
Held::Postgres(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?)))
|
||||
}
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?))),
|
||||
Pool::SqlServer(p) => {
|
||||
Held::SqlServer(Box::new(Lease::Own(p.dedicated_connection().await.map_err(mssql_err)?)))
|
||||
}
|
||||
Pool::Oracle(p) => Held::Oracle(Box::new(p.open_own().await?)),
|
||||
_ => Self::acquire(pool).await?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the server still answers, also inside a failed transaction.
|
||||
pub(crate) async fn is_alive(&mut self) -> bool {
|
||||
let ping = async {
|
||||
match self {
|
||||
Held::Sqlite(c) => c.ping().await.is_ok(),
|
||||
Held::Postgres(c) => c.conn.is_some() && c.ping().await.is_ok(),
|
||||
Held::Mysql(c) => c.conn.is_some() && c.ping().await.is_ok(),
|
||||
Held::SqlServer(c) => c.0.is_some() && mssql_command(c, "SELECT 1").await.is_ok(),
|
||||
Held::Oracle(c) => {
|
||||
crate::oracle::run(c, "SELECT 1 FROM DUAL", 0, 1, Cells::Text, &CancellationToken::new())
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
Held::Clickhouse(_) | Held::Snowflake(..) => true,
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), ping).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Returns the connection that ran `sql` to its pool, unless `sql` left a transaction open on it.
|
||||
pub(crate) async fn release_after(self, sql: &str, driver: DbDriver) {
|
||||
if crate::console_session::opens_transaction(sql, driver) {
|
||||
self.discard().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn context(&mut self) -> Option<&mut Context> {
|
||||
match self {
|
||||
Held::Postgres(c) => Some(&mut c.context),
|
||||
|
||||
@@ -7,7 +7,8 @@ use sqlx::{Executor, SqlSafeStr};
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
|
||||
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
/// Takes the first word off `input`, past comments; empty when something else comes first.
|
||||
pub(crate) fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
loop {
|
||||
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
|
||||
if let Some(comment) = input.strip_prefix("--") {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
//! The connection a SQL console keeps in auto-commit mode.
|
||||
//!
|
||||
//! Plain queries and changes run on any connection of the pool. The first statement that leaves
|
||||
//! something on its connection (a transaction, a temporary table, a setting) opens the console's
|
||||
//! own one, which then runs everything the console runs until the console is released.
|
||||
|
||||
use crate::conn::{Held, Pool, leading_word};
|
||||
use crate::source::DbDriver;
|
||||
use crate::{QueryResult, split};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
/// Consoles of one target that can keep a connection, beside those of the pool.
|
||||
pub(crate) const MAX_SESSIONS: u32 = 4;
|
||||
|
||||
/// `Some(true)`: `sql` opens a transaction, `Some(false)`: it ends the open one.
|
||||
fn transaction_control(sql: &str, driver: DbDriver) -> Option<bool> {
|
||||
let mut rest = sql;
|
||||
let first = leading_word(&mut rest).to_ascii_uppercase();
|
||||
let second = leading_word(&mut rest).to_ascii_uppercase();
|
||||
match first.as_str() {
|
||||
// A block, not a transaction.
|
||||
"BEGIN" if driver == DbDriver::Oracle => None,
|
||||
"BEGIN" if driver == DbDriver::SqlServer => second.starts_with("TRAN").then_some(true),
|
||||
"BEGIN" | "SAVEPOINT" => Some(true),
|
||||
"START" if second == "TRANSACTION" => Some(true),
|
||||
"SET" if matches!(second.as_str(), "AUTOCOMMIT" | "IMPLICIT_TRANSACTIONS") => Some(true),
|
||||
"COMMIT" | "END" | "ABORT" => Some(false),
|
||||
"ROLLBACK" if !sql.split_whitespace().any(|word| word.eq_ignore_ascii_case("TO")) => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn statements(sql: &str, driver: DbDriver) -> Vec<String> {
|
||||
// The `;` in the body of a routine or trigger ends none of its creator's statements.
|
||||
if sql.contains(';') && !leading_word(&mut &*sql).eq_ignore_ascii_case("CREATE") {
|
||||
split::split(sql, driver).into_iter().map(|s| s.text).collect()
|
||||
} else {
|
||||
vec![sql.to_owned()]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn opens_transaction(sql: &str, driver: DbDriver) -> bool {
|
||||
statements(sql, driver).iter().any(|sql| transaction_control(sql, driver) == Some(true))
|
||||
}
|
||||
|
||||
/// Whether a later statement of the console depends on `sql` having run on its connection.
|
||||
/// Unknown statements do.
|
||||
fn needs_session(sql: &str, driver: DbDriver) -> bool {
|
||||
statements(sql, driver).iter().any(|sql| {
|
||||
let mut rest = sql.as_str();
|
||||
let mut first = leading_word(&mut rest);
|
||||
while first.is_empty()
|
||||
&& let Some(inner) = rest.strip_prefix('(')
|
||||
{
|
||||
rest = inner;
|
||||
first = leading_word(&mut rest);
|
||||
}
|
||||
let first = first.to_ascii_uppercase();
|
||||
let words = || rest.split_whitespace().map(str::to_ascii_uppercase);
|
||||
match first.as_str() {
|
||||
"SELECT" | "WITH" | "VALUES" | "TABLE" | "INSERT" | "UPDATE" | "DELETE" | "REPLACE" | "MERGE" => {
|
||||
let text = rest.to_ascii_uppercase();
|
||||
let into = words().any(|word| word == "INTO");
|
||||
["SET_CONFIG", "ADVISORY_LOCK", "GET_LOCK", ":="].iter().any(|state| text.contains(state))
|
||||
|| (into && words().any(|word| is_temporary(&word, driver)))
|
||||
}
|
||||
"CREATE" => words().take(4).any(|word| is_temporary(&word, driver)),
|
||||
"ALTER" => words().next().is_some_and(|word| word == "SESSION"),
|
||||
"SHOW" | "EXPLAIN" | "DESCRIBE" | "DESC" | "DROP" | "TRUNCATE" | "RENAME" | "COMMENT" | "GRANT"
|
||||
| "REVOKE" | "ANALYZE" | "VACUUM" | "REINDEX" | "OPTIMIZE" | "COMMIT" | "END" | "ABORT" | "ROLLBACK" => {
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn is_temporary(word: &str, driver: DbDriver) -> bool {
|
||||
matches!(word, "TEMP" | "TEMPORARY")
|
||||
|| (driver == DbDriver::SqlServer
|
||||
&& word.starts_with(['#', '['])
|
||||
&& word.trim_start_matches('[').starts_with('#'))
|
||||
}
|
||||
|
||||
struct Open {
|
||||
connection: Held,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
/// The console's schema the connection was last put in. Reapplied only when the console picks
|
||||
/// another one, so a `USE` or `SET search_path` of the user stays.
|
||||
schema: Option<String>,
|
||||
transaction: bool,
|
||||
/// The schema was set inside the open transaction, whose rollback may restore the one before.
|
||||
schema_in_transaction: bool,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
async fn new(pool: &Pool, capacity: &Arc<Semaphore>, schema: Option<&str>) -> IdeResult<Self> {
|
||||
let permit = capacity.clone().try_acquire_owned().map_err(|_| {
|
||||
IdeError::unavailable(format!(
|
||||
"{MAX_SESSIONS} consoles already keep a session on this data source. Close one of them and its results, then run the statement again."
|
||||
))
|
||||
})?;
|
||||
let mut connection = Held::acquire_own(pool).await?;
|
||||
connection.apply_context(schema).await?;
|
||||
Ok(Self {
|
||||
connection,
|
||||
_permit: permit,
|
||||
schema: schema.map(str::to_owned),
|
||||
transaction: false,
|
||||
schema_in_transaction: false,
|
||||
})
|
||||
}
|
||||
|
||||
async fn run(
|
||||
&mut self,
|
||||
pool: &Pool,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let driver = pool.driver();
|
||||
// A failed transaction refuses everything but its end, switching the schema included.
|
||||
if self.schema.as_deref() != schema && transaction_control(statement, driver) != Some(false) {
|
||||
self.connection.apply_context(schema).await?;
|
||||
self.schema = schema.map(str::to_owned);
|
||||
self.schema_in_transaction = self.transaction;
|
||||
}
|
||||
let result = self.connection.execute_from(pool, statement, skip, max_rows, cancel).await?;
|
||||
for control in statements(statement, driver).iter().filter_map(|sql| transaction_control(sql, driver)) {
|
||||
self.transaction = control;
|
||||
}
|
||||
if !self.transaction && std::mem::take(&mut self.schema_in_transaction) {
|
||||
self.connection.apply_context(self.schema.as_deref()).await?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn close(mut self) {
|
||||
if self.transaction {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), self.connection.finish_manual(false)).await;
|
||||
}
|
||||
self.connection.discard().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Slot {
|
||||
open: Option<Open>,
|
||||
/// The connection ended inside a transaction, so the statements that follow must not commit on their own.
|
||||
lost_transaction: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ConsoleSession {
|
||||
slot: AsyncMutex<Slot>,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
impl ConsoleSession {
|
||||
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute(
|
||||
&self,
|
||||
pool: &Pool,
|
||||
capacity: &Arc<Semaphore>,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
request: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let cancel = self.retired.child_token();
|
||||
let mut slot = tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
slot = self.slot.lock() => slot,
|
||||
};
|
||||
if std::mem::take(&mut slot.lost_transaction) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::OutOfSync,
|
||||
"The console's connection was closed and its open transaction rolled back. Run the statement again to start over in a new session.",
|
||||
));
|
||||
}
|
||||
let schema = schema.filter(|s| !s.is_empty());
|
||||
if slot.open.is_none() {
|
||||
if !needs_session(statement, pool.driver()) {
|
||||
return Ok(None);
|
||||
}
|
||||
slot.open = Some(tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
open = Open::new(pool, capacity, schema) => open?,
|
||||
});
|
||||
}
|
||||
let open = slot.open.as_mut().expect("opened above");
|
||||
let result = {
|
||||
let execute = open.run(pool, statement, skip, max_rows, &cancel, schema);
|
||||
tokio::pin!(execute);
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => {
|
||||
cancel.cancel();
|
||||
execute.await
|
||||
}
|
||||
result = &mut execute => result,
|
||||
}
|
||||
};
|
||||
let cancelled = cancel.is_cancelled();
|
||||
if cancelled || (result.is_err() && !open.connection.is_alive().await) {
|
||||
let open = slot.open.take().expect("opened above");
|
||||
slot.lost_transaction = open.transaction;
|
||||
open.connection.discard().await;
|
||||
}
|
||||
if cancelled {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
result.map(Some)
|
||||
}
|
||||
|
||||
/// Stops a running statement, rolls back and closes the connection.
|
||||
pub(super) async fn retire(&self) {
|
||||
self.retired.cancel();
|
||||
let open = self.slot.lock().await.open.take();
|
||||
if let Some(open) = open {
|
||||
open.close().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn statements_that_leave_something_on_their_connection_need_a_session() {
|
||||
use DbDriver::{Mysql, Oracle, Postgres, SqlServer, Sqlite};
|
||||
for (driver, sql) in [
|
||||
(Sqlite, "/* note */ BEGIN"),
|
||||
(Sqlite, "PRAGMA foreign_keys = ON"),
|
||||
(Sqlite, "ATTACH 'other.db' AS other"),
|
||||
(Postgres, "SET work_mem = '64MB'"),
|
||||
(Postgres, "CREATE TEMP TABLE t (id int)"),
|
||||
(Postgres, "create local temporary table t (id int)"),
|
||||
(Postgres, "SELECT * INTO TEMP t FROM u"),
|
||||
(Postgres, "SELECT pg_advisory_lock(1)"),
|
||||
(Postgres, "INSERT INTO t VALUES (1); BEGIN"),
|
||||
(Mysql, "USE shop"),
|
||||
(Mysql, "SELECT @n := 1"),
|
||||
(Mysql, "LOCK TABLES t WRITE"),
|
||||
(SqlServer, "BEGIN TRAN"),
|
||||
(SqlServer, "CREATE TABLE #work (id int)"),
|
||||
(SqlServer, "SELECT * INTO #work FROM t"),
|
||||
(Oracle, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY'"),
|
||||
] {
|
||||
assert!(needs_session(sql, driver), "{sql}");
|
||||
}
|
||||
for (driver, sql) in [
|
||||
(Postgres, "SELECT temp FROM weather"),
|
||||
(Postgres, "-- all\n(SELECT 1) UNION (SELECT 2)"),
|
||||
(Postgres, "WITH x AS (SELECT 1) SELECT * FROM x"),
|
||||
(Postgres, "INSERT INTO t VALUES ('a;b')"),
|
||||
(Postgres, "CREATE TABLE t (temp int)"),
|
||||
(Postgres, "ALTER TABLE t ADD c int"),
|
||||
(Postgres, "ROLLBACK"),
|
||||
(Sqlite, "DELETE FROM t; DELETE FROM u"),
|
||||
(Mysql, "SHOW TABLES"),
|
||||
] {
|
||||
assert!(!needs_session(sql, driver), "{sql}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_and_partial_rollbacks_do_not_change_the_transaction() {
|
||||
assert_eq!(transaction_control("BEGIN NULL; END;", DbDriver::Oracle), None);
|
||||
assert_eq!(transaction_control("BEGIN TRY SELECT 1 END TRY", DbDriver::SqlServer), None);
|
||||
assert_eq!(transaction_control("rollback to savepoint s", DbDriver::Postgres), None);
|
||||
assert_eq!(transaction_control("-- done\nROLLBACK", DbDriver::Mysql), Some(false));
|
||||
assert_eq!(transaction_control("START TRANSACTION", DbDriver::Mysql), Some(true));
|
||||
assert!(opens_transaction("DELETE FROM t; BEGIN", DbDriver::Sqlite));
|
||||
assert!(!opens_transaction("SELECT 'BEGIN; x'", DbDriver::Sqlite));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
pub mod catalog;
|
||||
mod clickhouse;
|
||||
mod console_session;
|
||||
mod external_tunnel;
|
||||
pub use external_tunnel::stop_external_tunnels_on_exit;
|
||||
mod jdbc;
|
||||
@@ -2103,6 +2104,8 @@ impl DbManager {
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
|
||||
return nodes;
|
||||
}
|
||||
// SHOWPLAN is a setting of the connection that would stay on in the console's session.
|
||||
let console = console.filter(|_| driver != DbDriver::SqlServer);
|
||||
let result = self
|
||||
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
|
||||
.await?;
|
||||
@@ -2150,6 +2153,7 @@ impl DbManager {
|
||||
{
|
||||
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
|
||||
}
|
||||
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
|
||||
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
|
||||
let session = match console {
|
||||
Some(console) => connection.console_transactions.session(console),
|
||||
@@ -2164,6 +2168,15 @@ impl DbManager {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if session.is_none()
|
||||
&& let Some(editor) = editor
|
||||
&& let Some(result) = connection
|
||||
.console_transactions
|
||||
.execute_auto(editor, &pool, statement, skip, max_rows, cancel, schema)
|
||||
.await?
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
|
||||
let key = conn::CursorKey::new(id, statement, schema).with_console(console);
|
||||
let started = std::time::Instant::now();
|
||||
@@ -2196,6 +2209,7 @@ impl DbManager {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
conn.release_after(statement, pool.driver()).await;
|
||||
return r;
|
||||
};
|
||||
if pool.driver() == DbDriver::Clickhouse {
|
||||
@@ -2216,6 +2230,12 @@ impl DbManager {
|
||||
if self.source(id)?.driver == DbDriver::Clickhouse {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
if self.source(id)?.driver != DbDriver::Postgres
|
||||
&& let Some(connection) = self.opened_connection(id)
|
||||
{
|
||||
// Their statements now run in the transaction of the whole data source.
|
||||
connection.console_transactions.release_all_auto().await;
|
||||
}
|
||||
self.sessions.lock().entry(id.to_owned()).or_default();
|
||||
} else {
|
||||
let session = self.sessions.lock().remove(id);
|
||||
@@ -2245,7 +2265,9 @@ impl DbManager {
|
||||
return Err(IdeError::invalid("Scoped manual transactions require a PostgreSQL data source"));
|
||||
}
|
||||
if manual {
|
||||
self.connection(id).await?.console_transactions.enable(console)
|
||||
let connection = self.connection(id).await?;
|
||||
connection.console_transactions.release_auto(console).await;
|
||||
connection.console_transactions.enable(console)
|
||||
} else {
|
||||
if let Some(connection) = self.opened_connection(id) {
|
||||
connection.console_transactions.release(console).await?;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::console_session::{ConsoleSession, MAX_SESSIONS};
|
||||
use crate::{ConsoleId, Held, Pool, QueryResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
@@ -144,14 +145,23 @@ impl ManualSession {
|
||||
|
||||
pub(super) struct ConsoleTransactions {
|
||||
sessions: Mutex<HashMap<ConsoleKey, Session>>,
|
||||
/// Consoles in auto-commit mode.
|
||||
auto: Mutex<HashMap<ConsoleKey, Arc<ConsoleSession>>>,
|
||||
closed: CancellationToken,
|
||||
/// The four-slot pool also serves ordinary work and one retained result cursor.
|
||||
pub(super) capacity: Arc<Semaphore>,
|
||||
auto_capacity: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl Default for ConsoleTransactions {
|
||||
fn default() -> Self {
|
||||
Self { sessions: Mutex::default(), closed: CancellationToken::new(), capacity: Arc::new(Semaphore::new(2)) }
|
||||
Self {
|
||||
sessions: Mutex::default(),
|
||||
auto: Mutex::default(),
|
||||
closed: CancellationToken::new(),
|
||||
capacity: Arc::new(Semaphore::new(2)),
|
||||
auto_capacity: Arc::new(Semaphore::new(MAX_SESSIONS as usize)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,7 +188,43 @@ impl ConsoleTransactions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `statement` in the console's session; `None` when it has none and needs none.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute_auto(
|
||||
&self,
|
||||
console: ConsoleId<'_>,
|
||||
pool: &Pool,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let session = {
|
||||
let mut auto = self.auto.lock();
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
auto.entry(key(console)).or_default().clone()
|
||||
};
|
||||
// Boxed: the connect inside would double the size of every statement's future.
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
|
||||
}
|
||||
|
||||
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
|
||||
let session = self.auto.lock().remove(&key(console));
|
||||
if let Some(session) = session {
|
||||
session.retire().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn release_all_auto(&self) {
|
||||
let sessions = std::mem::take(&mut *self.auto.lock());
|
||||
futures::future::join_all(sessions.values().map(|session| session.retire())).await;
|
||||
}
|
||||
|
||||
pub(super) async fn release(&self, console: ConsoleId<'_>) -> IdeResult<()> {
|
||||
self.release_auto(console).await;
|
||||
let session = self.sessions.lock().remove(&key(console));
|
||||
if let Some(session) = session {
|
||||
session.retire().await?;
|
||||
@@ -198,5 +244,6 @@ impl ConsoleTransactions {
|
||||
for session in sessions.into_values() {
|
||||
let _ = session.rollback_and_release().await;
|
||||
}
|
||||
self.release_all_auto().await;
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,12 @@ impl OraclePool {
|
||||
/// A connection taken out of the pool for one statement or a held session.
|
||||
pub async fn get(&self) -> IdeResult<OracleConnection> {
|
||||
let pooled = self.pool.get_owned().await.map_err(|e| pool_err(e).into_ide())?;
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled })
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Pooled(pooled) })
|
||||
}
|
||||
|
||||
pub(crate) async fn open_own(&self) -> IdeResult<OracleConnection> {
|
||||
let own = self.pool.dedicated_connection().await.map_err(OracleError::into_ide)?;
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Own(own) })
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
@@ -273,7 +278,7 @@ impl ManageConnection for OracleConnectionManager {
|
||||
/// unless its statement was cancelled (then it is discarded).
|
||||
pub struct OracleConnection {
|
||||
state: Arc<State>,
|
||||
pooled: bb8::PooledConnection<'static, OracleConnectionManager>,
|
||||
pooled: crate::conn::Lease<OracleConnectionManager>,
|
||||
}
|
||||
|
||||
impl OracleConnection {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
|
||||
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const TARGET: &str = "fixture";
|
||||
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
|
||||
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
|
||||
const ROWS: &str = "SELECT id FROM public.console_session ORDER BY id";
|
||||
|
||||
async fn run_in(db: &DbManager, console: ConsoleId<'_>, sql: &str, schema: &str) -> IdeResult<QueryResult> {
|
||||
let cancel = CancellationToken::new();
|
||||
// Boxed: one test awaiting this many statements inline overflows a debug build's stack.
|
||||
Box::pin(db.execute_in_console(TARGET, sql, 0, 10, &cancel, Some(schema), Some(console))).await
|
||||
}
|
||||
|
||||
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
|
||||
run_in(db, console, sql, "public").await
|
||||
}
|
||||
|
||||
async fn value(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<String> {
|
||||
Ok(run(db, console, sql).await?.rows[0][0].clone().unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
|
||||
async fn console_sessions_keep_transactions_settings_and_temporary_tables() -> IdeResult<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: TARGET.into(),
|
||||
name: "Local PostgreSQL".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
|
||||
user: "console_fixture".into(),
|
||||
database: "console_fixture".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
let cancel = CancellationToken::new();
|
||||
for sql in [
|
||||
"DROP TABLE IF EXISTS public.console_session",
|
||||
"CREATE TABLE public.console_session (id int PRIMARY KEY)",
|
||||
"CREATE SCHEMA IF NOT EXISTS console_other",
|
||||
] {
|
||||
db.execute(TARGET, sql, 0, &cancel).await?;
|
||||
}
|
||||
let observer = db.pool(TARGET).await?;
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (1)").await?;
|
||||
let pid = value(&db, A, "SELECT pg_backend_pid()").await?;
|
||||
assert!(run(&db, B, ROWS).await?.rows.is_empty());
|
||||
assert!(observer.rows(ROWS, 10).await?.is_empty());
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty());
|
||||
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid);
|
||||
|
||||
run(&db, A, "SET work_mem = '77MB'").await?;
|
||||
run(&db, A, "CREATE TEMP TABLE work AS SELECT 7 AS n").await?;
|
||||
assert_eq!(value(&db, A, "SHOW work_mem").await?, "77MB");
|
||||
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
|
||||
assert!(run(&db, B, "SELECT n FROM work").await.is_err());
|
||||
assert_ne!(value(&db, B, "SHOW work_mem").await?, "77MB");
|
||||
|
||||
// The picker's schema is applied when it changes and leaves the user's own SET alone otherwise.
|
||||
run(&db, A, "SET search_path TO console_other").await?;
|
||||
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "console_other");
|
||||
run(&db, A, "BEGIN").await?;
|
||||
assert_eq!(run_in(&db, A, "SELECT current_schema()", "pg_catalog").await?.rows, [[Some("pg_catalog".into())]]);
|
||||
assert!(run_in(&db, A, "SELECT 1/0", "pg_catalog").await.is_err());
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "public");
|
||||
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid, "errors keep the session");
|
||||
|
||||
// Every session slot taken, both manual slots and a result cursor leave ordinary work running.
|
||||
let paths: Vec<_> = (0..4).map(|n| format!("{n}.sql")).collect();
|
||||
for path in &paths[..3] {
|
||||
run(&db, ConsoleId::new("main", path), "SET work_mem = '5MB'").await?;
|
||||
}
|
||||
let full = run(&db, ConsoleId::new("main", &paths[3]), "BEGIN").await.unwrap_err();
|
||||
assert_eq!(full.kind, ErrorKind::Unavailable);
|
||||
for path in ["m.sql", "n.sql"] {
|
||||
let console = ConsoleId::new("main", path);
|
||||
db.set_postgres_console_manual(TARGET, console, true).await?;
|
||||
run(&db, console, ROWS).await?;
|
||||
}
|
||||
let page = db
|
||||
.execute_in_console(TARGET, "SELECT generate_series(1, 1000)", 10, 10, &cancel, Some("public"), Some(B))
|
||||
.await?;
|
||||
assert!(page.has_more);
|
||||
tokio::time::timeout(Duration::from_secs(5), db.completion(TARGET)).await.expect("completion does not wait")?;
|
||||
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
|
||||
for path in paths[..3].iter().map(String::as_str).chain(["m.sql", "n.sql"]) {
|
||||
db.release_console(ConsoleId::new("main", path)).await?;
|
||||
}
|
||||
|
||||
// A session that ends inside a transaction is reported before anything else commits on its own.
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (2)").await?;
|
||||
observer.rows(&format!("SELECT pg_terminate_backend({pid})"), 1).await?;
|
||||
assert!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.is_err());
|
||||
assert_eq!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty());
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (4)").await?;
|
||||
let stop = CancellationToken::new();
|
||||
let (stopped, ()) = tokio::join!(
|
||||
db.execute_in_console(TARGET, "SELECT pg_sleep(8)", 0, 10, &stop, Some("public"), Some(A)),
|
||||
async {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
stop.cancel();
|
||||
}
|
||||
);
|
||||
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
assert_eq!(run(&db, A, "SELECT 1").await.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert!(observer.rows(ROWS, 10).await?.is_empty());
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
|
||||
db.release_console(A).await?;
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
|
||||
assert!(db.set_postgres_console_manual(TARGET, A, true).await?);
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty(), "manual mode starts its own transaction");
|
||||
db.release_console(A).await?;
|
||||
|
||||
db.execute(TARGET, "BEGIN", 0, &cancel).await?;
|
||||
db.execute_from(TARGET, "START TRANSACTION", 0, 0, &cancel, Some("public")).await?;
|
||||
let open = "SELECT count(*) FROM pg_stat_activity WHERE state LIKE 'idle in transaction%'";
|
||||
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
tokio::time::timeout(Duration::from_secs(5), db.disconnect(TARGET)).await.expect("disconnects");
|
||||
let observer = db.pool(TARGET).await?;
|
||||
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! What a SQL console in auto-commit mode keeps between its statements.
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, QueryResult};
|
||||
use std::time::Duration;
|
||||
|
||||
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
|
||||
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
|
||||
const COUNT: &str = "SELECT count(*) FROM t";
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
std::fs::File::create(root.join("app.db")).unwrap();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s1".into(),
|
||||
name: "app".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some("app.db".into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
for sql in ["CREATE TABLE t (id INTEGER PRIMARY KEY)", "INSERT INTO t VALUES (1), (2), (3)"] {
|
||||
db.execute("s1", sql, 0, &CancellationToken::new()).await.unwrap();
|
||||
}
|
||||
(tmp, db)
|
||||
}
|
||||
|
||||
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
|
||||
db.execute_in_console("s1", sql, 0, 10, &CancellationToken::new(), None, Some(console)).await
|
||||
}
|
||||
|
||||
async fn run_all(db: &DbManager, console: ConsoleId<'_>, script: &[&str]) -> IdeResult<()> {
|
||||
for sql in script {
|
||||
run(db, console, sql).await.map_err(|e| IdeError::invalid(format!("{sql}: {}", e.message)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn count(db: &DbManager, console: Option<ConsoleId<'_>>) -> IdeResult<String> {
|
||||
let token = CancellationToken::new();
|
||||
let result = db.execute_in_console("s1", COUNT, 0, 10, &token, None, console).await?;
|
||||
Ok(result.rows[0][0].clone().unwrap())
|
||||
}
|
||||
|
||||
async fn insert_in_table_editor(db: &DbManager, id: &str) -> IdeResult<u64> {
|
||||
let values = vec![CellValue { column: "id".into(), value: Some(id.into()) }];
|
||||
db.apply_edits("s1", "main", "t", &[DbRowEdit::Insert { values }]).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rollback_undoes_the_statements_since_begin() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "0");
|
||||
assert_eq!(count(&db, Some(B)).await?, "3", "another console reads committed rows");
|
||||
assert_eq!(count(&db, None).await?, "3", "so does a statement outside any console");
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run_all(&db, A, &["-- comment first\nBEGIN IMMEDIATE", "DELETE FROM t WHERE id = 1", "COMMIT"]).await?;
|
||||
assert_eq!(count(&db, Some(B)).await?, "2");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn temporary_tables_and_settings_belong_to_their_console() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "PRAGMA cache_size = 123"]).await?;
|
||||
run_all(&db, A, &["INSERT INTO work SELECT id FROM t"; 3]).await?;
|
||||
assert_eq!(run(&db, A, "SELECT count(*) FROM work").await?.rows, [[Some("9".into())]]);
|
||||
assert_eq!(run(&db, A, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
|
||||
assert!(run(&db, B, "SELECT count(*) FROM work").await.is_err());
|
||||
assert_ne!(run(&db, B, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
|
||||
let outside = db.execute("s1", "SELECT count(*) FROM work", 10, &CancellationToken::new()).await;
|
||||
assert!(outside.is_err());
|
||||
|
||||
// A later page of the console's own result reads the same session.
|
||||
let page = db
|
||||
.execute_in_console("s1", "SELECT id FROM work ORDER BY id", 3, 3, &CancellationToken::new(), None, Some(A))
|
||||
.await?;
|
||||
assert_eq!(page.rows, vec![vec![Some("2".to_owned())]; 3]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_console_rolls_back_and_frees_the_file() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
db.release_target_console(A, Some("other")).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "0", "another target's release leaves this session alone");
|
||||
db.release_console(A).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
|
||||
assert_eq!(count(&db, Some(A)).await?, "4");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnecting_rolls_back_an_open_transaction() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
tokio::time::timeout(Duration::from_secs(5), db.disconnect("s1")).await.expect("the pool closes");
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_mode_ends_the_console_sessions_of_its_data_source() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
db.set_manual_commit("s1", true).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run(&db, B, "INSERT INTO t VALUES (4)").await?;
|
||||
db.finish_transaction("s1", true).await?;
|
||||
db.set_manual_commit("s1", false).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "4");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_session_without_a_transaction_leaves_the_table_editor_free() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "BEGIN", "INSERT INTO t VALUES (4)", "COMMIT"]).await?;
|
||||
let token = CancellationToken::new();
|
||||
// The rows after the first stay unread on the session's connection.
|
||||
assert!(db.execute_in_console("s1", "SELECT id FROM t", 0, 1, &token, None, Some(A)).await?.has_more);
|
||||
let saved = tokio::time::timeout(Duration::from_secs(2), insert_in_table_editor(&db, "5"));
|
||||
assert_eq!(saved.await.expect("the table editor does not wait for the console")?, 1);
|
||||
assert_eq!(count(&db, Some(A)).await?, "5");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_rolls_back_and_the_next_statement_says_so() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
let slow = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000000) SELECT sum(i) FROM n";
|
||||
let token = CancellationToken::new();
|
||||
let (stopped, ()) = tokio::join!(db.execute_in_console("s1", slow, 0, 10, &token, None, Some(A)), async {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
token.cancel();
|
||||
});
|
||||
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let refused = run(&db, A, "DELETE FROM t WHERE id = 1").await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::OutOfSync, "it would commit outside the transaction: {}", refused.message);
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_are_bounded_and_leave_ordinary_statements_their_connections() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let paths: Vec<_> = (0..5).map(|n| format!("{n}.sql")).collect();
|
||||
let consoles: Vec<_> = paths.iter().map(|path| ConsoleId::new("main", path)).collect();
|
||||
for console in &consoles[..4] {
|
||||
run(&db, *console, "PRAGMA cache_size = 99").await?;
|
||||
}
|
||||
let refused = run(&db, consoles[4], "BEGIN").await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::Unavailable, "{}", refused.message);
|
||||
assert_eq!(count(&db, Some(consoles[4])).await?, "3", "a plain query needs no session");
|
||||
run(&db, consoles[4], "INSERT INTO t VALUES (4)").await?;
|
||||
db.completion("s1").await?;
|
||||
assert_eq!(insert_in_table_editor(&db, "5").await?, 1);
|
||||
db.release_console(consoles[0]).await?;
|
||||
run_all(&db, consoles[4], &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
|
||||
assert_eq!(count(&db, None).await?, "5");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_transaction_opened_outside_a_console_never_reaches_another_statement() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let token = CancellationToken::new();
|
||||
db.execute("s1", "BEGIN", 0, &token).await?;
|
||||
db.execute("s1", "BEGIN; DELETE FROM t", 0, &token).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
|
||||
db.execute("s1", "BEGIN; DELETE FROM t WHERE id = 1; COMMIT", 0, &token).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.20.0";
|
||||
pub const ENGINE_VERSION: &str = "1.21.0";
|
||||
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
|
||||
pub const MAX_CAPABILITY_REASON: usize = 500;
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
@@ -168,6 +168,7 @@ impl ActivationEvent {
|
||||
pub const EVENT_KINDS: &[&str] = &[
|
||||
"document-changed",
|
||||
"websocket-ready",
|
||||
"run-started",
|
||||
"run-exited",
|
||||
"terminal-exited",
|
||||
"content-tab-action",
|
||||
@@ -475,6 +476,9 @@ impl Manifest {
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "run-started") {
|
||||
self.needs_api(&format!("`{event}`"), 21)?;
|
||||
}
|
||||
if !seen.insert(event) {
|
||||
return Err(format!("duplicate activation event {event}"));
|
||||
}
|
||||
|
||||
@@ -603,7 +603,7 @@ impl AutomationService {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
out.sort_by(compare_automations_by_schedule);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -3146,6 +3146,32 @@ fn is_actively_scheduled(a: &AgentAutomation) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Orders automations as an upcoming schedule queue:
|
||||
/// 1. Enabled schedules with a future `next_run_ms` (soonest first),
|
||||
/// 2. Enabled idle/manual schedules with no upcoming firing (most recently updated first),
|
||||
/// 3. Paused automations (most recently updated first).
|
||||
fn compare_automations_by_schedule(a: &AgentAutomation, b: &AgentAutomation) -> std::cmp::Ordering {
|
||||
let tier = |x: &AgentAutomation| -> u8 {
|
||||
if !x.enabled {
|
||||
2
|
||||
} else if x.next_run_ms.is_some() {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
}
|
||||
};
|
||||
tier(a)
|
||||
.cmp(&tier(b))
|
||||
.then_with(|| {
|
||||
match (a.enabled.then_some(a.next_run_ms).flatten(), b.enabled.then_some(b.next_run_ms).flatten()) {
|
||||
(Some(na), Some(nb)) => na.total_cmp(&nb),
|
||||
_ => std::cmp::Ordering::Equal,
|
||||
}
|
||||
})
|
||||
.then_with(|| b.updated_ms.total_cmp(&a.updated_ms))
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
}
|
||||
|
||||
/// Disables a `OneShot` automation whose seed timestamp has elapsed once no active run remains
|
||||
/// and the agent did not schedule a future `next_run_override_ms`.
|
||||
fn finalize_exhausted_oneshot_locked(state: &mut StoredState, automation_id: &str, now: f64) -> bool {
|
||||
|
||||
@@ -19,6 +19,54 @@ const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@bi
|
||||
const DPRINT_MARKERS: [&str; 5] =
|
||||
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
|
||||
|
||||
/// CSharpier's configuration and ignore files.
|
||||
const CSHARPIER_CONFIGS: [&str; 5] =
|
||||
[".csharpierrc", ".csharpierrc.json", ".csharpierrc.yaml", ".csharpierrc.yml", ".csharpierignore"];
|
||||
|
||||
/// The version of CSharpier in the `dotnet` tool manifest that applies to `file`: the nearest one
|
||||
/// in the project that lists it, up to a manifest marked `isRoot` (as `dotnet` searches).
|
||||
fn local_csharpier(file: &Path, root: &Path) -> Option<String> {
|
||||
for dir in file.parent()?.ancestors().take_while(|dir| dir.starts_with(root)) {
|
||||
let mut is_root = false;
|
||||
// .NET 10's `dotnet new tool-manifest` writes the second location.
|
||||
for manifest in [dir.join(".config").join("dotnet-tools.json"), dir.join("dotnet-tools.json")] {
|
||||
let Some(json) = std::fs::read_to_string(manifest).ok().and_then(|text| {
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(text)).ok()
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let tool = json["tools"].as_object().and_then(|tools| {
|
||||
tools.iter().find(|(name, _)| name.eq_ignore_ascii_case("csharpier")).map(|(_, tool)| tool)
|
||||
});
|
||||
if let Some(tool) = tool {
|
||||
return Some(tool["version"].as_str().unwrap_or_default().to_owned());
|
||||
}
|
||||
is_root |= json["isRoot"] == serde_json::Value::Bool(true);
|
||||
}
|
||||
if is_root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// CSharpier for a `.cs` file of a project that uses it. `None` keeps the language server: another
|
||||
/// language, a project without CSharpier, or only its configuration with no CSharpier installed.
|
||||
fn csharpier_for(tools: &Tools, file: &Path, root: &Path) -> Option<IdeResult<formatter::CSharpierCommand>> {
|
||||
if !file.extension().is_some_and(|e| e.eq_ignore_ascii_case("cs")) {
|
||||
return None;
|
||||
}
|
||||
let local = local_csharpier(file, root);
|
||||
if local.is_none() && find_in_project(file, root, &CSHARPIER_CONFIGS).is_none() {
|
||||
return None;
|
||||
}
|
||||
match tools.csharpier_command(file, local.as_deref()) {
|
||||
Err(_) if local.is_none() => None,
|
||||
command => Some(command),
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
|
||||
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
|
||||
file.parent()?
|
||||
@@ -374,10 +422,53 @@ fn php_cs_fixer_edits(
|
||||
let copy = dir.path().join(name);
|
||||
std::fs::write(©, unsaved)?;
|
||||
formatter::run_php_cs_fixer(tools.php_cs_fixer_command(php, fixer, ©)?, &Default::default())?;
|
||||
let formatted = std::fs::read_to_string(©)?;
|
||||
fixed_edits(unsaved, &std::fs::read_to_string(©)?)
|
||||
}
|
||||
|
||||
/// Where a container finds the copy PHP-CS-Fixer fixes.
|
||||
const PHP_CS_FIXER_COPY: &str = "/openidea-php-cs-fixer";
|
||||
|
||||
/// [`php_cs_fixer_edits`] with the PHP of `target`, the container run target PHP runs in: the
|
||||
/// folder of the copy is mounted for this run, the configuration and `vendor` are in the project.
|
||||
fn php_cs_fixer_container_edits(
|
||||
data_dir: &Path,
|
||||
root: &Path,
|
||||
target: &ide_core::remote_settings::RunTarget,
|
||||
fixer: &formatter::PhpCsFixer,
|
||||
path: &Path,
|
||||
unsaved: &str,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let name = path.file_name().ok_or_else(|| IdeError::invalid("PHP-CS-Fixer: file has no name"))?;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let copy = dir.path().join(name);
|
||||
std::fs::write(©, unsaved)?;
|
||||
let php = crate::ops::run::container::PhpContainer::open(data_dir, root, target)?;
|
||||
let args = [
|
||||
php.path(&fixer.bin)?,
|
||||
"fix".into(),
|
||||
"--config".into(),
|
||||
php.path(&fixer.config)?,
|
||||
"--using-cache=no".into(),
|
||||
"--no-interaction".into(),
|
||||
"--show-progress=none".into(),
|
||||
format!("{PHP_CS_FIXER_COPY}/{}", name.to_string_lossy()),
|
||||
];
|
||||
let cwd = php.path(fixer.config.parent().unwrap_or(root))?;
|
||||
let volumes = [(dir.path().to_path_buf(), PHP_CS_FIXER_COPY.to_owned())];
|
||||
let (command, container) = php.command(&cwd, &volumes, &args)?;
|
||||
if let Err(error) = formatter::run_php_cs_fixer(command, &Default::default()) {
|
||||
// A run that timed out left its container behind.
|
||||
php.remove(&container);
|
||||
return Err(error);
|
||||
}
|
||||
fixed_edits(unsaved, &std::fs::read_to_string(©)?)
|
||||
}
|
||||
|
||||
/// The edits that turn `unsaved` into `formatted`.
|
||||
fn fixed_edits(unsaved: &str, formatted: &str) -> IdeResult<Vec<TextEdit>> {
|
||||
let text = ide_text::Document::new(unsaved);
|
||||
Ok(text
|
||||
.diff(&formatted)
|
||||
.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
@@ -756,8 +847,11 @@ async fn provider_edits(
|
||||
}
|
||||
let php = ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter);
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let edits = tokio::task::spawn_blocking(move || {
|
||||
php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text)
|
||||
let container = crate::ops::run::container::php_target(&settings);
|
||||
let (data_dir, root) = (host.data_dir.clone(), project.root.clone());
|
||||
let edits = tokio::task::spawn_blocking(move || match container {
|
||||
Some(target) => php_cs_fixer_container_edits(&data_dir, &root, &target, &fixer, &snap.path, &snap.text),
|
||||
None => php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
@@ -770,6 +864,39 @@ async fn provider_edits(
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
// CSharpier takes over Reformat Code for C# in projects that use it. It formats whole files
|
||||
// only, so ranges (a selection, generated code) stay with the language server, as in Rider.
|
||||
// It runs the project's tool, so Restricted Mode keeps the server too.
|
||||
if options.tool.is_none()
|
||||
&& range.is_none()
|
||||
&& project.require_trust().is_ok()
|
||||
&& let Some(command) = csharpier_for(&Tools::new(&host.local_data_dir), &snap.path, &project.root)
|
||||
{
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(None);
|
||||
}
|
||||
if snap.read_only {
|
||||
return Err(IdeError::invalid("The file is read-only"));
|
||||
}
|
||||
let command = command?;
|
||||
let (edits, excluded) = tokio::task::spawn_blocking(move || {
|
||||
let formatted = formatter::run_csharpier(command, &snap.text, &Default::default())?;
|
||||
if excluded_output(&snap.text, &formatted) {
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
Ok::<_, IdeError>((diff_edits(&ide_text::Document::new(&snap.text), &formatted), false))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
if excluded && !options.on_save {
|
||||
project.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Info,
|
||||
title: "CSharpier".into(),
|
||||
body: Some("CSharpier left the file unchanged: its configuration excludes it".into()),
|
||||
});
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
// dprint formats what its configuration covers, before the language's own formatters.
|
||||
let dprint = &settings.languages.dprint;
|
||||
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
|
||||
@@ -963,7 +1090,7 @@ async fn provider_edits(
|
||||
}
|
||||
|
||||
/// The edits that turn `text` into `formatted`, one per changed region.
|
||||
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
|
||||
pub(crate) fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
|
||||
text.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
@@ -1059,6 +1186,54 @@ mod tests {
|
||||
assert_eq!(external_tool(None, None, file, &settings).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharpier_is_found_in_the_projects_tool_manifest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("repo");
|
||||
let file = root.join("src/App/A.cs");
|
||||
let write = |path: &str, text: &str| {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
let manifest = |name: &str, version: &str, is_root: bool| {
|
||||
format!(r#"{{"isRoot":{is_root},"tools":{{"{name}":{{"version":"{version}"}}}}}}"#)
|
||||
};
|
||||
// Outside the project it is not the project's.
|
||||
write("dotnet-tools.json", &manifest("csharpier", "1.0.0", true));
|
||||
assert_eq!(local_csharpier(&file, &root), None);
|
||||
// .NET 10 writes the manifest at the root; names are case-insensitive, a BOM is fine.
|
||||
write("repo/dotnet-tools.json", &format!("\u{feff}{}", manifest("CSharpier", "1.4.2", true)));
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
// A nearer manifest without it passes the search on, unless it is the root one.
|
||||
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", false));
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", true));
|
||||
assert_eq!(local_csharpier(&file, &root), None);
|
||||
write("repo/src/.config/dotnet-tools.json", "not json");
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_csharp_files_of_csharpier_projects_leave_the_language_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let tools = Tools::new(&root.join("data"));
|
||||
let uses = |file: &str| csharpier_for(&tools, &root.join(file), root).is_some();
|
||||
assert!(!uses("A.cs"));
|
||||
// A configuration alone takes over only with a CSharpier installed (none on CI), else the
|
||||
// language server keeps formatting.
|
||||
std::fs::write(root.join(".csharpierrc"), "").unwrap();
|
||||
assert_eq!(uses("A.cs"), tools.formatter_command("csharpier", &root.join("A.cs"), None).is_ok());
|
||||
std::fs::write(root.join("dotnet-tools.json"), r#"{"tools":{"csharpier":{"version":"1.4.2"}}}"#).unwrap();
|
||||
// `.csx`, project files and other languages keep their formatter.
|
||||
for other in ["A.csx", "App.csproj", "a.fs"] {
|
||||
assert!(!uses(other), "{other}");
|
||||
}
|
||||
// Without `dotnet` this is the "SDK is not installed" error, still CSharpier's.
|
||||
assert!(uses("A.cs") && uses("B.CS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_is_the_python_external_formatter_and_is_opt_out() {
|
||||
let file = Path::new("/project/src/example.py");
|
||||
@@ -1555,6 +1730,51 @@ mod tests {
|
||||
assert_eq!(formatter::php_cs_fixer(&file).unwrap().config, root.join("src/.php-cs-fixer.dist.php"));
|
||||
}
|
||||
|
||||
/// With a real Docker daemon:
|
||||
/// `cargo test -p ide-host --lib formatter::tests::php_cs_fixer_fixes_the_copy_in -- --ignored`.
|
||||
#[test]
|
||||
#[ignore = "requires a Docker daemon and the php:8.3-cli image"]
|
||||
fn php_cs_fixer_fixes_the_copy_in_a_container_run_target() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("vendor/bin")).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join(".php-cs-fixer.dist.php"), "<?php").unwrap();
|
||||
// Stands in for PHP-CS-Fixer: it needs the configuration, runs beside it, and indents
|
||||
// the file it is given.
|
||||
let stand_in = r#"<?php
|
||||
$file = end($argv);
|
||||
if ($argv[1] !== 'fix' || !is_file($argv[3]) || getcwd() !== dirname($argv[3]) || getenv('XDEBUG_MODE') !== 'off') {
|
||||
fwrite(STDERR, 'unexpected run: ' . getcwd() . ' ' . implode(' ', $argv));
|
||||
exit(16);
|
||||
}
|
||||
file_put_contents($file, str_replace(' echo', ' echo', file_get_contents($file)));
|
||||
"#;
|
||||
std::fs::write(root.join("vendor/bin/php-cs-fixer"), stand_in).unwrap();
|
||||
let file = root.join("src").join("Kernel.php");
|
||||
let fixer = formatter::php_cs_fixer(&file).unwrap();
|
||||
let target = ide_core::remote_settings::RunTarget {
|
||||
kind: ide_core::remote_settings::RunTargetKind::Docker,
|
||||
id: "php".into(),
|
||||
name: "PHP".into(),
|
||||
image: "php:8.3-cli".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let data = root.join("data");
|
||||
let edits = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n echo 1;\n").unwrap();
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].new_text, " ");
|
||||
assert!(!file.exists(), "the file on disk is left alone");
|
||||
|
||||
std::fs::write(
|
||||
root.join("vendor/bin/php-cs-fixer"),
|
||||
"<?php fwrite(STDERR, 'Configuration file is invalid'); exit(16);",
|
||||
)
|
||||
.unwrap();
|
||||
let err = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n").unwrap_err();
|
||||
assert!(err.message.contains("Configuration file is invalid"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn php_cs_fixer_fixes_a_copy_of_the_unsaved_text() {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_core::{
|
||||
CancellationToken, Diagnostic, IdeError, IdeEvent, IdeResult, Pos, Range, Severity, SharedSink, TaskId,
|
||||
};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -20,6 +22,10 @@ use tokio::sync::Notify;
|
||||
const DELAY: Duration = Duration::from_millis(750);
|
||||
const SOURCE: &str = "kotlin-bridge";
|
||||
const COMMAND: &str = "openidea.kotlin.replace";
|
||||
/// How long a snapshot waits for jdtls to import the project, before it is sent regardless.
|
||||
const IMPORT_WAIT: Duration = Duration::from_secs(30 * 60);
|
||||
/// The pauses before a snapshot jdtls did not take is sent again.
|
||||
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(45)];
|
||||
|
||||
#[derive(Default)]
|
||||
struct Revision {
|
||||
@@ -133,13 +139,50 @@ impl KotlinBridge {
|
||||
self.revision.lock().cancel.cancel();
|
||||
}
|
||||
|
||||
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> ide_core::IdeResult<()> {
|
||||
let snapshot = serde_json::to_value(projects).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
/// Hands `projects` to jdtls once it imported the project, again after a pause when it
|
||||
/// timed out, refused or went away. A jdtls that was stopped is not started again.
|
||||
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let deadline = tokio::time::Instant::now() + IMPORT_WAIT;
|
||||
let mut delays = RETRY_DELAYS.iter();
|
||||
loop {
|
||||
let Err(error) = self.try_replace(projects, deadline, cancel).await else { return Ok(()) };
|
||||
let Some(delay) = delays.next() else { return Err(error) };
|
||||
if cancel.is_cancelled() || self.lsp.jdtls_stopped(&self.root) {
|
||||
return Err(error);
|
||||
}
|
||||
tracing::info!("Kotlin libraries: {error}; trying again in {} s", delay.as_secs());
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
_ = tokio::time::sleep(*delay) => {}
|
||||
}
|
||||
if self.lsp.jdtls_stopped(&self.root) {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`replace`](Self::replace), with a background task while it waits for the import.
|
||||
async fn publish(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let _waiting = (!self.lsp.jdtls_imported(&self.root)).then(|| {
|
||||
let task = BuildTask::start(self.sink.clone(), cancel);
|
||||
task.emit(Some("Waiting for jdtls to import the project".into()), None, false);
|
||||
task
|
||||
});
|
||||
self.replace(projects, cancel).await
|
||||
}
|
||||
|
||||
async fn try_replace(
|
||||
&self,
|
||||
projects: &[ProjectLibraries],
|
||||
deadline: tokio::time::Instant,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let snapshot = serde_json::to_value(projects).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
self.lsp.wait_jdtls_imported(&self.root, deadline, cancel).await?;
|
||||
let response = self.lsp.jdtls_command_cancellable(&self.root, COMMAND, vec![snapshot], cancel).await?;
|
||||
if response.as_u64().is_none() {
|
||||
return Err(ide_core::IdeError::unavailable(
|
||||
"Kotlin bridge command did not acknowledge its library snapshot",
|
||||
));
|
||||
return Err(IdeError::unavailable("Kotlin bridge command did not acknowledge its library snapshot"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -211,7 +254,7 @@ impl KotlinBridge {
|
||||
};
|
||||
// Clear entries persisted by an earlier incarnation only before our first build.
|
||||
if !initialized {
|
||||
if let Err(error) = self.replace(&[], &cancel).await {
|
||||
if let Err(error) = self.publish(&[], &cancel).await {
|
||||
if !cancel.is_cancelled() {
|
||||
self.failure(error.message, &mut diagnostics, &mut last_failure);
|
||||
}
|
||||
@@ -238,7 +281,7 @@ impl KotlinBridge {
|
||||
}
|
||||
match result {
|
||||
Ok(Ok(Outcome { success: true, projects, .. })) => {
|
||||
match self.replace(&projects, &cancel).await {
|
||||
match self.publish(&projects, &cancel).await {
|
||||
Ok(()) => {
|
||||
for old in published.drain(..) {
|
||||
remove_directory(old).await;
|
||||
@@ -423,6 +466,9 @@ impl DocumentObserver for KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod replace_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
//! The bridge against an in-memory jdtls that is still importing, refuses a snapshot or goes
|
||||
//! away (#7726). Maven is a fake `mvnw` that reports a build without modules.
|
||||
|
||||
use super::*;
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_language::{LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::{LaunchError, Launcher};
|
||||
use serde_json::{Value, json};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Longer than the time a command may take once it was sent.
|
||||
const LONG_IMPORT: Duration = Duration::from_secs(300);
|
||||
const PAST_RETRY: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jdtls {
|
||||
launches: AtomicUsize,
|
||||
/// Whether each snapshot arrived after the running instance's `ServiceReady`.
|
||||
replaces: Mutex<Vec<bool>>,
|
||||
/// The snapshots refused from now on, by their position among all.
|
||||
refused: Mutex<Vec<usize>>,
|
||||
/// Requests are not answered while set.
|
||||
stuck: AtomicBool,
|
||||
importing: AtomicBool,
|
||||
ready: AtomicBool,
|
||||
peer: Mutex<Option<Peer>>,
|
||||
}
|
||||
|
||||
impl Jdtls {
|
||||
fn finish_import(&self) {
|
||||
self.ready.store(true, Ordering::SeqCst);
|
||||
let peer = self.peer.lock().clone().unwrap();
|
||||
peer.notify("language/status", json!({ "type": "ServiceReady", "message": "ServiceReady" })).unwrap();
|
||||
}
|
||||
|
||||
fn replaces(&self) -> Vec<bool> {
|
||||
self.replaces.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
struct Server(Arc<Jdtls>);
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_notification(&self, method: &str, _: Value) {
|
||||
if method == "initialized" && !self.0.importing.load(Ordering::SeqCst) {
|
||||
self.0.finish_import();
|
||||
}
|
||||
}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({ "capabilities": {} })),
|
||||
"workspace/executeCommand" if params["command"] == COMMAND => {
|
||||
let position = {
|
||||
let mut replaces = self.0.replaces.lock();
|
||||
replaces.push(self.0.ready.load(Ordering::SeqCst));
|
||||
replaces.len() - 1
|
||||
};
|
||||
while self.0.stuck.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
if self.0.refused.lock().contains(&position) {
|
||||
return Err((-32603, "Workspace is locked".into()));
|
||||
}
|
||||
Ok(json!(0))
|
||||
}
|
||||
_ => Ok(Value::Null),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Launch(Arc<Jdtls>);
|
||||
|
||||
impl Launcher for Launch {
|
||||
fn launch(
|
||||
&self,
|
||||
config: &LanguageServerConfig,
|
||||
_: &Path,
|
||||
handler: Arc<dyn Handler>,
|
||||
_: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> Result<Peer, LaunchError> {
|
||||
if config.name != "jdtls" {
|
||||
return Err(LaunchError::Missing);
|
||||
}
|
||||
self.0.launches.fetch_add(1, Ordering::SeqCst);
|
||||
self.0.ready.store(false, Ordering::SeqCst);
|
||||
let (client, server) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(server);
|
||||
*self.0.peer.lock() = Some(Peer::connect(r, w, Arc::new(Server(self.0.clone()))));
|
||||
let (r, w) = tokio::io::split(client);
|
||||
Ok(Peer::connect(r, w, handler))
|
||||
}
|
||||
}
|
||||
|
||||
/// A background task's message (`None` when it starts or ends) and whether it is done.
|
||||
type TaskUpdate = (Option<String>, bool);
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
jdtls: Arc<Jdtls>,
|
||||
lsp: Arc<LspManager>,
|
||||
bridge: Arc<KotlinBridge>,
|
||||
tasks: Arc<Mutex<Vec<TaskUpdate>>>,
|
||||
failures: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
fn start(importing: bool, refused: &[usize]) -> Fixture {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("p");
|
||||
std::fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><groupId>g</groupId><artifactId>a</artifactId><version>1</version></project>",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("src/main/kotlin/K.kt"), "class K\n").unwrap();
|
||||
std::fs::write(
|
||||
root.join("mvnw"),
|
||||
"#!/bin/sh\nfor a; do case \"$a\" in -Dopenidea.kotlin.staging=*) echo '[]' > \"$(dirname \"${a#*=}\")/modules.json\";; esac; done\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(root.join("mvnw"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let jdtls = Arc::new(Jdtls::default());
|
||||
jdtls.importing.store(importing, Ordering::SeqCst);
|
||||
*jdtls.refused.lock() = refused.to_vec();
|
||||
let tasks: Arc<Mutex<Vec<_>>> = Arc::default();
|
||||
let failures: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let sink: SharedSink = Arc::new({
|
||||
let (tasks, failures) = (tasks.clone(), failures.clone());
|
||||
move |e: IdeEvent| match e {
|
||||
IdeEvent::Task { title, message, done, .. } if title == BuildTask::TITLE => {
|
||||
tasks.lock().push((message, done))
|
||||
}
|
||||
IdeEvent::Notify { body, .. } => failures.lock().push(body.unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
|
||||
let lsp = LspManager::with_launcher(root.clone(), languages, sink.clone(), Arc::new(Launch(jdtls.clone())));
|
||||
let bridge = KotlinBridge::new(
|
||||
root,
|
||||
base.join("cache"),
|
||||
&base.join("data"),
|
||||
Arc::new(SettingsStore::load(&base.join("config"), None)),
|
||||
lsp.clone(),
|
||||
sink,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
);
|
||||
bridge.start(&tokio::runtime::Handle::current());
|
||||
Fixture { _tmp: tmp, jdtls, lsp, bridge, tasks, failures }
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.jdtls.stuck.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// The bridge asked for jdtls and it was told `initialized`.
|
||||
async fn until_running(&self) {
|
||||
until("jdtls to run", || self.lsp.servers().iter().any(|s| s.name == "jdtls" && is_up(s.status))).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
async fn until_published(&self, replaces: usize) {
|
||||
until("the libraries to be published", || self.jdtls.replaces().len() == replaces).await;
|
||||
until("the task to end", || self.tasks.lock().last().is_some_and(|(_, done)| *done)).await;
|
||||
}
|
||||
|
||||
fn jdtls_id(&self) -> ide_core::ServerId {
|
||||
self.lsp.servers().iter().find(|s| s.name == "jdtls").unwrap().id
|
||||
}
|
||||
}
|
||||
|
||||
fn is_up(status: ide_core::event::ServerStatus) -> bool {
|
||||
matches!(status, ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy)
|
||||
}
|
||||
|
||||
async fn until(what: &str, done: impl Fn() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while !done() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves every timer on by `time` and lets what it wakes run.
|
||||
async fn skip(time: Duration) {
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(time).await;
|
||||
tokio::time::resume();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_waits_for_an_import_longer_than_the_command_timeout() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!((f.jdtls.replaces(), f.failures.lock().clone()), (vec![], vec![]));
|
||||
let waiting = f.tasks.lock().last().cloned().unwrap();
|
||||
assert!(waiting.0.is_some_and(|m| m.contains("import")) && !waiting.1, "the wait shows in the status bar");
|
||||
f.jdtls.finish_import();
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true], "only after ServiceReady");
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refused_snapshots_are_sent_again() {
|
||||
// The first snapshot clears earlier libraries, the third publishes the built ones.
|
||||
let f = start(false, &[0, 2]);
|
||||
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
|
||||
skip(PAST_RETRY).await;
|
||||
until("the built snapshot", || f.jdtls.replaces().len() == 3).await;
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(4).await;
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_that_times_out_is_sent_again() {
|
||||
let f = start(false, &[]);
|
||||
f.jdtls.stuck.store(true, Ordering::SeqCst);
|
||||
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
f.jdtls.stuck.store(false, Ordering::SeqCst);
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(3).await;
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_refused_every_time_is_reported_once_and_dropped() {
|
||||
let f = start(false, &[0, 1, 2, 3, 4, 5, 6, 7]);
|
||||
for attempt in 1..=1 + RETRY_DELAYS.len() {
|
||||
until("the next attempt", || f.jdtls.replaces().len() == attempt).await;
|
||||
skip(PAST_RETRY).await;
|
||||
}
|
||||
until("the failure", || !f.failures.lock().is_empty()).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.replaces().len(), 1 + RETRY_DELAYS.len());
|
||||
assert!(matches!(&f.failures.lock()[..], [text] if text.contains("Workspace is locked")));
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_restart_during_the_import_waits_for_the_new_instance() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.lsp.restart(f.jdtls_id()).await.unwrap();
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 2);
|
||||
f.jdtls.finish_import();
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true]);
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_lost_during_the_import_is_waited_for_again() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.jdtls.peer.lock().take().unwrap().kill();
|
||||
until("the restart after the crash", || f.jdtls.launches.load(Ordering::SeqCst) == 2).await;
|
||||
f.until_running().await;
|
||||
f.jdtls.finish_import();
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true]);
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stopping_jdtls_ends_the_wait_and_does_not_start_it_again() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.lsp.stop(f.jdtls_id()).await.unwrap();
|
||||
until("the failure", || !f.failures.lock().is_empty()).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 1);
|
||||
assert!(f.jdtls.replaces().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_the_project_ends_the_wait_at_once() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
let closing = Instant::now();
|
||||
f.bridge.shutdown().await;
|
||||
assert!(closing.elapsed() < Duration::from_secs(5), "{:?}", closing.elapsed());
|
||||
assert!(f.jdtls.replaces().is_empty());
|
||||
assert!(f.failures.lock().is_empty());
|
||||
assert!(f.tasks.lock().last().is_some_and(|(_, done)| *done), "the status bar task ends");
|
||||
}
|
||||
@@ -25,6 +25,8 @@ mod phpstan;
|
||||
pub mod plugins;
|
||||
mod project;
|
||||
mod proxy;
|
||||
mod python_move;
|
||||
mod python_signature;
|
||||
pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
|
||||
@@ -13,9 +13,9 @@ use ide_agent::{
|
||||
AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode,
|
||||
AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus,
|
||||
CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
|
||||
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult,
|
||||
McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -1205,6 +1205,42 @@ pub async fn agent_mcp_import_selected(
|
||||
})
|
||||
}
|
||||
|
||||
/// Searches or lists MCP servers from an open MCP Registry (`v0.1` / `v0`).
|
||||
/// When `registry_url` is omitted or blank, uses `agents.mcpRegistryUrl` or GitHub's MCP Registry.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_mcp_registry_search(
|
||||
host: &Host,
|
||||
registry_url: Option<String>,
|
||||
query: Option<String>,
|
||||
cursor: Option<String>,
|
||||
limit: Option<u32>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<McpRegistryPage> {
|
||||
let effective_url =
|
||||
registry_url.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).or_else(|| {
|
||||
let configured = host.global_settings.effective().agents.mcp_registry_url;
|
||||
let trimmed = configured.trim();
|
||||
(!trimmed.is_empty()).then(|| trimmed.to_owned())
|
||||
});
|
||||
let cancel = host.begin_request(request);
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::mcp_registry::HttpMcpRegistryFetcher::new(&search_path)?;
|
||||
ide_agent::mcp_registry::search_registry(
|
||||
&fetcher,
|
||||
effective_url.as_deref(),
|
||||
query.as_deref(),
|
||||
cursor.as_deref(),
|
||||
limit,
|
||||
&search_path,
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res
|
||||
}
|
||||
|
||||
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<McpProbeResult> {
|
||||
@@ -1440,11 +1476,12 @@ fn resolve_skills_with_host_plugins(
|
||||
);
|
||||
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
|
||||
ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_agent_plugins(
|
||||
ide_agent::skills::discover_skills_with_indexed_files(
|
||||
&policy.workspace_roots,
|
||||
home,
|
||||
&policy.plugin_dirs,
|
||||
&projected,
|
||||
&policy.indexed_skill_files,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
@@ -1664,6 +1701,13 @@ pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::Pa
|
||||
roots
|
||||
}
|
||||
|
||||
/// Non-ignored `SKILL.md` files currently known to `index`, used to discover deeply nested
|
||||
/// workspace skills without walking the filesystem again.
|
||||
pub(crate) fn indexed_skill_files(index: &ide_index::ProjectIndex) -> Vec<std::path::PathBuf> {
|
||||
let names = std::collections::HashSet::from([std::ffi::OsStr::new("SKILL.md")]);
|
||||
index.files_with_names(&names)
|
||||
}
|
||||
|
||||
/// The skill policies a session of `project` (or global Settings without a project) resolves against.
|
||||
fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPolicy {
|
||||
match project {
|
||||
@@ -1684,6 +1728,7 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
|
||||
workspace_trusted,
|
||||
workspace_roots: workspace_skill_roots(&project.root),
|
||||
plugin_dirs,
|
||||
indexed_skill_files: indexed_skill_files(&project.index),
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -1694,6 +1739,7 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
|
||||
workspace_trusted: true,
|
||||
workspace_roots: Vec::new(),
|
||||
plugin_dirs,
|
||||
indexed_skill_files: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2888,6 +2934,7 @@ ide_command::domain!(
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
agent_mcp_list,
|
||||
agent_mcp_registry_search,
|
||||
agent_mcp_remove,
|
||||
agent_mcp_save,
|
||||
agent_mcp_save_json,
|
||||
|
||||
@@ -1502,6 +1502,45 @@ pub async fn build_compile_file(
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Run dotnet format: `dotnet format` on a solution or project file (`verify`:
|
||||
/// `--verify-no-changes`), streaming like a build; cancellable with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn build_dotnet_format(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
file: std::path::PathBuf,
|
||||
verify: bool,
|
||||
request: RequestId,
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, sink) = (project.root.clone(), project.sink.clone());
|
||||
let file = ide_core::project_roots::resolve(&root, &file);
|
||||
let token = host.begin_project_request(window, request);
|
||||
let result = blocking(move || {
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.into(),
|
||||
source: compile::DIAGNOSTICS_SOURCE.into(),
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let plan = compile::dotnet_format_plan(&file, verify)?;
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
for (path, items) in compile::diagnostics(&result.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
}
|
||||
Ok::<_, IdeError>(result)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_tool_settings_tests {
|
||||
use super::*;
|
||||
@@ -1892,6 +1931,7 @@ mod maven_completion_tests {
|
||||
ide_command::domain!(
|
||||
build:
|
||||
build_compile_file,
|
||||
build_dotnet_format,
|
||||
build_model,
|
||||
build_run,
|
||||
build_sync,
|
||||
|
||||
@@ -126,6 +126,10 @@ async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() {
|
||||
.unwrap();
|
||||
let target = f.outside.with_extension("copy.txt");
|
||||
std::fs::write(&target, "old\n").unwrap();
|
||||
let error = doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old\n");
|
||||
std::fs::remove_file(&target).unwrap();
|
||||
|
||||
assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap());
|
||||
|
||||
|
||||
@@ -414,6 +414,12 @@ pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> I
|
||||
.await
|
||||
}
|
||||
|
||||
/// Whether both paths reach the same file, however they are spelled; fails when either is missing.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_same_file(host: &Host, a: PathBuf, b: PathBuf) -> IdeResult<bool> {
|
||||
host.blocking(move || ide_vfs::same_file(&a, &b)).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_rename(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
@@ -579,6 +585,7 @@ ide_command::domain!(
|
||||
fs_read_text,
|
||||
fs_read_texts,
|
||||
fs_rename,
|
||||
fs_same_file,
|
||||
fs_scratches_dir,
|
||||
fs_set_writable,
|
||||
fs_synchronize_directories,
|
||||
|
||||
@@ -102,16 +102,18 @@ pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_
|
||||
}
|
||||
|
||||
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
|
||||
/// (Navigate › Declaration on a variable), private file first.
|
||||
/// (Navigate › Declaration on a variable), private file first. With `env`, only the key a request
|
||||
/// run in that environment reads.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_variable_definitions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: IpcPath,
|
||||
name: String,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
|
||||
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name, env.as_deref()))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
|
||||
@@ -675,6 +675,25 @@ pub async fn lsp_switch_source_header(
|
||||
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// The document's Spring bean markers (injection points and bean declarations with their
|
||||
/// targets); `None` when no server attached to it provides them. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_spring_bean_markers(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
) -> IdeResult<Option<Vec<SpringBeanMarker>>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.spring_bean_markers(doc, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
|
||||
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -1590,8 +1609,13 @@ pub async fn lsp_signature_info(
|
||||
) -> IdeResult<MethodSignature> {
|
||||
// The signature of the method at `pos`, for Change Signature.
|
||||
let project = host.project(window)?;
|
||||
let python = project.documents.snapshot(doc)?.language.as_str() == "python";
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.change_signature_info(doc, pos, cancel).await;
|
||||
let result = if python {
|
||||
crate::python_signature::signature_info(host, window, doc, pos, cancel).await
|
||||
} else {
|
||||
project.lsp.change_signature_info(doc, pos, cancel).await
|
||||
};
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -1612,8 +1636,13 @@ pub async fn lsp_change_signature(
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let python = project.documents.snapshot(doc)?.language.as_str() == "python";
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.change_signature(doc, pos, signature, delegate, confirmation, cancel).await;
|
||||
let result = if python {
|
||||
crate::python_signature::change_signature(host, window, doc, pos, signature, confirmation, cancel).await
|
||||
} else {
|
||||
project.lsp.change_signature(doc, pos, signature, delegate, confirmation, cancel).await
|
||||
};
|
||||
host.end_request(request);
|
||||
let mut changed = result?;
|
||||
blocking(move || {
|
||||
@@ -1650,9 +1679,15 @@ pub async fn lsp_java_move_destinations(
|
||||
) -> IdeResult<Vec<String>> {
|
||||
// Where a Java Move code action of `kind` can go; `args` (JSON) carries the code action's own
|
||||
// arguments back unchanged, and each destination comes back as JSON.
|
||||
// For Python (`python_move`), the movable names of the module.
|
||||
let args = json_argument(&args)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
if project.documents.snapshot(doc)?.language.as_str() == "python" {
|
||||
let found = crate::python_move::symbols(host, window, doc, args, cancel).await;
|
||||
host.end_request(request);
|
||||
return found.map(json_strings);
|
||||
}
|
||||
let result = project.lsp.java_move_destinations(doc, kind, args, cancel).await;
|
||||
host.end_request(request);
|
||||
result.map(json_strings)
|
||||
@@ -1689,7 +1724,11 @@ pub async fn lsp_java_move(
|
||||
let args = json_argument(&args)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.java_move(doc, kind, args, confirmation, cancel).await;
|
||||
let result = if project.documents.snapshot(doc)?.language.as_str() == "python" {
|
||||
crate::python_move::move_symbols(host, window, doc, args, confirmation, cancel).await
|
||||
} else {
|
||||
project.lsp.java_move(doc, kind, args, confirmation, cancel).await
|
||||
};
|
||||
host.end_request(request);
|
||||
let mut moved = result?;
|
||||
blocking(move || {
|
||||
@@ -3442,6 +3481,7 @@ ide_command::domain!(
|
||||
lsp_hover,
|
||||
lsp_implementation_locations,
|
||||
lsp_file_references,
|
||||
lsp_spring_bean_markers,
|
||||
lsp_switch_source_header,
|
||||
lsp_source_definition,
|
||||
lsp_open_typescript_file,
|
||||
|
||||
@@ -130,6 +130,7 @@ ide_command::domains!(
|
||||
run_commands: crate::ops::run::commands,
|
||||
scaffold: crate::ops::scaffold,
|
||||
sdk: crate::ops::sdk,
|
||||
sdk_container_php: crate::ops::sdk::container_php,
|
||||
sdk_container_python: crate::ops::sdk::container_python,
|
||||
search: crate::ops::search,
|
||||
search_commands: crate::ops::search::commands,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_core::{FileEdit, IdeResult, IpcPath, Range, RequestId, WorkspaceEdit};
|
||||
use ide_language::Syntax;
|
||||
use ide_lsp::types::FileRenameEdits;
|
||||
use ide_workspace::Documents;
|
||||
@@ -70,7 +70,7 @@ pub async fn refactor_file_move_edits(
|
||||
result
|
||||
}
|
||||
|
||||
fn is_python(path: &Path) -> bool {
|
||||
pub(crate) fn is_python(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "py" || e == "pyi")
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ fn rel_path(root: &Path, path: &Path) -> Option<String> {
|
||||
|
||||
/// The dotted name of a Python module file or package folder and the root it is imported from
|
||||
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
|
||||
pub(crate) fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
|
||||
let rel = rel_path(root, path)?;
|
||||
let base = python_root(roots, &rel);
|
||||
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
|
||||
@@ -104,7 +104,7 @@ fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -
|
||||
}
|
||||
|
||||
/// The package relative imports in `file` start from.
|
||||
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
pub(crate) fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
|
||||
if file.file_stem().is_some_and(|s| s == "__init__") {
|
||||
module
|
||||
@@ -291,12 +291,179 @@ pub async fn refactor_file_move_text_edits(
|
||||
result
|
||||
}
|
||||
|
||||
/// A comment or string match added to a rename, with its line for the preview.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PythonMention {
|
||||
pub path: IpcPath,
|
||||
pub range: Range,
|
||||
pub line: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct PythonMentionEdits {
|
||||
/// The server's edit with the mentions merged in.
|
||||
pub edit: WorkspaceEdit,
|
||||
/// What was merged in, so the preview can show and drop each one.
|
||||
pub mentions: Vec<PythonMention>,
|
||||
}
|
||||
|
||||
/// Rename's "Search in comments and strings" for Python: adds the whole-word mentions of
|
||||
/// `old_name` to the server's rename `edit`, so they preview, apply and undo with it. A local
|
||||
/// symbol or parameter is searched in its function, anything else in the project's Python files.
|
||||
#[command(trust = always)]
|
||||
pub async fn refactor_python_mention_edits(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
old_name: String,
|
||||
new_name: String,
|
||||
edit: WorkspaceEdit,
|
||||
) -> IdeResult<PythonMentionEdits> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax().clone();
|
||||
let token = host.begin_request(request);
|
||||
let cancel = token.clone();
|
||||
let result = blocking(move || {
|
||||
let mut edit = edit;
|
||||
let found = python_mention_edits(
|
||||
&project.root,
|
||||
&project.exclude_globs(),
|
||||
&project.documents,
|
||||
&syntax,
|
||||
&old_name,
|
||||
&edit,
|
||||
&|| cancel.is_cancelled(),
|
||||
);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
let mut mentions = Vec::new();
|
||||
for file in found {
|
||||
let path = IpcPath::from(file.path);
|
||||
let mut existing = edit.files.iter_mut().find_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits, .. } if **p == *path => Some(edits),
|
||||
_ => None,
|
||||
});
|
||||
let lines: Vec<&str> = file.text.split('\n').collect();
|
||||
let mut added = Vec::new();
|
||||
for range in file.ranges {
|
||||
// The server may have renamed it already (`__all__`, a quoted annotation).
|
||||
let renamed = existing
|
||||
.as_ref()
|
||||
.is_some_and(|e| e.iter().any(|e| e.range.start < range.end && range.start < e.range.end));
|
||||
if !renamed {
|
||||
let line = lines.get(range.start.line as usize).copied().unwrap_or_default().to_owned();
|
||||
mentions.push(PythonMention { path: path.clone(), range, line });
|
||||
added.push(ide_core::TextEdit { range, new_text: new_name.clone() });
|
||||
}
|
||||
}
|
||||
if added.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match &mut existing {
|
||||
Some(existing) => existing.extend(added),
|
||||
None => edit.files.push(FileEdit::Edit { path, edits: added, version: None }),
|
||||
}
|
||||
// Apply refuses when a searched file changed after it was read.
|
||||
edit.preconditions.extend(file.preconditions);
|
||||
}
|
||||
Ok(PythonMentionEdits { edit, mentions })
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
struct Mentions {
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
ranges: Vec<Range>,
|
||||
/// Captured before `text` was read.
|
||||
preconditions: Vec<ide_core::WorkspaceEditPrecondition>,
|
||||
}
|
||||
|
||||
fn python_mention_edits(
|
||||
root: &Path,
|
||||
excludes: &[String],
|
||||
documents: &Documents,
|
||||
syntax: &Syntax,
|
||||
old: &str,
|
||||
edit: &WorkspaceEdit,
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> Vec<Mentions> {
|
||||
let renamed: Vec<(PathBuf, Vec<Range>)> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path, edits, .. } => Some((path.to_path_buf(), edits.iter().map(|e| e.range).collect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if old.is_empty() || !renamed.iter().any(|(path, _)| is_python(path)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let local: Vec<(PathBuf, Vec<Range>)> = renamed
|
||||
.iter()
|
||||
.filter(|(path, _)| is_python(path))
|
||||
.filter_map(|(path, ranges)| {
|
||||
let text = read_text(documents, path).ok()?;
|
||||
let scopes = syntax.python_rename_scope(&text, old, ranges, renamed.len() == 1);
|
||||
(!scopes.is_empty()).then(|| (path.clone(), scopes))
|
||||
})
|
||||
.collect();
|
||||
let Ok(real_root) = dunce::canonicalize(root) else { return Vec::new() };
|
||||
let found: Mutex<Vec<Mentions>> = Mutex::new(Vec::new());
|
||||
let search = |path: &Path, within: &[Range]| {
|
||||
// A symlink may lead out of the project.
|
||||
if !dunce::canonicalize(path).is_ok_and(|p| p.starts_with(&real_root)) {
|
||||
return;
|
||||
}
|
||||
// Cheap look first: most files never mention the name.
|
||||
let mentions = match documents.text_of(path) {
|
||||
Some(text) => text.contains(old),
|
||||
None => std::fs::read(path).is_ok_and(|b| String::from_utf8_lossy(&b).contains(old)),
|
||||
};
|
||||
if !mentions {
|
||||
return;
|
||||
}
|
||||
let mut guard = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit { path: path.into(), edits: Vec::new(), version: None }],
|
||||
..Default::default()
|
||||
};
|
||||
if documents.prepare_workspace_edit(&mut guard).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = read_text(documents, path) else { return };
|
||||
let ranges = syntax.python_mentions(&text, old, within);
|
||||
if !ranges.is_empty() {
|
||||
let preconditions = guard.preconditions;
|
||||
found.lock().push(Mentions { path: path.to_path_buf(), text, ranges, preconditions });
|
||||
}
|
||||
};
|
||||
if local.is_empty() {
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !cancelled() && is_python(path) {
|
||||
search(path, &[]);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
for (path, scopes) in &local {
|
||||
search(path, scopes);
|
||||
}
|
||||
}
|
||||
let mut files = found.into_inner();
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
files
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
refactor:
|
||||
refactor_can_undo_file_move,
|
||||
refactor_file_move_edits,
|
||||
refactor_file_move_text_edits,
|
||||
refactor_move_files,
|
||||
refactor_python_mention_edits,
|
||||
refactor_undo_file_move,
|
||||
);
|
||||
|
||||
|
||||
@@ -327,6 +327,10 @@ pub async fn run_start(
|
||||
let _ = on_output.send(chunk);
|
||||
});
|
||||
let operation = config.extras.params.get("plugin.operation").cloned();
|
||||
let plugin_debug =
|
||||
config.extras.params.contains_key("__pluginJavaDebug") || config.extras.params.contains_key("__pluginDebug");
|
||||
let user_owner = if operation.is_none() { crate::plugins::plugin_run_config_owner(&config)? } else { None };
|
||||
let user_config_snap = user_owner.as_ref().map(|_| config.clone());
|
||||
let mut config = config;
|
||||
let project = host.project(window)?;
|
||||
let agent = host.mcp_agent_runs.launch(&project.root, window, &mut config)?;
|
||||
@@ -351,8 +355,12 @@ pub async fn run_start(
|
||||
if let Some(id) = request {
|
||||
host.end_request(id);
|
||||
}
|
||||
if let (Ok(info), Some(operation), Some(plugins)) = (&result, operation, host.plugin_host()) {
|
||||
plugins.run_operation_started(window, &operation, info.id);
|
||||
if let (Ok(info), Some(plugins)) = (&result, host.plugin_host()) {
|
||||
if let Some(operation) = operation {
|
||||
plugins.run_operation_started(window, &operation, info.id);
|
||||
} else if let (Some(owner), Some(snap)) = (&user_owner, &user_config_snap) {
|
||||
plugins.user_run_started(window, owner, snap, info.id, plugin_debug);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -389,6 +397,7 @@ async fn start_inner(
|
||||
IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "plugin host is not available")
|
||||
})?;
|
||||
direct_stop = plugins.authorize_run_config(&project.root, &owner, &mut config)?;
|
||||
sink = plugins.user_run_exit_sink(window, &owner, &config, sink);
|
||||
plugin_authorized = true;
|
||||
}
|
||||
if let Some(agent) = agent {
|
||||
@@ -1232,6 +1241,39 @@ pub async fn run_container_path(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Where the debugger listens for the Xdebug of a PHP run in a container of `target`, and the
|
||||
/// folders the container mounts.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContainerXdebug {
|
||||
/// A free port on this machine.
|
||||
pub port: u16,
|
||||
/// `(folder in the container, folder here)`, the project's first.
|
||||
pub mounts: Vec<(String, ide_core::IpcPath)>,
|
||||
}
|
||||
|
||||
/// What debugging PHP in a container of the Docker or Compose run target `target` needs before
|
||||
/// the run starts: the debugger listens first, then Xdebug connects to it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_container_xdebug(host: &Host, window: &str, target: String) -> IdeResult<ContainerXdebug> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
let run_target = ide_remote::service::run_target(&settings, &target)?;
|
||||
if !matches!(run_target.kind, RunTargetKind::Docker | RunTargetKind::Compose) {
|
||||
return Err(IdeError::invalid(format!("Run target '{}' is not a container", run_target.name)));
|
||||
}
|
||||
let (root, data_dir) = (project.root.clone(), host.data_dir.clone());
|
||||
host.blocking(move || {
|
||||
let mounts = container::mounts(&data_dir, &root, &run_target)?;
|
||||
Ok(ContainerXdebug {
|
||||
port: container::free_port()?,
|
||||
mounts: mounts.into_iter().map(|(here, there)| (there, here.into())).collect(),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `config` for a container or WSL distribution: without what settings derived from this
|
||||
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
|
||||
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
|
||||
@@ -1282,6 +1324,7 @@ ide_command::domain!(
|
||||
run_close_stdin,
|
||||
run_configs,
|
||||
run_container_path,
|
||||
run_container_xdebug,
|
||||
run_list,
|
||||
run_resize,
|
||||
run_save_configs,
|
||||
|
||||
@@ -9,7 +9,7 @@ use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
|
||||
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_remote::target::{DEBUG_PARAM, XDEBUG_PORT_PARAM};
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -28,12 +28,24 @@ pub(super) async fn prepare(
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
let php = debug && config.debug_adapter.as_deref() == Some("php-debug");
|
||||
if debug && !php && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
|
||||
"'{}' can't be debugged in a container: only Python, Node.js and PHP run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
// Xdebug connects to the debugger, which listens already: nothing is mounted or published.
|
||||
let xdebug = match config.extras.params.get(XDEBUG_PORT_PARAM).map(|p| p.parse::<u16>()) {
|
||||
Some(Ok(port)) if php => Some(port),
|
||||
_ if php => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' has no port for Xdebug to connect to: debug it with the Debug action",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let endpoint = endpoint(&host.data_dir, &target)?;
|
||||
let root = root.to_path_buf();
|
||||
let data_dir = host.data_dir.clone();
|
||||
@@ -46,7 +58,7 @@ pub(super) async fn prepare(
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
let debugging = if debug && !php { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
|
||||
let config = container_config(
|
||||
&config,
|
||||
@@ -66,6 +78,7 @@ pub(super) async fn prepare(
|
||||
bootstrap_dir: &d.bootstrap_dir,
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
xdebug,
|
||||
},
|
||||
)?;
|
||||
Ok((config, note))
|
||||
@@ -179,6 +192,102 @@ fn compose_service_of(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeRe
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// The Docker or Compose run target PHP runs in: **Run in target** of Settings › PHP, else the
|
||||
/// project's default target.
|
||||
pub(crate) fn php_target(settings: &ide_core::settings::Settings) -> Option<RunTarget> {
|
||||
let id = match settings.languages.php.run_target.trim() {
|
||||
"local" => return None,
|
||||
"" => settings.run.default_target.trim(),
|
||||
id => id,
|
||||
};
|
||||
let container = |t: &&RunTarget| t.id == id && matches!(t.kind, RunTargetKind::Docker | RunTargetKind::Compose);
|
||||
settings.run_targets.iter().find(container).cloned()
|
||||
}
|
||||
|
||||
/// A run target's containers for the tools of the project that PHP runs (PHPStan, PHP-CS-Fixer).
|
||||
pub(crate) struct PhpContainer {
|
||||
target: RunTarget,
|
||||
root: PathBuf,
|
||||
container_root: String,
|
||||
docker: PathBuf,
|
||||
env: BTreeMap<String, String>,
|
||||
mounts: Mounts,
|
||||
user: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl PhpContainer {
|
||||
pub(crate) fn open(data_dir: &Path, root: &Path, target: &RunTarget) -> IdeResult<Self> {
|
||||
let endpoint = endpoint(data_dir, target)?;
|
||||
require_local(&endpoint, target)?;
|
||||
let docker = ide_docker::docker_executable().ok_or_else(|| {
|
||||
IdeError::unavailable("docker executable not found; install Docker and make sure it is on PATH")
|
||||
})?;
|
||||
let mounts = mounts(data_dir, root, target)?;
|
||||
// A Docker target mounts the project there; a Compose service has its own mounts.
|
||||
let container_root = match mounts.as_slice() {
|
||||
[(_, folder)] if target.kind == RunTargetKind::Docker => folder.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
Ok(Self {
|
||||
target: target.clone(),
|
||||
root: root.to_path_buf(),
|
||||
container_root,
|
||||
docker,
|
||||
env: ide_docker::run_env(&endpoint),
|
||||
mounts,
|
||||
user: user(root, target),
|
||||
})
|
||||
}
|
||||
|
||||
/// `file` as the container names it.
|
||||
pub(crate) fn path(&self, file: &Path) -> IdeResult<String> {
|
||||
ide_remote::docker::container_file(file, &self.mounts).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is not in a folder that run target '{}' mounts",
|
||||
file.display(),
|
||||
self.target.name
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The file here of a path the tool reports.
|
||||
pub(crate) fn local(&self, path: &str) -> Option<PathBuf> {
|
||||
ide_remote::docker::mounted_file(path, &self.mounts)
|
||||
}
|
||||
|
||||
/// `php args` in a new container, run in its folder `cwd`, and the container's name.
|
||||
pub(crate) fn command(
|
||||
&self,
|
||||
cwd: &str,
|
||||
volumes: &[(PathBuf, String)],
|
||||
args: &[String],
|
||||
) -> IdeResult<(std::process::Command, String)> {
|
||||
let name = container_name("php-tool", &unique());
|
||||
let tool = ide_remote::docker::PhpTool {
|
||||
target: &self.target,
|
||||
root: &self.root,
|
||||
container_root: &self.container_root,
|
||||
name: &name,
|
||||
cwd,
|
||||
volumes,
|
||||
user: self.user,
|
||||
};
|
||||
let mut command = std::process::Command::new(&self.docker);
|
||||
command.args(ide_remote::docker::php_tool_args(&tool, args)?).envs(&self.env).current_dir(&self.root);
|
||||
Ok((command, name))
|
||||
}
|
||||
|
||||
/// Stops a tool: ending the docker CLI leaves its container running.
|
||||
pub(crate) fn remove(&self, name: &str) {
|
||||
use std::process::Stdio;
|
||||
let mut command = std::process::Command::new(&self.docker);
|
||||
command.args(["rm", "--force", name]).envs(&self.env);
|
||||
command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
ide_core::process::prepare(&mut command);
|
||||
let _ = command.status();
|
||||
}
|
||||
}
|
||||
|
||||
/// Variables a development server in the container finds besides the configuration's: the
|
||||
/// Compose service's `environment` (and published ports), and the `.env` / `.flaskenv` of the
|
||||
/// folder it runs in. Best effort: a Compose file `docker compose config` can't read gives none.
|
||||
@@ -226,8 +335,8 @@ pub(super) fn ide_debugpy(data_dir: &Path) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// A port nobody listens on here: debugpy listens on the same port in the container,
|
||||
/// published on the loopback interface.
|
||||
fn free_port() -> IdeResult<u16> {
|
||||
/// published on the loopback interface; the PHP debugger listens on it for Xdebug.
|
||||
pub(super) fn free_port() -> IdeResult<u16> {
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
|
||||
Ok(listener.local_addr()?.port())
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub mod container_php;
|
||||
pub mod container_python;
|
||||
pub use container_php::{ContainerPhp, sdk_container_php};
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
|
||||
|
||||
/// Executables found for "run this file", and where single files are compiled to.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The PHP of a Docker or Compose run target: its version and the Xdebug it loads, read by
|
||||
//! running it once in a new container (the image's entrypoint and the service's dependencies
|
||||
//! skipped), removed when it exits. Nothing is installed in the container.
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Building or pulling the image may come first.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
|
||||
|
||||
/// What a run target's PHP is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContainerPhp {
|
||||
/// The run target's id and name.
|
||||
pub target: String,
|
||||
pub name: String,
|
||||
pub php_version: String,
|
||||
/// The Xdebug version; `None`: not loaded.
|
||||
pub xdebug: Option<String>,
|
||||
}
|
||||
|
||||
/// Answers by project and target, as the target was configured when it was asked: a container
|
||||
/// takes seconds to start, and the settings page asks each time it is shown.
|
||||
static KNOWN: LazyLock<Mutex<HashMap<(PathBuf, String), ContainerPhp>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn key(root: &Path, target: &RunTarget) -> (PathBuf, String) {
|
||||
(root.to_path_buf(), serde_json::to_string(target).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The version of the PHP of the run target `target` (a Docker or Compose one) and of the Xdebug
|
||||
/// it loads. Asked once per target configuration; `refresh` asks again (after the image changed).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn sdk_container_php(host: &Host, window: &str, target: String, refresh: bool) -> IdeResult<ContainerPhp> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
let target = ide_remote::service::run_target(&settings, &target)?;
|
||||
if !matches!(target.kind, RunTargetKind::Docker | RunTargetKind::Compose) {
|
||||
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
|
||||
}
|
||||
let key = key(&project.root, &target);
|
||||
if !refresh && let Some(known) = KNOWN.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
return Ok(known.clone());
|
||||
}
|
||||
let endpoint = crate::ops::run::container::endpoint(&host.data_dir, &target)?;
|
||||
let root = project.root.clone();
|
||||
let found = host.blocking(move || probe(&endpoint, &root, &target)).await?;
|
||||
KNOWN.lock().unwrap_or_else(|e| e.into_inner()).insert(key, found.clone());
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn probe(endpoint: &ide_docker::DockerEndpoint, root: &Path, target: &RunTarget) -> IdeResult<ContainerPhp> {
|
||||
let args = ide_remote::docker::php_probe_args(target, root, ide_sdk::php::XDEBUG_PROBE)?;
|
||||
let out = ide_docker::cli(endpoint, Some(root), &args, PROBE_TIMEOUT, None)?;
|
||||
let (php_version, xdebug) = ide_sdk::php::parse_xdebug(&out).ok_or_else(|| {
|
||||
IdeError::invalid(format!("The PHP of run target '{}' printed no version: {out}", target.name))
|
||||
})?;
|
||||
Ok(ContainerPhp { target: target.id.clone(), name: target.name.clone(), php_version, xdebug })
|
||||
}
|
||||
|
||||
ide_command::domain!(sdk_container_php: sdk_container_php);
|
||||
@@ -149,10 +149,11 @@ pub async fn replace_preview(
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Validates a query (e.g. regex syntax) while the user types.
|
||||
/// Validates a query (e.g. regex syntax), and what Replace would insert, while the user types.
|
||||
#[command(trust = always)]
|
||||
pub fn search_validate(query: SearchQuery) -> IdeResult<()> {
|
||||
ide_search::validate_query(&query)
|
||||
pub fn search_validate(query: SearchQuery, replacement: Option<String>) -> IdeResult<()> {
|
||||
ide_search::validate_query(&query)?;
|
||||
replacement.map_or(Ok(()), |r| ide_search::validate_replacement(&query, &r))
|
||||
}
|
||||
|
||||
ide_command::domain!(search_commands: replace_in_files, replace_preview, search_validate);
|
||||
@@ -256,6 +256,11 @@ pub enum RemoteOp {
|
||||
UpdateProjectBranch {
|
||||
rebase: bool,
|
||||
},
|
||||
/// Subversion › Update File / Update Directory: `svn update` of these paths of the
|
||||
/// working copy only.
|
||||
UpdateFiles {
|
||||
paths: Vec<PathBuf>,
|
||||
},
|
||||
UpdateSubmodule {
|
||||
parent: PathBuf,
|
||||
},
|
||||
@@ -345,6 +350,15 @@ pub enum RemoteOp {
|
||||
pub enum RemoteOpReport {
|
||||
Push(PushReport),
|
||||
Fetch(FetchReport),
|
||||
Update(UpdateReport),
|
||||
}
|
||||
|
||||
/// What an update of a non-Git working copy (`svn update`) changed.
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateReport {
|
||||
/// Files and folders added, deleted, changed or merged.
|
||||
pub updated_files: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
@@ -1976,12 +1990,22 @@ pub async fn vcs_remote(
|
||||
_ => None,
|
||||
};
|
||||
// Update Project on a non-Git working copy is its own update (`svn update`, `p4 sync`).
|
||||
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
|
||||
let paths = match &op {
|
||||
RemoteOp::UpdateFiles { paths } => Some(paths.as_slice()),
|
||||
RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. } => Some(&[][..]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(paths) = paths
|
||||
&& project.backend_at(repo.as_deref()).is_some()
|
||||
{
|
||||
let result = with_shelf_batch(&project, shelf_batch, || {
|
||||
project
|
||||
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
|
||||
project.with_backend_recorded(repo.as_deref(), Some("Update"), |b| {
|
||||
b.update(paths, &cancel, &out).map(|changed| {
|
||||
Some(RemoteOpReport::Update(UpdateReport {
|
||||
updated_files: u32::try_from(changed).unwrap_or(u32::MAX),
|
||||
}))
|
||||
})
|
||||
})
|
||||
});
|
||||
// An update brings or takes away externals (working copies of their own): the roots
|
||||
// are known when it returns, not only once a later scan runs.
|
||||
@@ -2025,6 +2049,9 @@ pub async fn vcs_remote(
|
||||
RemoteOp::InitSubmodules => r.init_submodules(&cancel, &out).map(|()| None),
|
||||
RemoteOp::SyncSubmodules => r.sync_submodules(&cancel, &out).map(|()| None),
|
||||
RemoteOp::ResetToUpstream => r.reset_to_upstream_with_tags(tags_mode, &cancel, &out).map(|()| None),
|
||||
RemoteOp::UpdateFiles { .. } => Err(ide_core::IdeError::invalid(
|
||||
"Update File is for working copies of other version control systems",
|
||||
)),
|
||||
RemoteOp::Push { force_with_lease, set_upstream, tags, force, no_verify } => r
|
||||
.push_with(PushOptions { force_with_lease, force, set_upstream, tags, no_verify }, &cancel, &out)
|
||||
.map(|report| Some(RemoteOpReport::Push(report))),
|
||||
|
||||
@@ -55,7 +55,7 @@ pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult<Stri
|
||||
let project = host.project(window).ok();
|
||||
let root = project.as_ref().map(|p| p.root.as_path());
|
||||
let languages = project.as_ref().map_or(&host.languages, |p| &p.languages);
|
||||
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") {
|
||||
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html" | "jinja-html") {
|
||||
host.web.page_url_for(root, &path).await
|
||||
} else {
|
||||
host.web.url_for(root, &path).await
|
||||
|
||||
@@ -240,8 +240,8 @@ fn index_build(
|
||||
sink: &ide_core::SharedSink,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<XcodeIndexBuild> {
|
||||
let params = ide_run::xcode::first_run_params(root)
|
||||
.ok_or_else(|| IdeError::unavailable("The Xcode project has no scheme to build"))?;
|
||||
// Nothing Run could build either: no build, no warning.
|
||||
let Some(params) = ide_run::xcode::first_run_params(root) else { return Ok(XcodeIndexBuild::NotNeeded) };
|
||||
let scheme = params.get("scheme").cloned().unwrap_or_default();
|
||||
let task = TaskId::next();
|
||||
let _cancel_handle = ide_core::task::on_cancel(task, {
|
||||
@@ -271,6 +271,15 @@ ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate, xcode_index
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_index_build_skips_a_project_without_a_scheme_quietly() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("App.xcodeproj")).unwrap();
|
||||
let sink: ide_core::SharedSink = std::sync::Arc::new(ide_core::NullSink);
|
||||
let result = index_build(tmp.path(), &tmp.path().join("DerivedData"), &sink, &CancellationToken::new());
|
||||
assert_eq!(result.unwrap(), XcodeIndexBuild::NotNeeded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_the_workspace_and_skips_configured_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
//! Saved PHP files -> `vendor/bin/phpstan analyse` -> `phpstan` diagnostics.
|
||||
|
||||
use crate::ops::run::container::{PhpContainer, php_target};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_core::remote_settings::RunTarget;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, IdeResult, Pos, Range, Severity, SharedSink};
|
||||
use ide_text::AppliedChange;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -44,6 +47,8 @@ impl Queue {
|
||||
pub(crate) struct Phpstan {
|
||||
root: PathBuf,
|
||||
config_dir: PathBuf,
|
||||
/// Where the Docker connections of run targets are kept.
|
||||
data_dir: PathBuf,
|
||||
settings: Arc<SettingsStore>,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
@@ -60,6 +65,7 @@ impl Phpstan {
|
||||
pub(crate) fn new(
|
||||
root: PathBuf,
|
||||
config_dir: PathBuf,
|
||||
data_dir: PathBuf,
|
||||
settings: Arc<SettingsStore>,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
@@ -67,6 +73,7 @@ impl Phpstan {
|
||||
Arc::new(Self {
|
||||
root,
|
||||
config_dir,
|
||||
data_dir,
|
||||
settings,
|
||||
sink,
|
||||
trusted,
|
||||
@@ -159,8 +166,9 @@ impl Phpstan {
|
||||
continue;
|
||||
}
|
||||
let (root, config_dir, settings) = (self.root.clone(), self.config_dir.clone(), self.settings.clone());
|
||||
let data_dir = self.data_dir.clone();
|
||||
let Ok((checks, unchecked)) =
|
||||
tokio::task::spawn_blocking(move || plan(&root, &config_dir, &settings, files)).await
|
||||
tokio::task::spawn_blocking(move || plan(&root, &config_dir, &data_dir, &settings, files)).await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
@@ -170,8 +178,15 @@ impl Phpstan {
|
||||
let mut checks = checks.into_iter();
|
||||
while let Some(check) = checks.next() {
|
||||
let started = std::time::Instant::now();
|
||||
let program = check.command.get_program().to_string_lossy().into_owned();
|
||||
let output = analyse(check.command, &cancel).await;
|
||||
let (output, container) = match check.run {
|
||||
Ok(run) => {
|
||||
let program = run.command.get_program().to_string_lossy().into_owned();
|
||||
let output = analyse(run.command, run.container.clone(), &cancel).await;
|
||||
(output.map(|o| o.map_err(|error| format!("Cannot run {program}: {error}"))), run.container)
|
||||
}
|
||||
// The run target's container can't be started as the settings describe it.
|
||||
Err(text) => (Some(Err(text)), None),
|
||||
};
|
||||
let Some(output) = output.filter(|_| self.queue.lock().current(generation)) else {
|
||||
// A newer save: these files are checked again with it.
|
||||
let mut queue = self.queue.lock();
|
||||
@@ -206,14 +221,19 @@ impl Phpstan {
|
||||
}
|
||||
})
|
||||
}
|
||||
Err(error) => Err(format!("Cannot run {program}: {error}")),
|
||||
Err(text) => Err(text),
|
||||
};
|
||||
let failure = match report {
|
||||
Ok(report) => {
|
||||
let files = check.files.clone();
|
||||
let results = tokio::task::spawn_blocking(move || diagnostics(&files, report.files))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let results = tokio::task::spawn_blocking(move || {
|
||||
diagnostics(&files, report.files, &|name| match &container {
|
||||
Some(container) => container.php.local(name),
|
||||
None => Some(PathBuf::from(name)),
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for (path, items) in results {
|
||||
// Edited while the saved text was checked: its lines moved since.
|
||||
if self.edited.lock().contains(&path) {
|
||||
@@ -291,7 +311,27 @@ async fn debounce(cancel: &CancellationToken, lifetime: &CancellationToken) -> b
|
||||
struct Check {
|
||||
root: PathBuf,
|
||||
files: Vec<PathBuf>,
|
||||
/// The text to report when the run can't be started (a run target that no longer works).
|
||||
run: Result<Run, String>,
|
||||
}
|
||||
|
||||
struct Run {
|
||||
command: Command,
|
||||
/// PHP runs in a container run target: PHPStan names the files as the container does.
|
||||
container: Option<Arc<Container>>,
|
||||
}
|
||||
|
||||
struct Container {
|
||||
php: PhpContainer,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The check of `files` in a new container of `target`, the run target PHP runs in.
|
||||
fn container_run(data_dir: &Path, root: &Path, s: &Settings, target: &RunTarget, files: &[PathBuf]) -> IdeResult<Run> {
|
||||
let php = PhpContainer::open(data_dir, root, target)?;
|
||||
let args = ide_sdk::php::phpstan_container_args(root, s, files, &|file| php.path(file))?;
|
||||
let (command, name) = php.command(&php.path(root)?, &[], &args)?;
|
||||
Ok(Run { command, container: Some(Arc::new(Container { php, name })) })
|
||||
}
|
||||
|
||||
/// The runs that check `files`, and the files not checked, whose earlier diagnostics no longer
|
||||
@@ -301,6 +341,7 @@ struct Check {
|
||||
fn plan(
|
||||
project: &Path,
|
||||
config_dir: &Path,
|
||||
data_dir: &Path,
|
||||
settings: &SettingsStore,
|
||||
files: BTreeSet<PathBuf>,
|
||||
) -> (Vec<Check>, Vec<PathBuf>) {
|
||||
@@ -328,16 +369,27 @@ fn plan(
|
||||
f.strip_prefix(&root).is_ok_and(|rel| !rel.starts_with("vendor") && !excludes.is_excluded(rel))
|
||||
});
|
||||
unchecked.extend(skipped);
|
||||
match ide_sdk::php::phpstan_command(&root, &effective, &files).filter(|_| !files.is_empty()) {
|
||||
Some(command) => checks.push(Check { root, files, command }),
|
||||
let run = match php_target(&effective) {
|
||||
Some(target) => ide_sdk::php::has_phpstan(&root)
|
||||
.then(|| container_run(data_dir, &root, &effective, &target, &files).map_err(|e| e.message)),
|
||||
None => ide_sdk::php::phpstan_command(&root, &effective, &files)
|
||||
.map(|command| Ok(Run { command, container: None })),
|
||||
};
|
||||
match run.filter(|_| !files.is_empty()) {
|
||||
Some(run) => checks.push(Check { root, files, run }),
|
||||
None => unchecked.extend(files),
|
||||
}
|
||||
}
|
||||
(checks, unchecked)
|
||||
}
|
||||
|
||||
/// Runs `cmd` to its end; `None` when `cancel` fires first, which kills it.
|
||||
async fn analyse(mut cmd: Command, cancel: &CancellationToken) -> Option<std::io::Result<Output>> {
|
||||
/// Runs `cmd` to its end; `None` when `cancel` fires first, which kills it, and removes its
|
||||
/// container: that outlives the docker CLI.
|
||||
async fn analyse(
|
||||
mut cmd: Command,
|
||||
container: Option<Arc<Container>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<std::io::Result<Output>> {
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
@@ -354,14 +406,19 @@ async fn analyse(mut cmd: Command, cancel: &CancellationToken) -> Option<std::io
|
||||
// PHPStan may start workers of its own.
|
||||
let cancelled = async {
|
||||
cancel.cancelled().await;
|
||||
if let Some(container) = container {
|
||||
let _ = tokio::task::spawn_blocking(move || container.php.remove(&container.name)).await;
|
||||
}
|
||||
if let Some(pid) = pid {
|
||||
let _ = tokio::task::spawn_blocking(move || ide_core::process::kill_tree_of(pid)).await;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
let output = tokio::select! {
|
||||
output = child.wait_with_output() => Some(output),
|
||||
() = cancelled => None,
|
||||
}
|
||||
};
|
||||
// Removing the container ends the docker CLI before the cancellation is through.
|
||||
output.filter(|_| !cancel.is_cancelled())
|
||||
}
|
||||
|
||||
/// A PHPStan message: 0-based line, text with its tip, identifier.
|
||||
@@ -466,14 +523,21 @@ fn failure_text(stdout: &str, stderr: &str) -> String {
|
||||
}
|
||||
|
||||
/// The diagnostics of each checked file (none for a clean one), matched to the report's files
|
||||
/// by their real paths. Errors PHPStan reports in a trait name the class using it
|
||||
/// by their real paths; `local` gives the file here of a name in the report (a container's
|
||||
/// differ). Errors PHPStan reports in a trait name the class using it
|
||||
/// (`Trait.php (in context of class Foo)`).
|
||||
fn diagnostics(files: &[PathBuf], reported: BTreeMap<String, Vec<Message>>) -> Vec<(PathBuf, Vec<Diagnostic>)> {
|
||||
fn diagnostics(
|
||||
files: &[PathBuf],
|
||||
reported: BTreeMap<String, Vec<Message>>,
|
||||
local: &dyn Fn(&str) -> Option<PathBuf>,
|
||||
) -> Vec<(PathBuf, Vec<Diagnostic>)> {
|
||||
let real = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
let mut messages: BTreeMap<PathBuf, Vec<Message>> = BTreeMap::new();
|
||||
for (name, list) in reported {
|
||||
let name = name.split(" (in context of ").next().unwrap_or(&name);
|
||||
messages.entry(real(Path::new(name))).or_default().extend(list);
|
||||
if let Some(file) = local(name) {
|
||||
messages.entry(real(&file)).or_default().extend(list);
|
||||
}
|
||||
}
|
||||
files
|
||||
.iter()
|
||||
@@ -517,6 +581,67 @@ fn line_range(text: Option<&str>, line: u32) -> Range {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// With a real Docker daemon:
|
||||
/// `cargo test -p ide-host --lib phpstan::tests::a_container_run_target -- --ignored`.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires a Docker daemon and the php:8.3-cli image"]
|
||||
async fn a_container_run_target_checks_the_files_and_names_them_here() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(root.join("vendor/bin")).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
// Stands in for PHPStan: an error in its last argument, the file as the container names it.
|
||||
let phpstan = r#"<?php
|
||||
$message = getenv('XDEBUG_MODE') . ' ' . getcwd() . ' ' . implode(' ', array_slice($argv, 1, 3));
|
||||
$messages = [['message' => $message, 'line' => 2, 'ignorable' => true, 'identifier' => 'test.id']];
|
||||
echo json_encode(['totals' => ['errors' => 0, 'file_errors' => 1],
|
||||
'files' => [end($argv) => ['errors' => 1, 'messages' => $messages]], 'errors' => []]);
|
||||
exit(1);
|
||||
"#;
|
||||
std::fs::write(root.join("vendor/bin/phpstan"), phpstan).unwrap();
|
||||
let settings = "[[runTargets]]\nkind = \"docker\"\nid = \"php\"\nname = \"PHP\"\nimage = \"php:8.3-cli\"\n\n\
|
||||
[languages.php]\nrunTarget = \"php\"\n";
|
||||
std::fs::write(root.join(".openidea/settings.toml"), settings).unwrap();
|
||||
let file = root.join("src").join("A.php");
|
||||
std::fs::write(&file, "<?php\n\necho UNKNOWN;\n").unwrap();
|
||||
let settings = SettingsStore::load(&base.join("config"), Some(&root));
|
||||
|
||||
let files = BTreeSet::from([file.clone()]);
|
||||
let (mut checks, unchecked) = plan(&root, &base.join("config"), &base.join("data"), &settings, files);
|
||||
assert!(unchecked.is_empty(), "{unchecked:?}");
|
||||
let run = checks.pop().unwrap().run.unwrap();
|
||||
let container = run.container.clone().expect("PHP runs in the container");
|
||||
let output = analyse(run.command, run.container, &CancellationToken::new()).await.unwrap().unwrap();
|
||||
let (stdout, stderr) = (decode_tool_output(&output.stdout), decode_tool_output(&output.stderr));
|
||||
let report = parse(&stdout, &stderr).unwrap_or_else(|text| panic!("{text}"));
|
||||
let out = diagnostics(std::slice::from_ref(&file), report.files, &|name| container.php.local(name));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].0, file, "the container's /workspaces/project/src/A.php is this file");
|
||||
let messages: Vec<&str> = out[0].1.iter().map(|d| d.message.as_str()).collect();
|
||||
assert_eq!(messages, ["off /workspaces/project analyse --error-format=json --no-progress"]);
|
||||
assert_eq!(out[0].1[0].range.start.line, 1, "PHPStan counts lines from 1");
|
||||
|
||||
// A check a newer save cancels leaves no container behind.
|
||||
std::fs::write(root.join("vendor/bin/phpstan"), "<?php sleep(60);").unwrap();
|
||||
let files = BTreeSet::from([file.clone()]);
|
||||
let (mut checks, _) = plan(&root, &base.join("config"), &base.join("data"), &settings, files);
|
||||
let run = checks.pop().unwrap().run.unwrap();
|
||||
let name = run.container.as_ref().unwrap().name.clone();
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(4)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
assert!(analyse(run.command, run.container, &cancel).await.is_none());
|
||||
let docker = ide_docker::docker_executable().unwrap();
|
||||
let left =
|
||||
Command::new(docker).args(["ps", "--all", "--quiet", "--filter"]).arg(format!("name={name}")).output();
|
||||
assert_eq!(String::from_utf8_lossy(&left.unwrap().stdout).trim(), "", "the container is removed");
|
||||
}
|
||||
|
||||
const REPORT: &str = r#"{"totals":{"errors":0,"file_errors":3},"files":{
|
||||
"/p/src/A.php":{"errors":2,"messages":[
|
||||
{"message":"Constant UNKNOWN not found.","line":11,"ignorable":true,
|
||||
@@ -603,7 +728,8 @@ mod tests {
|
||||
(format!("{} (in context of class A)", t.display()), vec![message(0, "In a trait", "trait.x")]),
|
||||
("/elsewhere/B.php".to_string(), vec![message(0, "Not checked", "x")]),
|
||||
]);
|
||||
let out = diagnostics(&[a.clone(), t.clone(), clean.clone()], reported);
|
||||
let here = |name: &str| Some(PathBuf::from(name));
|
||||
let out = diagnostics(&[a.clone(), t.clone(), clean.clone()], reported, &here);
|
||||
assert_eq!(
|
||||
out.iter().map(|(p, items)| (p.clone(), items.len())).collect::<Vec<_>>(),
|
||||
[(a, 1), (t, 1), (clean, 0)]
|
||||
@@ -678,7 +804,7 @@ mod tests {
|
||||
let sink_events = events.clone();
|
||||
let sink: SharedSink = Arc::new(move |e| sink_events.lock().push(e));
|
||||
let trusted = Arc::new(AtomicBool::new(true));
|
||||
let checker = Phpstan::new(root.clone(), config, settings, sink, trusted.clone());
|
||||
let checker = Phpstan::new(root.clone(), config, base.join("data"), settings, sink, trusted.clone());
|
||||
checker.start(&tokio::runtime::Handle::current());
|
||||
Self { _dir: dir, root, events, trusted, checker }
|
||||
}
|
||||
|
||||
@@ -763,6 +763,7 @@ pub(super) struct Shared {
|
||||
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
|
||||
pub(super) run_targets: Mutex<super::run_targets::Targets>,
|
||||
pub(super) operations: Mutex<BTreeMap<String, super::execution::Operation>>,
|
||||
pub(super) active_plugin_runs: Mutex<BTreeMap<ide_core::RunId, super::execution::ActivePluginRun>>,
|
||||
pub(super) content_tabs: Mutex<BTreeMap<(String, String, String), ide_plugin::ContentTab>>,
|
||||
pub(super) content_requests: Mutex<ContentRequests>,
|
||||
|
||||
@@ -873,6 +874,7 @@ impl Shared {
|
||||
run_configurations: Arc::default(),
|
||||
run_targets: Mutex::default(),
|
||||
operations: Mutex::default(),
|
||||
active_plugin_runs: Mutex::default(),
|
||||
content_tabs: Mutex::default(),
|
||||
content_requests: Mutex::default(),
|
||||
|
||||
@@ -1904,7 +1906,12 @@ impl HostApi for PluginApi {
|
||||
run.args.extend(args);
|
||||
let id = self.new_operation(
|
||||
client,
|
||||
super::execution::OperationKind::Run { config: config.into(), configuration: run.id.clone(), program },
|
||||
super::execution::OperationKind::Run {
|
||||
config: config.into(),
|
||||
configuration: run.id.clone(),
|
||||
program,
|
||||
debug,
|
||||
},
|
||||
)?;
|
||||
run.extras.params.insert(super::execution::RUN_OPERATION.into(), id.clone());
|
||||
let request = super::WindowRequest::Run { operation: id.clone(), config: Box::new(run), debug };
|
||||
@@ -1914,6 +1921,80 @@ impl HostApi for PluginApi {
|
||||
);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn stop_run(&self, client: &str, id: &str, cancel: &CancellationToken, timeout: Duration) -> Result<(), HostError> {
|
||||
self.require_api("`run.stop`", 21)?;
|
||||
let target_id = {
|
||||
let mut ops = self.shared.operations.lock();
|
||||
if let Some(op) = ops.get_mut(id).filter(|op| {
|
||||
op.plugin == self.id()
|
||||
&& op.client == client
|
||||
&& matches!(op.kind, super::execution::OperationKind::Run { .. })
|
||||
}) {
|
||||
op.closed = true;
|
||||
Some(op.run.map_or_else(|| id.to_owned(), |r| r.0.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
.or_else(|| {
|
||||
let mut runs = self.shared.active_plugin_runs.lock();
|
||||
runs.values_mut()
|
||||
.find(|r| {
|
||||
r.plugin == self.id()
|
||||
&& r.client == client
|
||||
&& (format!("run-{}", r.run_id.0) == id || r.run_id.0.to_string() == id)
|
||||
})
|
||||
.map(|r| {
|
||||
r.killed = true;
|
||||
r.run_id.0.to_string()
|
||||
})
|
||||
});
|
||||
let Some(target_id) = target_id else {
|
||||
return Err(HostError::NotFound(format!("no active run `{id}`")));
|
||||
};
|
||||
let _ = self.window_request(client, super::WindowRequest::StopRun { id: target_id }, cancel, timeout)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn upsert_run_configuration(
|
||||
&self,
|
||||
client: &str,
|
||||
draft: ide_plugin::RunConfigDraft,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError> {
|
||||
self.require_api("`run.upsert-configuration`", 21)?;
|
||||
if !self
|
||||
.shared
|
||||
.ui
|
||||
.items(super::ui_points::RUN_CONFIG_TYPES, Some(self.id()))
|
||||
.iter()
|
||||
.any(|i| i.key == draft.type_id)
|
||||
{
|
||||
return Err(HostError::Denied(format!(
|
||||
"plugin {:?} does not declare run configuration type {:?}",
|
||||
self.id(),
|
||||
draft.type_id
|
||||
)));
|
||||
}
|
||||
self.window_request(client, super::WindowRequest::UpsertRunConfiguration { draft }, cancel, timeout)?
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| HostError::Failed("window did not return saved configuration id".into()))
|
||||
}
|
||||
|
||||
fn open_edit_configurations(
|
||||
&self,
|
||||
client: &str,
|
||||
config_id: Option<String>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<(), HostError> {
|
||||
self.require_api("`run.open-edit-configurations`", 21)?;
|
||||
let _ =
|
||||
self.window_request(client, super::WindowRequest::OpenEditConfigurations { config_id }, cancel, timeout)?;
|
||||
Ok(())
|
||||
}
|
||||
fn open_terminal_session(
|
||||
&self,
|
||||
client: &str,
|
||||
|
||||
@@ -412,6 +412,59 @@ pub async fn plugin_debug_attach_target(
|
||||
blocking(move || plugins.debug_attach_target(&host, &client, &config, run)).await
|
||||
}
|
||||
|
||||
/// Bounded slice of a log file tailed for a plugin run console tab.
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginLogTailChunk {
|
||||
pub content: String,
|
||||
pub offset: u64,
|
||||
pub truncated: bool,
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// Reads an incremental chunk of an authorized log file for a plugin run session.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_log_tail(
|
||||
host: &Arc<Host>,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
path: String,
|
||||
offset: u64,
|
||||
max_bytes: Option<u32>,
|
||||
) -> IdeResult<PluginLogTailChunk> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let plugins = plugins.clone();
|
||||
let root = project.root.clone();
|
||||
blocking(move || {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let (resolved, exists) = plugins.authorize_run_log_read(&plugin_id, &root, &path)?;
|
||||
if !exists || !resolved.is_file() {
|
||||
return Ok(PluginLogTailChunk { content: String::new(), offset: 0, truncated: false, exists: false });
|
||||
}
|
||||
let mut file = std::fs::File::open(&resolved)?;
|
||||
let len = file.metadata()?.len();
|
||||
let (start, truncated) = if offset > len { (0, true) } else { (offset, false) };
|
||||
file.seek(SeekFrom::Start(start))?;
|
||||
let cap = usize::try_from(max_bytes.unwrap_or(131_072).min(262_144)).unwrap_or(131_072);
|
||||
let mut buf = vec![0u8; cap];
|
||||
let n = file.read(&mut buf)?;
|
||||
buf.truncate(n);
|
||||
// Leave a character cut by the chunk size for the next read.
|
||||
if let Err(e) = std::str::from_utf8(&buf)
|
||||
&& e.error_len().is_none()
|
||||
&& e.valid_up_to() > 0
|
||||
{
|
||||
buf.truncate(e.valid_up_to());
|
||||
}
|
||||
let n = buf.len();
|
||||
let content = String::from_utf8_lossy(&buf).into_owned();
|
||||
Ok(PluginLogTailChunk { content, offset: start + n as u64, truncated, exists: true })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
plugins_commands:
|
||||
plugin_answer_clipboard,
|
||||
@@ -435,6 +488,7 @@ ide_command::domain!(
|
||||
plugin_run_anything_suggest,
|
||||
plugin_run_command,
|
||||
plugin_run_configuration_complete,
|
||||
plugin_run_log_tail,
|
||||
plugin_select_tests,
|
||||
plugin_set_active_file,
|
||||
plugin_set_ui_locale,
|
||||
|
||||
@@ -18,8 +18,16 @@ pub(super) struct Operation {
|
||||
pub terminal: Option<(std::sync::Weak<crate::Host>, ide_core::TerminalId)>,
|
||||
}
|
||||
|
||||
pub(super) struct ActivePluginRun {
|
||||
pub plugin: String,
|
||||
pub client: String,
|
||||
pub config: String,
|
||||
pub run_id: ide_core::RunId,
|
||||
pub killed: bool,
|
||||
}
|
||||
|
||||
pub(super) enum OperationKind {
|
||||
Run { config: String, configuration: String, program: String },
|
||||
Run { config: String, configuration: String, program: String, debug: bool },
|
||||
Terminal { key: String, command: ide_plugin::ProcessCommand },
|
||||
}
|
||||
|
||||
@@ -478,7 +486,7 @@ fn inherited_env(name: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Attach to Process kinds a configuration may attach to.
|
||||
pub(super) const ATTACH_KINDS: [&str; 5] = ["dotnet", "node", "python", "go", "native"];
|
||||
pub(super) const ATTACH_KINDS: [&str; 6] = ["dotnet", "node", "python", "go", "native", "java"];
|
||||
|
||||
fn validate_debugger(debugger: Option<&ide_plugin::PluginDebugger>) -> Result<(), HostError> {
|
||||
match debugger {
|
||||
@@ -888,6 +896,8 @@ impl PluginHost {
|
||||
let binary = self.program_for_project(plugin, &program, Some(root))?;
|
||||
config.command = if has_target { program } else { binary.to_string_lossy().into_owned() };
|
||||
config.detected = false;
|
||||
config.extras.params.remove("__pluginJavaDebug");
|
||||
config.extras.params.remove("__pluginDebug");
|
||||
plugin.as_str()
|
||||
}
|
||||
PluginRunConfigOwner::Detected { plugin, .. } => {
|
||||
@@ -1132,20 +1142,190 @@ impl PluginHost {
|
||||
Ok((wrapped, true, stop))
|
||||
}
|
||||
pub(crate) fn run_operation_started(&self, client: &str, operation: &str, run: ide_core::RunId) {
|
||||
if let Some(op) = self
|
||||
.shared
|
||||
.operations
|
||||
.lock()
|
||||
.get_mut(operation)
|
||||
.filter(|op| op.client == client && matches!(op.kind, OperationKind::Run { .. }))
|
||||
{
|
||||
op.run = Some(run);
|
||||
let started = {
|
||||
let mut ops = self.shared.operations.lock();
|
||||
ops.get_mut(operation)
|
||||
.filter(|op| op.client == client && matches!(op.kind, OperationKind::Run { .. }))
|
||||
.and_then(|op| {
|
||||
op.run = Some(run);
|
||||
let OperationKind::Run { config, debug, .. } = &op.kind else { return None };
|
||||
Some((op.plugin.clone(), config.clone(), *debug))
|
||||
})
|
||||
};
|
||||
if let Some((plugin, config, debug)) = started {
|
||||
self.emit_run_started_if_wanted(&plugin, client, operation.to_owned(), config, debug);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_operation_stopped(&self, run: ide_core::RunId) {
|
||||
for op in self.shared.operations.lock().values_mut().filter(|op| op.run == Some(run)) {
|
||||
op.closed = true;
|
||||
}
|
||||
if let Some(active) = self.shared.active_plugin_runs.lock().get_mut(&run) {
|
||||
active.killed = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_run_started_if_wanted(&self, plugin_id: &str, client: &str, id: String, config: String, debug: bool) {
|
||||
let Some(plugin) = self.plugins.read().get(plugin_id).cloned() else { return };
|
||||
let wanted = {
|
||||
let subs = self.shared.subscriptions.lock();
|
||||
Self::wants(&plugin, super::EventKind::RunStarted, subs.kinds.get(plugin_id))
|
||||
};
|
||||
if wanted {
|
||||
self.post_owned_event(
|
||||
plugin_id,
|
||||
client,
|
||||
WorkbenchEvent::RunStarted(ide_plugin::RunStarted { id, config, debug }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_plugin_and_config(owner: &PluginRunConfigOwner, config: &ide_run::RunConfig) -> (String, String) {
|
||||
match owner {
|
||||
PluginRunConfigOwner::Detected { plugin, config_id } => (plugin.clone(), config_id.clone()),
|
||||
PluginRunConfigOwner::CustomType { plugin, .. } => (plugin.clone(), config.id.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps `previous` so user-launched plugin runs emit `run-exited` if subscribed.
|
||||
pub(crate) fn user_run_exit_sink(
|
||||
self: &Arc<Self>,
|
||||
client: &str,
|
||||
owner: &PluginRunConfigOwner,
|
||||
config: &ide_run::RunConfig,
|
||||
previous: Arc<dyn ide_core::EventSink>,
|
||||
) -> Arc<dyn ide_core::EventSink> {
|
||||
let (plugin_id, config_id) = Self::owner_plugin_and_config(owner, config);
|
||||
let weak = Arc::downgrade(self);
|
||||
let client = client.to_owned();
|
||||
Arc::new(move |event: ide_core::IdeEvent| {
|
||||
if let ide_core::IdeEvent::RunExited { run, code } = &event
|
||||
&& let Some(plugins) = weak.upgrade()
|
||||
{
|
||||
let active = plugins.shared.active_plugin_runs.lock().remove(run);
|
||||
let (cfg, killed) = match active {
|
||||
Some(a) => (a.config, a.killed),
|
||||
None => (config_id.clone(), false),
|
||||
};
|
||||
// Plugins built for an older API only see `run-exited` for runs they started.
|
||||
if let Some(plugin) = plugins
|
||||
.plugins
|
||||
.read()
|
||||
.get(&plugin_id)
|
||||
.filter(|p| p.manifest().needs_api("user-launched `run-exited`", 21).is_ok())
|
||||
.cloned()
|
||||
{
|
||||
let wanted = {
|
||||
let subs = plugins.shared.subscriptions.lock();
|
||||
Self::wants(&plugin, super::EventKind::RunExited, subs.kinds.get(&plugin_id))
|
||||
};
|
||||
if wanted {
|
||||
plugins.post_owned_event(
|
||||
&plugin_id,
|
||||
&client,
|
||||
WorkbenchEvent::RunExited(ide_plugin::RunExited {
|
||||
id: format!("run-{}", run.0),
|
||||
config: cfg,
|
||||
status: *code,
|
||||
killed,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
previous.emit(event);
|
||||
})
|
||||
}
|
||||
|
||||
/// Records a user-launched plugin run as active and emits `run-started` if subscribed.
|
||||
pub(crate) fn user_run_started(
|
||||
&self,
|
||||
client: &str,
|
||||
owner: &PluginRunConfigOwner,
|
||||
config: &ide_run::RunConfig,
|
||||
run_id: ide_core::RunId,
|
||||
debug: bool,
|
||||
) {
|
||||
let (plugin, cfg) = Self::owner_plugin_and_config(owner, config);
|
||||
self.shared.active_plugin_runs.lock().insert(
|
||||
run_id,
|
||||
ActivePluginRun {
|
||||
plugin: plugin.clone(),
|
||||
client: client.to_owned(),
|
||||
config: cfg.clone(),
|
||||
run_id,
|
||||
killed: false,
|
||||
},
|
||||
);
|
||||
self.emit_run_started_if_wanted(&plugin, client, format!("run-{}", run_id.0), cfg, debug);
|
||||
}
|
||||
|
||||
/// Authorizes reading a log file for `plugin_id` in `project_root` via either
|
||||
/// `project.read` (inside the project) or an active `fs.read:<dir>` grant.
|
||||
/// Returns `(resolved_path, exists)`.
|
||||
pub(crate) fn authorize_run_log_read(
|
||||
&self,
|
||||
plugin_id: &str,
|
||||
project_root: &std::path::Path,
|
||||
asked: &str,
|
||||
) -> IdeResult<(std::path::PathBuf, bool)> {
|
||||
if asked.trim().is_empty() || asked.contains('\0') {
|
||||
return Err(IdeError::invalid("invalid log file path"));
|
||||
}
|
||||
let loaded = self.get(plugin_id)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin_id:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
let grant = self.ledger.lock().get(&loaded.subject()).cloned();
|
||||
let Some(grant) = grant.filter(|g| g.confirmed) else {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin_id:?} is not confirmed"),
|
||||
));
|
||||
};
|
||||
if grant.has(&ide_extension::Capability::ProjectRead) {
|
||||
if let Ok(existing) = ide_plugin::resolve_in_root(project_root, asked) {
|
||||
return Ok((existing, true));
|
||||
}
|
||||
if let Ok(missing) = ide_plugin::resolve_writable_in_root(project_root, asked) {
|
||||
return Ok((missing, false));
|
||||
}
|
||||
}
|
||||
let read_caps: Vec<ide_extension::Capability> = loaded
|
||||
.manifest()
|
||||
.capabilities
|
||||
.all()
|
||||
.filter(|c| matches!(c, ide_extension::Capability::FsRead(_)) && grant.has(c))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !read_caps.is_empty() {
|
||||
match ide_plugin::resolve_granted(&read_caps, asked) {
|
||||
Ok(real) => return Ok((real, true)),
|
||||
Err(ide_plugin::Refusal::Denied(cap)) => {
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, format!("denied {cap}")));
|
||||
}
|
||||
Err(ide_plugin::Refusal::Invalid(_)) => {
|
||||
let write_caps: Vec<_> = read_caps
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_extension::Capability::FsRead(p) => Some(ide_extension::Capability::FsWrite(p.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if let Ok(missing) = ide_plugin::resolve_writable(&write_caps, asked) {
|
||||
return Ok((missing, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin_id:?} lacks project.read or fs.read permission for {asked}"),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1235,7 +1415,8 @@ mod tests {
|
||||
for kind in ATTACH_KINDS {
|
||||
assert!(ok(AttachChild { kind: kind.into(), command_contains: None }), "{kind}");
|
||||
}
|
||||
assert!(!ok(AttachChild { kind: "java".into(), command_contains: None }));
|
||||
assert!(ok(AttachChild { kind: "java".into(), command_contains: None }));
|
||||
assert!(!ok(AttachChild { kind: "ruby".into(), command_contains: None }));
|
||||
assert!(ok(AttachChild { kind: "dotnet".into(), command_contains: Some("Worker.dll".into()) }));
|
||||
assert!(!ok(AttachChild { kind: "dotnet".into(), command_contains: Some(String::new()) }));
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const MAX_GROUPS: usize = 64;
|
||||
const MAX_CHOICES: usize = 16;
|
||||
const MAX_CHOICES: usize = 64;
|
||||
const MAX_CHOICE_OPTIONS: usize = 16;
|
||||
const MAX_NAME_LEN: usize = 255;
|
||||
pub(super) const DARK_SUFFIX: &str = "_dark";
|
||||
@@ -77,17 +77,44 @@ pub(super) struct Group {
|
||||
name: String,
|
||||
#[serde(default = "enabled_by_default")]
|
||||
enabled: bool,
|
||||
/// An icon of the theme shown next to the checkbox on the settings page.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct ChoiceOption {
|
||||
pub(super) id: String,
|
||||
pub(super) name: String,
|
||||
/// An icon of the theme shown next to the option on the settings page.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) icon: Option<String>,
|
||||
/// Groups this option turns on. A group listed by a choice is owned by it: it is on exactly
|
||||
/// while a selected option lists it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
groups: Vec<String>,
|
||||
/// Replaces the theme's `folder` icon while this option is selected. Only one choice of a
|
||||
/// theme may set `folder`, `folderExpanded` or `folderOpen`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder: Option<String>,
|
||||
/// Replaces the theme's `folderExpanded` icon while this option is selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder_expanded: Option<String>,
|
||||
/// Replaces the theme's `folderOpen` icon while this option is selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder_open: Option<String>,
|
||||
#[serde(default)]
|
||||
overrides: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl ChoiceOption {
|
||||
fn folder_icons(&self) -> impl Iterator<Item = &String> {
|
||||
[&self.folder, &self.folder_expanded, &self.folder_open].into_iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Choice {
|
||||
@@ -138,10 +165,16 @@ fn check_unique<'a>(ids: impl Iterator<Item = &'a String>, what: &str) -> Result
|
||||
|
||||
impl Extensions {
|
||||
pub(super) fn mappings(&self) -> usize {
|
||||
let chosen: usize = self.choices.iter().flat_map(|c| &c.options).map(|o| o.overrides.len()).sum();
|
||||
let chosen: usize =
|
||||
self.choices.iter().flat_map(|c| &c.options).map(|o| o.overrides.len() + o.groups.len()).sum();
|
||||
self.patterns.len() + self.overrides.len() + chosen
|
||||
}
|
||||
|
||||
/// The groups some choice lists: their state follows that choice, not the group's own setting.
|
||||
pub(super) fn owned_groups(&self) -> BTreeSet<&str> {
|
||||
self.choices.iter().flat_map(|c| &c.options).flat_map(|o| &o.groups).map(String::as_str).collect()
|
||||
}
|
||||
|
||||
pub(super) fn validate(&self, check_ref: &dyn Fn(&str, &str) -> Result<(), String>) -> Result<(), String> {
|
||||
self.validate_groups()?;
|
||||
for p in &self.patterns {
|
||||
@@ -160,8 +193,17 @@ impl Extensions {
|
||||
}
|
||||
}
|
||||
check_overrides(&self.overrides, check_ref, "overrides")?;
|
||||
for icon in self.groups.iter().filter_map(|g| g.icon.as_deref()) {
|
||||
check_ref(icon, "groups")?;
|
||||
}
|
||||
for choice in &self.choices {
|
||||
for option in &choice.options {
|
||||
if let Some(icon) = &option.icon {
|
||||
check_ref(icon, "choices")?;
|
||||
}
|
||||
for icon in option.folder_icons() {
|
||||
check_ref(icon, "choices")?;
|
||||
}
|
||||
check_overrides(&option.overrides, check_ref, "choices")?;
|
||||
}
|
||||
}
|
||||
@@ -172,6 +214,8 @@ impl Extensions {
|
||||
if self.groups.len() > MAX_GROUPS || self.choices.len() > MAX_CHOICES {
|
||||
return Err(format!("too many groups or choices (max {MAX_GROUPS} and {MAX_CHOICES})"));
|
||||
}
|
||||
let mut owners: BTreeMap<&str, &str> = BTreeMap::new();
|
||||
let mut folder_choice: Option<&str> = None;
|
||||
for g in &self.groups {
|
||||
check_named(&g.id, &g.name, "group")?;
|
||||
}
|
||||
@@ -184,6 +228,29 @@ impl Extensions {
|
||||
}
|
||||
for option in &choice.options {
|
||||
check_named(&option.id, &option.name, "choice option")?;
|
||||
if option.folder_icons().next().is_some()
|
||||
&& let Some(other) = folder_choice.replace(&choice.id)
|
||||
&& other != choice.id
|
||||
{
|
||||
return Err(format!(
|
||||
"choices {other:?} and {:?} both set folder icons; only one choice may set folder, folderExpanded or folderOpen",
|
||||
choice.id
|
||||
));
|
||||
}
|
||||
check_unique(option.groups.iter(), "group in a choice option")?;
|
||||
for group in &option.groups {
|
||||
if !self.groups.iter().any(|g| &g.id == group) {
|
||||
return Err(format!("choice {:?} option {:?}: unknown group {group:?}", choice.id, option.id));
|
||||
}
|
||||
if let Some(other) = owners.insert(group, &choice.id)
|
||||
&& other != choice.id
|
||||
{
|
||||
return Err(format!(
|
||||
"group {group:?} is listed by choices {other:?} and {:?}; a group belongs to one choice",
|
||||
choice.id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
check_unique(choice.options.iter().map(|o| &o.id), "choice option")?;
|
||||
if !choice.options.iter().any(|o| o.id == choice.default) {
|
||||
|
||||
@@ -7,6 +7,14 @@ const MAX_TEXT_LEN: usize = 255;
|
||||
const MAX_HINT_LEN: usize = 512;
|
||||
const MAX_COLUMNS: u8 = 4;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum Presentation {
|
||||
Select,
|
||||
Radio,
|
||||
Segmented,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum SettingOption {
|
||||
@@ -15,6 +23,7 @@ pub(super) enum SettingOption {
|
||||
HideUiIcons,
|
||||
HidePsiIcons,
|
||||
HollowFolders,
|
||||
FileIconsForCode,
|
||||
Groups,
|
||||
Choice,
|
||||
Accent,
|
||||
@@ -46,6 +55,9 @@ pub(super) struct SettingItem {
|
||||
choice: Option<String>,
|
||||
#[serde(default)]
|
||||
columns: Option<u8>,
|
||||
/// How a `choice` item is drawn: a dropdown (`select`, the default), radio buttons or a segmented control.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
presentation: Option<Presentation>,
|
||||
#[serde(default)]
|
||||
default: Option<SettingDefault>,
|
||||
}
|
||||
@@ -69,6 +81,8 @@ struct ChoiceSummary<'a> {
|
||||
struct OptionSummary<'a> {
|
||||
id: &'a str,
|
||||
name: &'a str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<&'a str>,
|
||||
}
|
||||
|
||||
fn check_text(text: &str, max: usize, what: &str) -> Result<(), String> {
|
||||
@@ -100,6 +114,7 @@ fn is_flag(option: SettingOption) -> bool {
|
||||
| SettingOption::HideUiIcons
|
||||
| SettingOption::HidePsiIcons
|
||||
| SettingOption::HollowFolders
|
||||
| SettingOption::FileIconsForCode
|
||||
)
|
||||
}
|
||||
|
||||
@@ -122,6 +137,9 @@ impl SettingItem {
|
||||
{
|
||||
return Err(format!("settings: columns are 1 to {MAX_COLUMNS}, for groups only"));
|
||||
}
|
||||
if self.presentation.is_some() && self.option != SettingOption::Choice {
|
||||
return Err("settings: presentation is only for choice items".into());
|
||||
}
|
||||
match (self.option, &self.choice) {
|
||||
(SettingOption::Choice, Some(id)) if !ext.choices.iter().any(|c| &c.id == id) => {
|
||||
return Err(format!("settings: unknown choice {id:?}"));
|
||||
@@ -166,6 +184,8 @@ pub(super) fn validate(sections: &[SettingsSection], ext: &Extensions) -> Result
|
||||
}
|
||||
|
||||
pub(super) fn summary(sections: &[SettingsSection], ext: &Extensions) -> serde_json::Value {
|
||||
let owned = ext.owned_groups();
|
||||
let groups: Vec<_> = ext.groups.iter().filter(|g| !owned.contains(g.id.as_str())).collect();
|
||||
let choices: Vec<ChoiceSummary> = ext
|
||||
.choices
|
||||
.iter()
|
||||
@@ -173,11 +193,15 @@ pub(super) fn summary(sections: &[SettingsSection], ext: &Extensions) -> serde_j
|
||||
id: &c.id,
|
||||
name: &c.name,
|
||||
default: &c.default,
|
||||
options: c.options.iter().map(|o| OptionSummary { id: &o.id, name: &o.name }).collect(),
|
||||
options: c
|
||||
.options
|
||||
.iter()
|
||||
.map(|o| OptionSummary { id: &o.id, name: &o.name, icon: o.icon.as_deref() })
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"groups": ext.groups,
|
||||
"groups": groups,
|
||||
"choices": choices,
|
||||
"accent": ext.accent,
|
||||
"settings": sections,
|
||||
|
||||
@@ -36,6 +36,26 @@ pub const POINT_ID: &str = "iconThemes";
|
||||
const MAX_ICONS: usize = 5000;
|
||||
pub(super) const MAX_SVG: usize = 64 << 10;
|
||||
const MAX_MAPPINGS: usize = 20_000;
|
||||
/// Role icons of folders a theme may also name (`roleFolderNames`): source roots, packages, modules, …
|
||||
const FOLDER_ROLES: &[&str] = &[
|
||||
"folder-source",
|
||||
"folder-test",
|
||||
"folder-resources",
|
||||
"folder-test-resources",
|
||||
"folder-generated-source",
|
||||
"folder-generated-test",
|
||||
"folder-excluded",
|
||||
"folder-compiled",
|
||||
"folder-javadoc",
|
||||
"folder-library",
|
||||
"folder-github",
|
||||
"package",
|
||||
"module",
|
||||
"gradle-project",
|
||||
"gradle-module",
|
||||
"maven-project",
|
||||
"maven-module",
|
||||
];
|
||||
/// A plugin's own icon is inline in every plugin listing and index entry.
|
||||
pub const MAX_PLUGIN_ICON: usize = 16 << 10;
|
||||
|
||||
@@ -66,6 +86,8 @@ struct ThemeFile {
|
||||
#[serde(default)]
|
||||
folder_names: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
role_folder_names: Vec<String>,
|
||||
#[serde(default)]
|
||||
patterns: Vec<Pattern>,
|
||||
#[serde(default)]
|
||||
overrides: BTreeMap<String, String>,
|
||||
@@ -130,8 +152,11 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
|
||||
if theme.icon_definitions.len() > MAX_ICONS {
|
||||
return Err(format!("{}: more than {MAX_ICONS} icons", d.path.display()));
|
||||
}
|
||||
let mappings =
|
||||
theme.file_extensions.len() + theme.file_names.len() + theme.folder_names.len() + extensions.mappings();
|
||||
let mappings = theme.file_extensions.len()
|
||||
+ theme.file_names.len()
|
||||
+ theme.folder_names.len()
|
||||
+ theme.role_folder_names.len()
|
||||
+ extensions.mappings();
|
||||
if mappings > MAX_MAPPINGS {
|
||||
return Err(format!("{}: more than {MAX_MAPPINGS} mappings", d.path.display()));
|
||||
}
|
||||
@@ -171,6 +196,15 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
|
||||
let file_extensions = lower(&theme.file_extensions, "fileExtensions")?;
|
||||
let file_names = lower(&theme.file_names, "fileNames")?;
|
||||
let folder_names = lower(&theme.folder_names, "folderNames")?;
|
||||
let mut seen_roles = BTreeSet::new();
|
||||
for role in &theme.role_folder_names {
|
||||
if !FOLDER_ROLES.contains(&role.as_str()) {
|
||||
return Err(format!("{}: unknown folder role {role:?}", at("roleFolderNames")));
|
||||
}
|
||||
if !seen_roles.insert(role.as_str()) {
|
||||
return Err(format!("{}: duplicate folder role {role:?}", at("roleFolderNames")));
|
||||
}
|
||||
}
|
||||
|
||||
let mut assets = Vec::with_capacity(theme.icon_definitions.len() + 1);
|
||||
let mut files = vec![d.path.clone()];
|
||||
@@ -190,6 +224,7 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
|
||||
"fileExtensions": file_extensions,
|
||||
"fileNames": file_names,
|
||||
"folderNames": folder_names,
|
||||
"roleFolderNames": theme.role_folder_names,
|
||||
"patterns": extensions.patterns,
|
||||
"overrides": extensions.overrides,
|
||||
"groups": extensions.groups,
|
||||
@@ -755,6 +790,179 @@ mod tests {
|
||||
assert!(d.files.iter().any(|f| f.ends_with("icons/rust-dark.svg")));
|
||||
}
|
||||
|
||||
const SETTINGS_PAGE: &str =
|
||||
r#","settings":[{"title":"Packs","items":[{"option":"groups"},{"option":"choice","choice":"arrows"}]}]"#;
|
||||
|
||||
const PREVIEWS: &str = r#","groups":[{"id":"tests","name":"Tests","icon":"tests"},{"id":"plain","name":"Plain"}],
|
||||
"choices":[{"id":"arrows","name":"Arrows","default":"plain","options":[
|
||||
{"id":"plain","name":"Default","icon":"arrow"},{"id":"material","name":"Material"}]}]"#;
|
||||
|
||||
#[test]
|
||||
fn setting_icons_reach_the_mapping_and_the_summary() {
|
||||
let d = load(&with(&format!("{PREVIEWS}{SETTINGS_PAGE}"))).unwrap();
|
||||
let groups = serde_json::json!([{"id":"tests","name":"Tests","enabled":true,"icon":"tests"},
|
||||
{"id":"plain","name":"Plain","enabled":true}]);
|
||||
let options =
|
||||
serde_json::json!([{"id":"plain","name":"Default","icon":"arrow"},{"id":"material","name":"Material"}]);
|
||||
let map = map_of(&d);
|
||||
assert_eq!(map["groups"], groups);
|
||||
assert_eq!(map["choices"][0]["options"][0]["icon"], "arrow");
|
||||
assert!(map["choices"][0]["options"][1].get("icon").is_none());
|
||||
let s = settings_of(&d).unwrap();
|
||||
assert_eq!(s["groups"], groups);
|
||||
assert_eq!(s["choices"][0]["options"], options);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_icons_must_be_icons_of_the_theme() {
|
||||
let cases = [
|
||||
(r#","groups":[{"id":"a","name":"A","icon":"nope"}]"#, "unknown icon"),
|
||||
(
|
||||
r#","choices":[{"id":"c","name":"C","default":"y","options":[{"id":"y","name":"Y","icon":"nope"}]}]"#,
|
||||
"unknown icon",
|
||||
),
|
||||
];
|
||||
for (extra, needle) in cases {
|
||||
let err = load(&with(extra)).err().unwrap_or_else(|| panic!("accepted: {extra}"));
|
||||
assert!(err.contains(needle), "{extra}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
const FAMILIES: &str = r#","groups":[{"id":"alt-kt","name":"Kotlin alt","enabled":false},
|
||||
{"id":"alt-kt-2","name":"Kotlin alt 2"},{"id":"tests","name":"Tests"}],
|
||||
"choices":[{"id":"family-kt","name":"Kotlin","default":"base","options":[
|
||||
{"id":"base","name":"Base","icon":"rust"},
|
||||
{"id":"alt","name":"Alt","groups":["alt-kt"]},
|
||||
{"id":"alt-2","name":"Alt 2","groups":["alt-kt-2"]},
|
||||
{"id":"alt-again","name":"Alt 3","groups":["alt-kt"]}]}]"#;
|
||||
|
||||
fn families_with(items: &str) -> Result<UiDecl, String> {
|
||||
load(&with(&format!(r#"{FAMILIES},"settings":[{{"title":"T","items":[{items}]}}]"#)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_options_turn_groups_on() {
|
||||
let d = families_with(r#"{"option":"groups"},{"option":"choice","choice":"family-kt","presentation":"radio"}"#)
|
||||
.unwrap();
|
||||
let map = map_of(&d);
|
||||
assert_eq!(map["choices"][0]["options"][1]["groups"], serde_json::json!(["alt-kt"]));
|
||||
assert!(map["choices"][0]["options"][0].get("groups").is_none());
|
||||
assert_eq!(map["groups"].as_array().unwrap().len(), 3, "the mapping keeps every group");
|
||||
let s = settings_of(&d).unwrap();
|
||||
assert_eq!(s["groups"], serde_json::json!([{"id":"tests","name":"Tests","enabled":true}]));
|
||||
assert_eq!(s["settings"][0]["items"][1]["presentation"], "radio");
|
||||
assert!(s["settings"][0]["items"][0].get("presentation").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_option_groups_are_validated() {
|
||||
let choices = |a: &str, b: &str| {
|
||||
format!(
|
||||
r#","groups":[{{"id":"a","name":"A"}},{{"id":"b","name":"B"}}],"choices":[
|
||||
{{"id":"c1","name":"C1","default":"x","options":[{{"id":"x","name":"X","groups":{a}}}]}},
|
||||
{{"id":"c2","name":"C2","default":"y","options":[{{"id":"y","name":"Y","groups":{b}}}]}}]"#
|
||||
)
|
||||
};
|
||||
let one_choice = r#","groups":[{"id":"a","name":"A"}],"choices":[{"id":"c","name":"C","default":"x","options":[
|
||||
{"id":"x","name":"X","groups":["a"]},{"id":"y","name":"Y","groups":["a"]},{"id":"z","name":"Z"}]}]"#;
|
||||
assert!(load(&with(one_choice)).is_ok(), "several options of one choice may list a group");
|
||||
assert!(load(&with(&choices(r#"["a"]"#, r#"["b"]"#))).is_ok());
|
||||
let unknown =
|
||||
r#","choices":[{"id":"c","name":"C","default":"x","options":[{"id":"x","name":"X","groups":["a"]}]}]"#;
|
||||
let cases = [
|
||||
(choices(r#"["nope"]"#, "[]"), "unknown group"),
|
||||
(choices(r#"["a"]"#, r#"["a"]"#), "one choice"),
|
||||
(choices(r#"["a","a"]"#, "[]"), "duplicate"),
|
||||
(unknown.to_string(), "unknown group"),
|
||||
];
|
||||
for (extra, needle) in cases {
|
||||
let err = load(&with(&extra)).err().unwrap_or_else(|| panic!("accepted: {extra}"));
|
||||
assert!(err.contains(needle), "{extra}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_are_limited_to_64() {
|
||||
let choices = |n: usize| {
|
||||
let one =
|
||||
|i: usize| format!(r#"{{"id":"c{i}","name":"C","default":"x","options":[{{"id":"x","name":"X"}}]}}"#);
|
||||
let all: Vec<String> = (0..n).map(one).collect();
|
||||
format!(r#","choices":[{}]"#, all.join(","))
|
||||
};
|
||||
assert!(load(&with(&choices(64))).is_ok());
|
||||
assert!(load(&with(&choices(65))).err().unwrap().contains("too many groups or choices"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_presentation_is_validated() {
|
||||
for presentation in ["select", "radio", "segmented"] {
|
||||
let item = format!(r#"{{"option":"choice","choice":"family-kt","presentation":"{presentation}"}}"#);
|
||||
assert!(families_with(&item).is_ok(), "{presentation}");
|
||||
}
|
||||
let cases = [
|
||||
(r#"{"option":"choice","choice":"family-kt","presentation":"slider"}"#, "unknown variant"),
|
||||
(r#"{"option":"choice","choice":"family-kt","presentation":"Radio"}"#, "unknown variant"),
|
||||
(r#"{"option":"groups","presentation":"radio"}"#, "only for choice"),
|
||||
(r#"{"option":"hideFiles","label":"F","presentation":"radio"}"#, "only for choice"),
|
||||
];
|
||||
for (item, needle) in cases {
|
||||
let err = families_with(item).err().unwrap_or_else(|| panic!("accepted: {item}"));
|
||||
assert!(err.contains(needle), "{item}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
const FOLDER_CHOICE: &str = r#","choices":[{"id":"default-folder","name":"Default folder","default":"plain","options":[
|
||||
{"id":"plain","name":"Plain","icon":"folder"},
|
||||
{"id":"src","name":"Src","folder":"folder-src","folderExpanded":"folder-src-open","folderOpen":"folder-src-open"},
|
||||
{"id":"only","name":"Only","folder":"folder-src"}]}]"#;
|
||||
|
||||
#[test]
|
||||
fn choice_options_set_the_default_folder_icons() {
|
||||
let map = map_of(&load(&with(FOLDER_CHOICE)).unwrap());
|
||||
let options = &map["choices"][0]["options"];
|
||||
assert_eq!(options[1]["folder"], "folder-src");
|
||||
assert_eq!(options[1]["folderExpanded"], "folder-src-open");
|
||||
assert_eq!(options[1]["folderOpen"], "folder-src-open");
|
||||
assert_eq!(options[2]["folder"], "folder-src");
|
||||
for key in ["folder", "folderExpanded", "folderOpen"] {
|
||||
assert!(options[0].get(key).is_none(), "{key} is only serialized when set");
|
||||
}
|
||||
assert!(options[2].get("folderExpanded").is_none());
|
||||
assert!(options[2].get("folderOpen").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_option_folder_icons_are_validated() {
|
||||
let option = |key: &str| {
|
||||
format!(
|
||||
r#","choices":[{{"id":"c","name":"C","default":"x","options":[{{"id":"x","name":"X","{key}":"nope"}}]}}]"#
|
||||
)
|
||||
};
|
||||
for key in ["folder", "folderExpanded", "folderOpen"] {
|
||||
let err = load(&with(&option(key))).err().unwrap_or_else(|| panic!("accepted {key}"));
|
||||
assert!(err.contains("unknown icon"), "{key}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_choice_sets_folder_icons() {
|
||||
let two = |a: &str, b: &str| {
|
||||
format!(
|
||||
r#","choices":[
|
||||
{{"id":"c1","name":"C1","default":"x","options":[{{"id":"x","name":"X"{a}}}]}},
|
||||
{{"id":"c2","name":"C2","default":"y","options":[{{"id":"y","name":"Y"{b}}}]}}]"#
|
||||
)
|
||||
};
|
||||
let folder = r#","folder":"folder-src""#;
|
||||
let expanded = r#","folderExpanded":"folder-src-open""#;
|
||||
assert!(load(&with(&two(folder, ""))).is_ok());
|
||||
assert!(load(&with(&two("", folder))).is_ok());
|
||||
for (a, b) in [(folder, folder), (folder, expanded), (expanded, folder)] {
|
||||
let err = load(&with(&two(a, b))).err().unwrap_or_else(|| panic!("accepted: {a} {b}"));
|
||||
assert!(err.contains("only one choice") && err.contains("c1") && err.contains("c2"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn themes_without_extensions_keep_their_mapping() {
|
||||
let map = map_of(&load(&with("")).unwrap());
|
||||
@@ -763,6 +971,81 @@ mod tests {
|
||||
assert_eq!(map["groups"], serde_json::json!([]));
|
||||
assert_eq!(map["choices"], serde_json::json!([]));
|
||||
assert_eq!(map["accent"], false);
|
||||
assert_eq!(map["roleFolderNames"], serde_json::json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_folder_names_are_checked_and_reach_the_mapping() {
|
||||
let map = map_of(&load(&with(r#","roleFolderNames":["package","folder-source","gradle-module"]"#)).unwrap());
|
||||
assert_eq!(map["roleFolderNames"], serde_json::json!(["package", "folder-source", "gradle-module"]));
|
||||
let err = load(&with(r#","roleFolderNames":["folder-sources"]"#)).unwrap_err();
|
||||
assert!(err.contains("unknown folder role \"folder-sources\""), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_folder_names_reject_duplicates() {
|
||||
let err = load(&with(r#","roleFolderNames":["package","folder-source","package"]"#)).unwrap_err();
|
||||
assert!(err.contains("duplicate folder role \"package\""), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_folder_names_errors_name_the_file_and_key() {
|
||||
let err = load(&with(r#","roleFolderNames":["nope"]"#)).unwrap_err();
|
||||
assert!(err.contains("theme.json (roleFolderNames)"), "{err}");
|
||||
let err = load(&with(r#","roleFolderNames":["package","package"]"#)).unwrap_err();
|
||||
assert!(err.contains("theme.json (roleFolderNames)"), "{err}");
|
||||
// Role names are exact: no trimming, no case folding.
|
||||
for bad in ["", " package", "Package", "folder-source "] {
|
||||
let err = load(&with(&format!(r#","roleFolderNames":[{bad:?}]"#))).unwrap_err();
|
||||
assert!(err.contains("unknown folder role"), "{bad:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_folder_names_must_be_a_list_of_strings() {
|
||||
for extra in [
|
||||
r#","roleFolderNames":"package""#,
|
||||
r#","roleFolderNames":{"package":true}"#,
|
||||
r#","roleFolderNames":[1]"#,
|
||||
r#","roleFolderNames":[null]"#,
|
||||
r#","roleFolderNames":[["package"]]"#,
|
||||
r#","roleFolderNames":null"#,
|
||||
r#","roleFolderNames":true"#,
|
||||
] {
|
||||
let err = load(&with(extra)).err().unwrap_or_else(|| panic!("accepted: {extra}"));
|
||||
assert!(err.contains("theme.json"), "{extra}: {err}");
|
||||
assert!(err.contains("invalid type"), "{extra}: {err}");
|
||||
}
|
||||
// The key is camelCase only.
|
||||
let err = load(&with(r#","role_folder_names":["package"]"#)).unwrap_err();
|
||||
assert!(err.contains("unknown field"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_folder_role_is_accepted() {
|
||||
let all = serde_json::to_string(FOLDER_ROLES).unwrap();
|
||||
let map = map_of(&load(&with(&format!(r#","roleFolderNames":{all}"#))).unwrap());
|
||||
assert_eq!(map["roleFolderNames"], serde_json::json!(FOLDER_ROLES));
|
||||
let unique: BTreeSet<_> = FOLDER_ROLES.iter().collect();
|
||||
assert_eq!(unique.len(), FOLDER_ROLES.len(), "FOLDER_ROLES has duplicates");
|
||||
assert!(load(&with(r#","roleFolderNames":[]"#)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_folder_names_count_toward_the_mapping_limit() {
|
||||
let names: Vec<String> = (0..MAX_MAPPINGS).map(|i| format!("n{i}")).collect();
|
||||
let folder_names: String = names.iter().map(|n| format!("{n:?}:\"folder\"")).collect::<Vec<_>>().join(",");
|
||||
// Exactly at the limit with one role over it.
|
||||
let theme = with(&format!(r#","folderNames":{{{folder_names}}},"roleFolderNames":["package"]"#));
|
||||
let err = load(&theme).unwrap_err();
|
||||
assert!(err.contains("more than 20000 mappings"), "{err}");
|
||||
// One mapping fewer fits.
|
||||
let fewer: String = names[1..].iter().map(|n| format!("{n:?}:\"folder\"")).collect::<Vec<_>>().join(",");
|
||||
assert!(load(&with(&format!(r#","folderNames":{{{fewer}}},"roleFolderNames":["package"]"#))).is_ok());
|
||||
// A huge list is rejected (by the limit or as duplicates) rather than accepted.
|
||||
let big = vec!["package"; MAX_MAPPINGS + 1].join("\",\"");
|
||||
let err = load(&with(&format!(r#","roleFolderNames":["{big}"]"#))).unwrap_err();
|
||||
assert!(err.contains("more than 20000 mappings"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -798,7 +1081,8 @@ mod tests {
|
||||
const SETTINGS: &str = r##","settings":[
|
||||
{"title":"Toggle","items":[
|
||||
{"option":"hideFiles","label":"Enable file icons","hint":"Files","invert":true},
|
||||
{"option":"hollowFolders","label":"Hollow"}]},
|
||||
{"option":"hollowFolders","label":"Hollow"},
|
||||
{"option":"fileIconsForCode","label":"File icons for code","hint":"Kotlin and Java"}]},
|
||||
{"title":"Packs","items":[{"option":"groups","columns":2}]},
|
||||
{"title":"Other","items":[
|
||||
{"option":"choice","choice":"arrows"},
|
||||
@@ -820,17 +1104,35 @@ mod tests {
|
||||
serde_json::json!([{"id":"arrows","name":"Arrows","default":"plain","options":[
|
||||
{"id":"plain","name":"Default"},{"id":"material","name":"Material"}]}])
|
||||
);
|
||||
assert!(s["groups"][0].get("icon").is_none());
|
||||
assert_eq!(s["settings"][0]["title"], "Toggle");
|
||||
assert_eq!(
|
||||
s["settings"][0]["items"][0],
|
||||
serde_json::json!({"option":"hideFiles","label":"Enable file icons","hint":"Files","invert":true,
|
||||
"choice":null,"columns":null,"default":null})
|
||||
);
|
||||
assert_eq!(
|
||||
s["settings"][0]["items"][2],
|
||||
serde_json::json!({"option":"fileIconsForCode","label":"File icons for code","hint":"Kotlin and Java",
|
||||
"invert":false,"choice":null,"columns":null,"default":null})
|
||||
);
|
||||
assert_eq!(s["settings"][2]["items"][1]["default"], "#009688");
|
||||
assert_eq!(s["settings"][2]["items"][2]["default"], 10);
|
||||
assert!(settings_of(&load(&with(EXTENSIONS)).unwrap()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_icons_for_code_is_a_flag_option() {
|
||||
let section = |items: &str| with(&format!(r#"{EXTENSIONS},"settings":[{{"title":"T","items":[{items}]}}]"#));
|
||||
load(§ion(r#"{"option":"fileIconsForCode","label":"F"}"#)).unwrap();
|
||||
let inverted = load(§ion(r#"{"option":"fileIconsForCode","label":"F","invert":true}"#)).unwrap();
|
||||
assert_eq!(settings_of(&inverted).unwrap()["settings"][0]["items"][0]["invert"], true);
|
||||
assert!(load(§ion(r#"{"option":"fileIconsForCode"}"#)).unwrap_err().contains("label"));
|
||||
assert!(
|
||||
load(§ion(r#"{"option":"fileIconsForCode","label":"F","default":1}"#)).unwrap_err().contains("default")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_settings_are_validated() {
|
||||
let section = |items: &str| with(&format!(r#"{EXTENSIONS},"settings":[{{"title":"T","items":[{items}]}}]"#));
|
||||
|
||||
@@ -2226,7 +2226,8 @@ impl PluginHost {
|
||||
.filter(|e| {
|
||||
!matches!(
|
||||
e,
|
||||
WorkbenchEvent::RunExited(_)
|
||||
WorkbenchEvent::RunStarted(_)
|
||||
| WorkbenchEvent::RunExited(_)
|
||||
| WorkbenchEvent::TerminalExited(_)
|
||||
| WorkbenchEvent::ContentTabAction(_)
|
||||
)
|
||||
@@ -2356,6 +2357,7 @@ impl PluginHost {
|
||||
event,
|
||||
WorkbenchEvent::FilesChanged(_)
|
||||
| WorkbenchEvent::WatchedFilesChanged(_)
|
||||
| WorkbenchEvent::RunStarted(_)
|
||||
| WorkbenchEvent::RunExited(_)
|
||||
| WorkbenchEvent::TerminalExited(_)
|
||||
| WorkbenchEvent::ContentTabAction(_)
|
||||
@@ -2583,7 +2585,13 @@ impl PluginHost {
|
||||
&& !kinds.contains(&EventKind::Scheduled)
|
||||
&& !kinds.contains(&EventKind::FilesChanged)
|
||||
&& !kinds.iter().any(|k| {
|
||||
matches!(k, EventKind::RunExited | EventKind::TerminalExited | EventKind::ContentTabAction)
|
||||
matches!(
|
||||
k,
|
||||
EventKind::RunStarted
|
||||
| EventKind::RunExited
|
||||
| EventKind::TerminalExited
|
||||
| EventKind::ContentTabAction
|
||||
)
|
||||
})
|
||||
{
|
||||
actor.cancel_soft();
|
||||
|
||||
@@ -587,4 +587,11 @@ pub enum WindowRequest {
|
||||
env: BTreeMap<String, String>,
|
||||
cwd: ide_core::IpcPath,
|
||||
},
|
||||
/// Stop an active run/debug session belonging to this plugin (API 1.21).
|
||||
StopRun { id: String },
|
||||
/// Create or update a saved run configuration for one of this plugin's own types (API 1.21).
|
||||
UpsertRunConfiguration { draft: ide_plugin::RunConfigDraft },
|
||||
/// Open Run/Debug Configurations dialog, optionally selecting `config_id` (API 1.21).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenEditConfigurations { config_id: Option<String> },
|
||||
}
|
||||
@@ -127,7 +127,9 @@ const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
|
||||
const OPEN_IN_MENU: &str = "openIn";
|
||||
/// Context menu of tables/views in the Database tool window (API 1.20).
|
||||
const DATABASE_TABLE_MENU: &str = "database.table.context";
|
||||
const MENU_IDS: [&str; 14] = [
|
||||
/// Toolbar of the Run and Debug consoles (API 1.21).
|
||||
const RUN_CONSOLE_TOOLBAR_MENU: &str = "runConsole.toolbar";
|
||||
const MENU_IDS: [&str; 15] = [
|
||||
"editor.context",
|
||||
"projectView.context",
|
||||
"editorTab.context",
|
||||
@@ -142,6 +144,7 @@ const MENU_IDS: [&str; 14] = [
|
||||
SERVICES_MENUS[1],
|
||||
OPEN_IN_MENU,
|
||||
DATABASE_TABLE_MENU,
|
||||
RUN_CONSOLE_TOOLBAR_MENU,
|
||||
];
|
||||
const MAX_TITLE: usize = 256;
|
||||
const MAX_SETTINGS: usize = 200;
|
||||
@@ -215,6 +218,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
if d.menu == OPEN_IN_MENU {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {OPEN_IN_MENU}"), 19)?;
|
||||
}
|
||||
if d.menu == RUN_CONSOLE_TOOLBAR_MENU {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {RUN_CONSOLE_TOOLBAR_MENU}"), 21)?;
|
||||
}
|
||||
if let Some(w) = &d.when {
|
||||
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
|
||||
}
|
||||
@@ -469,53 +475,176 @@ pub struct SettingSchema {
|
||||
pub items: Option<Box<SettingSchema>>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub properties: Vec<SettingSchema>,
|
||||
/// API 1.21: how the value is edited (`radio`, `segmented`, `slider`, `color`, `checkbox-list`;
|
||||
/// `select` is the default for an `enum`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub presentation: Option<String>,
|
||||
/// API 1.21: a label, hint and icon for each `enum` value, in `enum` order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub enum_options: Vec<SettingOption>,
|
||||
/// API 1.21: bounds of a number or integer setting (`step`: the slider's increment).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub minimum: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub maximum: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub step: Option<f64>,
|
||||
/// API 1.21: shown only while another setting of the page has one of some values.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub when: Option<SettingWhen>,
|
||||
}
|
||||
|
||||
/// The plugin API minor that adds `presentation`, `enumOptions`, `when` and number bounds.
|
||||
const SETTING_CONTROLS_API: u64 = 21;
|
||||
const RADIO: &str = "radio";
|
||||
const SEGMENTED: &str = "segmented";
|
||||
const SLIDER: &str = "slider";
|
||||
const COLOR: &str = "color";
|
||||
const CHECKBOX_LIST: &str = "checkbox-list";
|
||||
const PRESENTATIONS: [&str; 6] = ["select", RADIO, SEGMENTED, SLIDER, COLOR, CHECKBOX_LIST];
|
||||
/// Option icons across a plugin's settings, each a light and maybe a dark SVG.
|
||||
const MAX_SETTING_ICONS: usize = 256;
|
||||
|
||||
/// One value of an `enum` setting as the page shows it (API 1.21).
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SettingOption {
|
||||
pub value: String,
|
||||
pub label: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
/// A package SVG beside the label; `iconDark` is its dark-theme variant.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub icon: Option<PathBuf>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub icon_dark: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// `{"key": "mode", "equals": "custom"}` or `{"key": "mode", "in": ["a", "b"]}` (API 1.20).
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SettingWhen {
|
||||
pub key: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub equals: Option<Value>,
|
||||
#[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
|
||||
pub one_of: Option<Vec<Value>>,
|
||||
}
|
||||
|
||||
impl SettingWhen {
|
||||
fn values(&self) -> impl Iterator<Item = &Value> {
|
||||
self.equals.iter().chain(self.one_of.iter().flatten())
|
||||
}
|
||||
}
|
||||
|
||||
/// Asset id of the SVG of option `index` of a setting's `enumOptions` (`dark`: its dark variant).
|
||||
pub fn setting_icon_asset(key: &str, index: usize, dark: bool) -> String {
|
||||
format!("settingIcon/{key}/{index}/{}", if dark { "dark" } else { "light" })
|
||||
}
|
||||
|
||||
fn is_hex_color(s: &str) -> bool {
|
||||
s.len() == 7 && s.starts_with('#') && s[1..].chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
impl SettingSchema {
|
||||
/// Whether `v` is a valid value of this setting.
|
||||
pub fn accepts(&self, v: &Value) -> bool {
|
||||
let presented = |p: &str| self.presentation.as_deref() == Some(p);
|
||||
match self.kind.as_str() {
|
||||
"boolean" => v.is_boolean(),
|
||||
"integer" => v.is_i64() || v.is_u64(),
|
||||
"number" => v.is_number(),
|
||||
"integer" | "number" => {
|
||||
let whole = v.is_i64() || v.is_u64();
|
||||
(whole || (self.kind == "number" && v.is_number()))
|
||||
&& v.as_f64().is_some_and(|n| {
|
||||
self.minimum.is_none_or(|min| n >= min) && self.maximum.is_none_or(|max| n <= max)
|
||||
})
|
||||
}
|
||||
"array" => v.as_array().is_some_and(|a| {
|
||||
a.len() <= 1000 && self.items.as_ref().is_some_and(|item| a.iter().all(|v| item.accepts(v)))
|
||||
a.len() <= 1000
|
||||
&& self.items.as_ref().is_some_and(|item| a.iter().all(|v| item.accepts(v)))
|
||||
&& (!presented(CHECKBOX_LIST)
|
||||
|| a.iter().filter_map(Value::as_str).collect::<BTreeSet<_>>().len() == a.len())
|
||||
}),
|
||||
"object" => v.as_object().is_some_and(|o| {
|
||||
o.len() == self.properties.len()
|
||||
&& self.properties.iter().all(|p| o.get(&p.key).is_some_and(|v| p.accepts(v)))
|
||||
}),
|
||||
_ => v
|
||||
.as_str()
|
||||
.is_some_and(|s| s.len() <= 64 << 10 && self.options.as_ref().is_none_or(|o| o.iter().any(|x| x == s))),
|
||||
_ => v.as_str().is_some_and(|s| {
|
||||
s.len() <= 64 << 10
|
||||
&& self.options.as_ref().is_none_or(|o| o.iter().any(|x| x == s))
|
||||
&& (!presented(COLOR) || is_hex_color(s))
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn setting(key: &str, raw: &serde_json::value::RawValue) -> Result<SettingSchema, String> {
|
||||
setting_at(key, raw, 0)
|
||||
/// Refuses a schema field the manifest's API doesn't have yet (`what`, API minor).
|
||||
type NeedsApi<'a> = &'a dyn Fn(&str, u64) -> Result<(), String>;
|
||||
|
||||
fn setting(key: &str, raw: &serde_json::value::RawValue, needs: NeedsApi) -> Result<SettingSchema, String> {
|
||||
setting_at(key, raw, 0, needs)
|
||||
}
|
||||
|
||||
fn setting_at(key: &str, raw: &serde_json::value::RawValue, depth: u8) -> Result<SettingSchema, String> {
|
||||
fn setting_at(
|
||||
key: &str,
|
||||
raw: &serde_json::value::RawValue,
|
||||
depth: u8,
|
||||
needs: NeedsApi,
|
||||
) -> Result<SettingSchema, String> {
|
||||
if key.is_empty() || key.len() > 64 || !key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) {
|
||||
return Err(format!("setting {key:?}: keys are 1–64 of [A-Za-z0-9._-]"));
|
||||
}
|
||||
let value: Value = serde_json::from_str(raw.get()).map_err(|e| e.to_string())?;
|
||||
let o = value.as_object().ok_or_else(|| format!("setting {key:?}: expected an object"))?;
|
||||
let kind = o.get("type").and_then(Value::as_str).unwrap_or("");
|
||||
let options = match o.get("enum") {
|
||||
None => None,
|
||||
Some(Value::Array(a)) if kind == "string" && !a.is_empty() && a.len() <= 100 => Some(
|
||||
a.iter()
|
||||
.map(|v| v.as_str().map(str::to_owned).ok_or_else(|| format!("setting {key:?}: `enum` lists strings")))
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
),
|
||||
Some(_) => return Err(format!("setting {key:?}: `enum` is 1–100 strings of a string setting")),
|
||||
};
|
||||
// Plain JSON Schema words that older IDEs ignored: still ignored for those manifests.
|
||||
let bounds = needs("", SETTING_CONTROLS_API).is_ok();
|
||||
let bound = |name: &str| -> Result<Option<f64>, String> {
|
||||
let Some(v) = o.get(name).filter(|_| bounds) else { return Ok(None) };
|
||||
if kind != "number" && kind != "integer" {
|
||||
return Err(format!("setting {key:?}: `{name}` is for a number or integer setting"));
|
||||
}
|
||||
match v.as_f64() {
|
||||
Some(n) if kind == "number" || n.fract() == 0.0 => Ok(Some(n)),
|
||||
_ => Err(format!("setting {key:?}: `{name}` is a number (an integer for an integer setting)")),
|
||||
}
|
||||
};
|
||||
let (minimum, maximum, step) = (bound("minimum")?, bound("maximum")?, bound("step")?);
|
||||
if minimum.zip(maximum).is_some_and(|(min, max)| min > max) {
|
||||
return Err(format!("setting {key:?}: `minimum` is above `maximum`"));
|
||||
}
|
||||
if step.is_some_and(|s| s <= 0.0) {
|
||||
return Err(format!("setting {key:?}: `step` is above 0"));
|
||||
}
|
||||
let mut items = None;
|
||||
let mut properties = Vec::new();
|
||||
let default = match kind {
|
||||
"boolean" => o.get("default").cloned().unwrap_or(Value::Bool(false)),
|
||||
"string" => o.get("default").cloned().unwrap_or(Value::String(String::new())),
|
||||
"number" | "integer" => o.get("default").cloned().unwrap_or(Value::from(0)),
|
||||
"string" => o
|
||||
.get("default")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Value::String(options.as_ref().and_then(|o| o.first()).cloned().unwrap_or_default())),
|
||||
// Without a default, 0 brought within the bounds.
|
||||
"number" | "integer" => o.get("default").cloned().unwrap_or_else(|| {
|
||||
let n = maximum.map_or(0.0, |max| max.min(0.0)).max(minimum.unwrap_or(f64::MIN));
|
||||
if n.fract() == 0.0 { Value::from(n as i64) } else { Value::from(n) }
|
||||
}),
|
||||
"array" if depth == 0 => {
|
||||
#[derive(Deserialize)]
|
||||
struct ArraySchema {
|
||||
items: Box<serde_json::value::RawValue>,
|
||||
}
|
||||
let array: ArraySchema = serde_json::from_str(raw.get()).map_err(|e| e.to_string())?;
|
||||
let item = setting_at("item", &array.items, 1)?;
|
||||
let item = setting_at("item", &array.items, 1, needs)?;
|
||||
if item.kind != "string" && item.kind != "object" {
|
||||
return Err(format!("setting {key:?}: items must be strings or objects"));
|
||||
}
|
||||
@@ -527,22 +656,13 @@ fn setting_at(key: &str, raw: &serde_json::value::RawValue, depth: u8) -> Result
|
||||
if fields.is_empty() || fields.len() > MAX_SETTINGS {
|
||||
return Err(format!("setting {key:?}: table needs 1–{MAX_SETTINGS} columns"));
|
||||
}
|
||||
properties = fields.iter().map(|(k, v)| setting_at(k, v, 2)).collect::<Result<_, _>>()?;
|
||||
properties = fields.iter().map(|(k, v)| setting_at(k, v, 2, needs)).collect::<Result<_, _>>()?;
|
||||
o.get("default").cloned().unwrap_or_else(|| {
|
||||
Value::Object(properties.iter().map(|p| (p.key.clone(), p.default.clone())).collect())
|
||||
})
|
||||
}
|
||||
_ => return Err(format!("setting {key:?}: unsupported setting type {kind:?}")),
|
||||
};
|
||||
let options = match o.get("enum") {
|
||||
None => None,
|
||||
Some(Value::Array(a)) if kind == "string" && !a.is_empty() && a.len() <= 100 => Some(
|
||||
a.iter()
|
||||
.map(|v| v.as_str().map(str::to_owned).ok_or_else(|| format!("setting {key:?}: `enum` lists strings")))
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
),
|
||||
Some(_) => return Err(format!("setting {key:?}: `enum` is 1–100 strings of a string setting")),
|
||||
};
|
||||
let text = |name: &str, max: usize| -> Result<Option<String>, String> {
|
||||
match o.get(name) {
|
||||
None => Ok(None),
|
||||
@@ -564,6 +684,40 @@ fn setting_at(key: &str, raw: &serde_json::value::RawValue, depth: u8) -> Result
|
||||
Some(e)
|
||||
}
|
||||
};
|
||||
let gated = |field: &str| needs(&format!("setting {key:?}: `{field}`"), SETTING_CONTROLS_API);
|
||||
let presentation = match o.get("presentation") {
|
||||
None => None,
|
||||
Some(Value::String(p)) => {
|
||||
gated("presentation")?;
|
||||
Some(p.clone())
|
||||
}
|
||||
Some(_) => return Err(format!("setting {key:?}: `presentation` is one of {}", PRESENTATIONS.join(", "))),
|
||||
};
|
||||
let enum_options = match o.get("enumOptions") {
|
||||
None => Vec::new(),
|
||||
Some(v) => {
|
||||
gated("enumOptions")?;
|
||||
enum_options(key, v, options.as_deref(), depth)?
|
||||
}
|
||||
};
|
||||
let when = match o.get("when") {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
gated("when")?;
|
||||
if depth != 0 {
|
||||
return Err(format!("setting {key:?}: `when` is for a setting of the page, not a list item or column"));
|
||||
}
|
||||
let w: SettingWhen = serde_json::from_value(v.clone()).map_err(|e| {
|
||||
format!("setting {key:?}: `when` is {{\"key\", \"equals\"}} or {{\"key\", \"in\"}}: {e}")
|
||||
})?;
|
||||
match (&w.equals, &w.one_of) {
|
||||
(Some(_), None) => {}
|
||||
(None, Some(values)) if (1..=100).contains(&values.len()) => {}
|
||||
_ => return Err(format!("setting {key:?}: `when` takes `equals` or `in` (1–100 values), not both")),
|
||||
}
|
||||
Some(w)
|
||||
}
|
||||
};
|
||||
let s = SettingSchema {
|
||||
key: key.to_owned(),
|
||||
kind: kind.to_owned(),
|
||||
@@ -576,20 +730,152 @@ fn setting_at(key: &str, raw: &serde_json::value::RawValue, depth: u8) -> Result
|
||||
example,
|
||||
items,
|
||||
properties,
|
||||
presentation,
|
||||
enum_options,
|
||||
minimum,
|
||||
maximum,
|
||||
step,
|
||||
when,
|
||||
};
|
||||
if let Some(p) = &s.presentation {
|
||||
check_presentation(&s, p, depth)?;
|
||||
}
|
||||
if !s.accepts(&s.default) {
|
||||
return Err(format!("setting {key:?}: the default does not match its type"));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// `enumOptions`: exactly one entry per `enum` value, returned in `enum` order.
|
||||
fn enum_options(key: &str, v: &Value, values: Option<&[String]>, depth: u8) -> Result<Vec<SettingOption>, String> {
|
||||
let values = values.ok_or_else(|| format!("setting {key:?}: `enumOptions` describes the values of `enum`"))?;
|
||||
let list: Vec<SettingOption> = serde_json::from_value(v.clone()).map_err(|e| {
|
||||
format!("setting {key:?}: `enumOptions` lists {{\"value\", \"label\", \"description\", \"icon\", \"iconDark\"}}: {e}")
|
||||
})?;
|
||||
let mut by_value = BTreeMap::new();
|
||||
for option in list {
|
||||
let at = format!("setting {key:?}: `enumOptions` {:?}", option.value);
|
||||
if option.label.trim().is_empty() || option.label.len() > MAX_TITLE {
|
||||
return Err(format!("{at}: `label` is 1–{MAX_TITLE} bytes"));
|
||||
}
|
||||
if option.description.as_ref().is_some_and(|d| d.trim().is_empty() || d.len() > 1024) {
|
||||
return Err(format!("{at}: `description` is 1–1024 bytes"));
|
||||
}
|
||||
for icon in option.icon.iter().chain(&option.icon_dark) {
|
||||
if icon.extension().is_none_or(|e| e != "svg") || icon.as_os_str().len() > 256 {
|
||||
return Err(format!("{at}: icons are package .svg files (paths up to 256 bytes)"));
|
||||
}
|
||||
}
|
||||
if option.icon_dark.is_some() && option.icon.is_none() {
|
||||
return Err(format!("{at}: `iconDark` needs `icon`"));
|
||||
}
|
||||
if option.icon.is_some() && depth > 1 {
|
||||
return Err(format!("{at}: option icons are for settings of the page and lists, not table columns"));
|
||||
}
|
||||
if !values.contains(&option.value) {
|
||||
return Err(format!("{at}: not a value of `enum`"));
|
||||
}
|
||||
let value = option.value.clone();
|
||||
if by_value.insert(value.clone(), option).is_some() {
|
||||
return Err(format!("setting {key:?}: `enumOptions` describes {value:?} twice"));
|
||||
}
|
||||
}
|
||||
values
|
||||
.iter()
|
||||
.map(|v| by_value.remove(v).ok_or_else(|| format!("setting {key:?}: `enumOptions` has no entry for {v:?}")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Refuses a `presentation` that can't edit the setting.
|
||||
fn check_presentation(s: &SettingSchema, p: &str, depth: u8) -> Result<(), String> {
|
||||
let key = &s.key;
|
||||
let needs = match p {
|
||||
"select" => (s.options.is_none()).then_some("a string setting with `enum`"),
|
||||
RADIO | SEGMENTED => (s.options.is_none() || depth != 0).then_some("a string setting of the page with `enum`"),
|
||||
SLIDER => (depth != 0 || !s.minimum.zip(s.maximum).is_some_and(|(min, max)| min < max))
|
||||
.then_some("a number or integer setting of the page with `minimum` below `maximum`"),
|
||||
COLOR => (s.kind != "string" || depth != 0 || s.options.is_some() || s.multiline)
|
||||
.then_some("a string setting of the page without `enum` or `multiline`; its value is #rrggbb"),
|
||||
CHECKBOX_LIST => (s.kind != "array" || s.items.as_ref().is_none_or(|i| i.options.is_none()))
|
||||
.then_some("an array whose `items` are strings with `enum`"),
|
||||
_ => {
|
||||
return Err(format!("setting {key:?}: unknown presentation {p:?} (one of {})", PRESENTATIONS.join(", ")));
|
||||
}
|
||||
};
|
||||
match needs {
|
||||
Some(needs) => Err(format!("setting {key:?}: presentation {p:?} is for {needs}")),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each `when` names another boolean, string or number setting of the page and values it can
|
||||
/// take, without a cycle.
|
||||
fn check_conditions(settings: &[SettingSchema]) -> Result<(), String> {
|
||||
let find = |key: &str| settings.iter().find(|s| s.key == key);
|
||||
for s in settings {
|
||||
let Some(w) = &s.when else { continue };
|
||||
let at = format!("setting {:?}: `when`", s.key);
|
||||
let target = find(&w.key).ok_or_else(|| format!("{at} names {:?}, not a setting of this page", w.key))?;
|
||||
if target.key == s.key {
|
||||
return Err(format!("{at} names the setting itself"));
|
||||
}
|
||||
if !["boolean", "string", "number", "integer"].contains(&target.kind.as_str()) {
|
||||
return Err(format!("{at} names {:?}; name a boolean, string or number setting", w.key));
|
||||
}
|
||||
if let Some(v) = w.values().find(|v| !target.accepts(v)) {
|
||||
return Err(format!("{at}: {v} is not a value of {:?}", w.key));
|
||||
}
|
||||
}
|
||||
for s in settings {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut at = s;
|
||||
while let Some(w) = &at.when {
|
||||
if !seen.insert(at.key.as_str()) {
|
||||
return Err(format!("setting {:?}: `when` conditions form a cycle", s.key));
|
||||
}
|
||||
at = find(&w.key).unwrap_or(at);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The validated settings of a `[contributes.settings]` schema file.
|
||||
pub fn parse_settings_schema(text: &str) -> Result<Vec<SettingSchema>, String> {
|
||||
parse_page(text, &|_, _| Ok(()))
|
||||
}
|
||||
|
||||
fn parse_page(text: &str, needs: NeedsApi) -> Result<Vec<SettingSchema>, String> {
|
||||
let file: SchemaFile = serde_json::from_str(text).map_err(|e| e.to_string())?;
|
||||
if file.properties.len() > MAX_SETTINGS {
|
||||
return Err(format!("more than {MAX_SETTINGS} settings"));
|
||||
}
|
||||
file.properties.iter().map(|(k, v)| setting(k, v)).collect()
|
||||
let settings = file.properties.iter().map(|(k, v)| setting(k, v, needs)).collect::<Result<Vec<_>, _>>()?;
|
||||
check_conditions(&settings)?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
/// Reads and sanitises the option icons of the page's settings (and of their list items).
|
||||
fn setting_icons(pkg: &Package, settings: &[SettingSchema], out: &mut UiDecl) -> Result<(), String> {
|
||||
for s in settings {
|
||||
let options = if s.enum_options.is_empty() {
|
||||
s.items.as_ref().map_or(&[][..], |i| &i.enum_options[..])
|
||||
} else {
|
||||
&s.enum_options[..]
|
||||
};
|
||||
for (index, option) in options.iter().enumerate() {
|
||||
for (path, dark) in [(option.icon.as_ref(), false), (option.icon_dark.as_ref(), true)] {
|
||||
let Some(path) = path else { continue };
|
||||
if out.assets.len() >= MAX_SETTING_ICONS {
|
||||
return Err(format!("settings: more than {MAX_SETTING_ICONS} option icons"));
|
||||
}
|
||||
let svg = super::icons::read_icon(pkg, path, super::icons::MAX_SVG)
|
||||
.map_err(|e| format!("setting {:?}: {e}", s.key))?;
|
||||
out.assets.push((setting_icon_asset(&s.key, index, dark), svg));
|
||||
out.files.push(path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn settings(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
@@ -604,9 +890,9 @@ pub(super) fn settings(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Strin
|
||||
title_ok(&title)?;
|
||||
let mut files = Vec::new();
|
||||
let mut keys = BTreeSet::new();
|
||||
let needs = |what: &str, minor: u64| pkg.manifest.needs_api(what, minor);
|
||||
let mut load = |path: &Path| -> Result<Vec<SettingSchema>, String> {
|
||||
let properties =
|
||||
parse_settings_schema(&pkg.read_text(path)?).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let properties = parse_page(&pkg.read_text(path)?, &needs).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
for p in &properties {
|
||||
if !keys.insert(p.key.clone()) {
|
||||
return Err(format!("settings: duplicate key {:?} across pages", p.key));
|
||||
@@ -656,6 +942,12 @@ pub(super) fn settings(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Strin
|
||||
}),
|
||||
);
|
||||
decl.files = files;
|
||||
setting_icons(pkg, &properties, &mut decl)?;
|
||||
if !decl.assets.is_empty() {
|
||||
// A changed SVG must reproject even when its declared path stays the same.
|
||||
let bytes = serde_json::to_vec(&decl.assets).map_err(|e| e.to_string())?;
|
||||
decl.json["iconRevision"] = Value::String(blake3::hash(&bytes).to_hex().to_string());
|
||||
}
|
||||
Ok(decl)
|
||||
}
|
||||
|
||||
@@ -1071,6 +1363,8 @@ struct RunConfigTypeDecl {
|
||||
owns_working_directory: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
owns_environment: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
owns_before_launch: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
prepare_command: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -1086,6 +1380,9 @@ const RUN_CONFIG_HEIGHT: std::ops::RangeInclusive<u32> = 120..=1200;
|
||||
pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: RunConfigTypeDecl = decode(RUN_CONFIG_TYPES, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{RUN_CONFIG_TYPES}"), 20)?;
|
||||
if d.owns_before_launch {
|
||||
pkg.manifest.needs_api("runConfigTypes.ownsBeforeLaunch", 21)?;
|
||||
}
|
||||
validate_item_id(&d.id, "run config type id")?;
|
||||
let what = format!("run config type {:?}", d.id);
|
||||
for point in [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS] {
|
||||
@@ -1760,6 +2057,291 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn one(field: &str) -> Result<SettingSchema, String> {
|
||||
parse_settings_schema(&format!(r#"{{"properties":{{"x":{field}}}}}"#)).map(|mut s| s.remove(0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_schemas_project_as_before() {
|
||||
let schema = r#"{"properties":{
|
||||
"n":{"type":"number"},"i":{"type":"integer","default":3},"s":{"type":"string","enum":["a","b"],"default":"b"},
|
||||
"l":{"type":"array","items":{"type":"string"}}}}"#;
|
||||
let json = serde_json::to_value(parse_settings_schema(schema).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
serde_json::json!([
|
||||
{"key":"n","type":"number","title":"n","default":0,"multiline":false},
|
||||
{"key":"i","type":"integer","title":"i","default":3,"multiline":false},
|
||||
{"key":"s","type":"string","title":"s","default":"b","options":["a","b"],"multiline":false},
|
||||
{"key":"l","type":"array","title":"l","default":[],"multiline":false,
|
||||
"items":{"key":"item","type":"string","title":"item","default":"","multiline":false}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presentations_fit_their_setting() {
|
||||
let enumerated = |p: &str| format!(r#"{{"type":"string","enum":["a","b"],"presentation":"{p}"}}"#);
|
||||
for p in ["select", RADIO, SEGMENTED] {
|
||||
let s = one(&enumerated(p)).unwrap();
|
||||
assert_eq!((s.presentation.as_deref(), s.default.clone()), (Some(p), Value::from("a")), "{p}");
|
||||
}
|
||||
let slider = one(r#"{"type":"integer","presentation":"slider","minimum":1,"maximum":9,"step":2}"#).unwrap();
|
||||
assert_eq!(
|
||||
(slider.minimum, slider.maximum, slider.step, slider.default.clone()),
|
||||
(Some(1.0), Some(9.0), Some(2.0), Value::from(1))
|
||||
);
|
||||
let color = one(r##"{"type":"string","presentation":"color","default":"#A0b1c2"}"##).unwrap();
|
||||
assert!(color.accepts(&Value::from("#000000")));
|
||||
for bad in ["red", "#fff", "#00000g", "#0000000", ""] {
|
||||
assert!(!color.accepts(&Value::from(bad)), "{bad}");
|
||||
}
|
||||
let list = one(r#"{"type":"array","presentation":"checkbox-list","items":{"type":"string","enum":["a","b"]},"default":["b"]}"#).unwrap();
|
||||
assert!(list.accepts(&serde_json::json!(["a", "b"])));
|
||||
assert!(!list.accepts(&serde_json::json!(["a", "a"])), "a value is checked once");
|
||||
assert!(!list.accepts(&serde_json::json!(["c"])));
|
||||
|
||||
for (field, error) in [
|
||||
(r#"{"type":"string","presentation":"radio"}"#, "a string setting of the page with `enum`"),
|
||||
(r#"{"type":"boolean","presentation":"segmented"}"#, "with `enum`"),
|
||||
(r#"{"type":"string","presentation":"select"}"#, "with `enum`"),
|
||||
(r#"{"type":"string","enum":["a"],"presentation":"dial"}"#, "unknown presentation \"dial\""),
|
||||
(r#"{"type":"string","enum":["a"],"presentation":3}"#, "`presentation` is one of"),
|
||||
(r#"{"type":"number","presentation":"slider"}"#, "`minimum` below `maximum`"),
|
||||
(r#"{"type":"number","presentation":"slider","minimum":0}"#, "`minimum` below `maximum`"),
|
||||
(
|
||||
r#"{"type":"number","presentation":"slider","minimum":1,"maximum":1,"default":1}"#,
|
||||
"`minimum` below `maximum`",
|
||||
),
|
||||
(r#"{"type":"string","presentation":"slider","minimum":0,"maximum":1}"#, "`minimum` is for a number"),
|
||||
(r#"{"type":"string","presentation":"color"}"#, "default does not match"),
|
||||
(r##"{"type":"string","presentation":"color","default":"#abc"}"##, "default does not match"),
|
||||
(r##"{"type":"string","presentation":"color","enum":["#000000"]}"##, "without `enum`"),
|
||||
(r##"{"type":"string","presentation":"color","multiline":true,"default":"#000000"}"##, "`multiline`"),
|
||||
(r##"{"type":"integer","presentation":"color"}"##, "a string setting"),
|
||||
(
|
||||
r#"{"type":"array","presentation":"checkbox-list","items":{"type":"string"}}"#,
|
||||
"`items` are strings with `enum`",
|
||||
),
|
||||
(r#"{"type":"string","enum":["a"],"presentation":"checkbox-list"}"#, "an array"),
|
||||
(r#"{"type":"array","items":{"type":"string","enum":["a"],"presentation":"radio"}}"#, "of the page"),
|
||||
(
|
||||
r#"{"type":"array","items":{"type":"object","properties":{"c":{"type":"number","presentation":"slider","minimum":0,"maximum":1}}}}"#,
|
||||
"of the page",
|
||||
),
|
||||
(
|
||||
r#"{"type":"array","presentation":"checkbox-list","items":{"type":"string","enum":["a"]},"default":["a","a"]}"#,
|
||||
"default",
|
||||
),
|
||||
] {
|
||||
let err = one(field).unwrap_err();
|
||||
assert!(err.contains(error), "{field}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_bounds_limit_values_and_defaults() {
|
||||
let s = one(r#"{"type":"number","minimum":-1.5,"maximum":2.5}"#).unwrap();
|
||||
assert_eq!(s.default, Value::from(0));
|
||||
for (v, ok) in [(-1.5, true), (2.5, true), (0.25, true), (-1.6, false), (2.6, false)] {
|
||||
assert_eq!(s.accepts(&Value::from(v)), ok, "{v}");
|
||||
}
|
||||
assert_eq!(one(r#"{"type":"integer","minimum":5}"#).unwrap().default, Value::from(5));
|
||||
assert_eq!(one(r#"{"type":"number","maximum":-0.5}"#).unwrap().default, Value::from(-0.5));
|
||||
for (field, error) in [
|
||||
(r#"{"type":"integer","minimum":0.5}"#, "an integer for an integer setting"),
|
||||
(r#"{"type":"number","minimum":"1"}"#, "is a number"),
|
||||
(r#"{"type":"number","minimum":2,"maximum":1}"#, "above `maximum`"),
|
||||
(r#"{"type":"number","step":0}"#, "`step` is above 0"),
|
||||
(r#"{"type":"boolean","maximum":1}"#, "for a number or integer"),
|
||||
(r#"{"type":"integer","minimum":0,"maximum":10,"default":11}"#, "default does not match"),
|
||||
] {
|
||||
let err = one(field).unwrap_err();
|
||||
assert!(err.contains(error), "{field}\n→ {err}");
|
||||
}
|
||||
// A table column takes bounds too.
|
||||
let table = one(r#"{"type":"array","items":{"type":"object","properties":{"t":{"type":"number","minimum":0,"maximum":2}}}}"#).unwrap();
|
||||
assert!(table.accepts(&serde_json::json!([{"t": 1}])));
|
||||
assert!(!table.accepts(&serde_json::json!([{"t": 3}])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enum_options_describe_each_enum_value_once() {
|
||||
let s = one(r#"{"type":"string","enum":["b","a"],"enumOptions":[
|
||||
{"value":"a","label":"Alpha","icon":"icons/a.svg","iconDark":"icons/a_dark.svg"},
|
||||
{"value":"b","label":"Beta","description":"The second letter"}]}"#)
|
||||
.unwrap();
|
||||
// In `enum` order, whatever the order of `enumOptions`.
|
||||
assert_eq!(s.enum_options.iter().map(|o| o.label.as_str()).collect::<Vec<_>>(), ["Beta", "Alpha"]);
|
||||
assert_eq!(s.enum_options[0].description.as_deref(), Some("The second letter"));
|
||||
assert_eq!(s.enum_options[1].icon_dark.as_deref(), Some(Path::new("icons/a_dark.svg")));
|
||||
let json = serde_json::to_value(&s).unwrap();
|
||||
assert_eq!(
|
||||
json["enumOptions"][1],
|
||||
serde_json::json!({"value":"a","label":"Alpha","icon":"icons/a.svg","iconDark":"icons/a_dark.svg"})
|
||||
);
|
||||
assert_eq!(json["options"], serde_json::json!(["b", "a"]));
|
||||
// The projected schema reads back (the host reads values through it).
|
||||
assert_eq!(serde_json::from_value::<SettingSchema>(json).unwrap(), s);
|
||||
|
||||
let with = |options: &str| one(&format!(r#"{{"type":"string","enum":["a","b"],"enumOptions":{options}}}"#));
|
||||
for (options, error) in [
|
||||
(r#"[{"value":"a","label":"A"}]"#, "no entry for \"b\""),
|
||||
(
|
||||
r#"[{"value":"a","label":"A"},{"value":"b","label":"B"},{"value":"c","label":"C"}]"#,
|
||||
"\"c\": not a value of `enum`",
|
||||
),
|
||||
(
|
||||
r#"[{"value":"a","label":"A"},{"value":"a","label":"A2"},{"value":"b","label":"B"}]"#,
|
||||
"describes \"a\" twice",
|
||||
),
|
||||
(r#"[{"value":"a","label":" "},{"value":"b","label":"B"}]"#, "`label` is 1–"),
|
||||
(r#"[{"value":"a"},{"value":"b","label":"B"}]"#, "missing field `label`"),
|
||||
(r#"[{"value":"a","label":"A","tooltip":"x"},{"value":"b","label":"B"}]"#, "unknown field `tooltip`"),
|
||||
(r#"[{"value":"a","label":"A","description":""},{"value":"b","label":"B"}]"#, "`description` is 1–1024"),
|
||||
(r#"[{"value":"a","label":"A","icon":"icons/a.png"},{"value":"b","label":"B"}]"#, ".svg"),
|
||||
(
|
||||
r#"[{"value":"a","label":"A","iconDark":"icons/a.svg"},{"value":"b","label":"B"}]"#,
|
||||
"`iconDark` needs `icon`",
|
||||
),
|
||||
(r#"{"a":"A"}"#, "`enumOptions` lists"),
|
||||
] {
|
||||
let err = with(options).unwrap_err();
|
||||
assert!(err.contains(error), "{options}\n→ {err}");
|
||||
}
|
||||
assert!(
|
||||
one(r#"{"type":"string","enumOptions":[{"value":"a","label":"A"}]}"#)
|
||||
.unwrap_err()
|
||||
.contains("values of `enum`")
|
||||
);
|
||||
// List items and table cells take labels; icons stop at list items.
|
||||
let list = one(
|
||||
r#"{"type":"array","items":{"type":"string","enum":["a"],"enumOptions":[{"value":"a","label":"A","icon":"i.svg"}]}}"#,
|
||||
);
|
||||
assert_eq!(list.unwrap().items.unwrap().enum_options[0].label, "A");
|
||||
let column = |icon: &str| {
|
||||
one(&format!(
|
||||
r#"{{"type":"array","items":{{"type":"object","properties":{{"c":{{"type":"string","enum":["a"],"enumOptions":[{{"value":"a","label":"A"{icon}}}]}}}}}}}}"#
|
||||
))
|
||||
};
|
||||
assert!(column("").is_ok());
|
||||
assert!(column(r#","icon":"i.svg""#).unwrap_err().contains("not table columns"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn when_names_another_setting_of_the_page() {
|
||||
let page = |when: &str| {
|
||||
parse_settings_schema(&format!(
|
||||
r#"{{"properties":{{
|
||||
"mode":{{"type":"string","enum":["a","b"]}},"on":{{"type":"boolean"}},"n":{{"type":"integer"}},
|
||||
"list":{{"type":"array","items":{{"type":"string"}}}},
|
||||
"x":{{"type":"string","when":{when}}}}}}}"#
|
||||
))
|
||||
};
|
||||
for when in [
|
||||
r#"{"key":"mode","equals":"b"}"#,
|
||||
r#"{"key":"mode","in":["a","b"]}"#,
|
||||
r#"{"key":"on","equals":true}"#,
|
||||
r#"{"key":"n","in":[1,2]}"#,
|
||||
] {
|
||||
let x = page(when).unwrap().pop().unwrap();
|
||||
assert_eq!(serde_json::to_value(x.when).unwrap(), serde_json::from_str::<Value>(when).unwrap());
|
||||
}
|
||||
for (when, error) in [
|
||||
(r#"{"key":"missing","equals":"a"}"#, "names \"missing\", not a setting of this page"),
|
||||
(r#"{"key":"x","equals":"a"}"#, "names the setting itself"),
|
||||
(r#"{"key":"list","equals":[]}"#, "name a boolean, string or number setting"),
|
||||
(r#"{"key":"mode","equals":"c"}"#, "\"c\" is not a value of \"mode\""),
|
||||
(r#"{"key":"on","in":[true,"yes"]}"#, "\"yes\" is not a value of \"on\""),
|
||||
(r#"{"key":"mode","in":[]}"#, "`equals` or `in`"),
|
||||
(r#"{"key":"mode"}"#, "`equals` or `in`"),
|
||||
(r#"{"key":"mode","equals":"a","in":["b"]}"#, "not both"),
|
||||
(r#"{"key":"mode","is":"a"}"#, "unknown field `is`"),
|
||||
(r#""mode == a""#, "`when` is"),
|
||||
] {
|
||||
let err = page(when).unwrap_err();
|
||||
assert!(err.contains(error), "{when}\n→ {err}");
|
||||
}
|
||||
let cycle = r#"{"properties":{
|
||||
"a":{"type":"boolean","when":{"key":"b","equals":true}},
|
||||
"b":{"type":"boolean","when":{"key":"a","equals":true}}}}"#;
|
||||
assert!(parse_settings_schema(cycle).unwrap_err().contains("cycle"));
|
||||
let chain = r#"{"properties":{
|
||||
"a":{"type":"boolean"},
|
||||
"b":{"type":"boolean","when":{"key":"a","equals":true}},
|
||||
"c":{"type":"boolean","when":{"key":"b","equals":true}}}}"#;
|
||||
assert!(parse_settings_schema(chain).is_ok());
|
||||
let nested = r#"{"type":"array","items":{"type":"string","when":{"key":"a","equals":true}}}"#;
|
||||
assert!(one(nested).unwrap_err().contains("not a list item"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_controls_need_api_1_20_and_register_option_icons() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/settings-controls");
|
||||
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap().replace("\r\n", "\n");
|
||||
let check = |source: &str, dir: &Path| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(SETTINGS).into_iter().next().unwrap();
|
||||
settings(&Package::new(manifest, dir.to_path_buf()), decl)
|
||||
};
|
||||
let d = check(&source, &root).unwrap();
|
||||
let keys: Vec<_> = d.assets.iter().map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"settingIcon/density/0/light",
|
||||
"settingIcon/density/0/dark",
|
||||
"settingIcon/density/1/light",
|
||||
"settingIcon/packs/0/light"
|
||||
]
|
||||
);
|
||||
assert!(d.assets.iter().all(|(_, svg)| svg.starts_with("<svg")));
|
||||
assert!(d.files.contains(&PathBuf::from("icons/compact_dark.svg")));
|
||||
assert_eq!(d.json["iconRevision"].as_str().map(str::len), Some(64));
|
||||
let props = &d.json["properties"];
|
||||
assert_eq!(props[1]["when"], serde_json::json!({"key": "density", "equals": "custom"}));
|
||||
assert_eq!(props[4]["presentation"], "checkbox-list");
|
||||
assert_eq!(props[4]["items"]["enumOptions"][2]["description"], "Cargo and rustfmt files");
|
||||
assert_eq!(props[6]["default"], "chevron");
|
||||
|
||||
let older = source.replace("^1.21", "^1.20");
|
||||
let err = check(&older, &root).unwrap_err();
|
||||
assert!(err.contains("`presentation` is new in plugin API 1.21"), "{err}");
|
||||
|
||||
// Below 1.21, a schema's JSON Schema bounds stay ignored, as older IDEs ignored them.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("settings.schema.json"),
|
||||
r#"{"properties":{"n":{"type":"integer","minimum":5,"maximum":1,"default":0}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let legacy = check(&older.replace("^1.20", "^1.0"), dir.path()).unwrap();
|
||||
assert_eq!(
|
||||
legacy.json["properties"][0],
|
||||
serde_json::json!({"key":"n","type":"integer","title":"n","default":0,"multiline":false})
|
||||
);
|
||||
assert!(legacy.assets.is_empty() && legacy.json.get("iconRevision").is_none());
|
||||
assert!(check(&source, dir.path()).unwrap_err().contains("above `maximum`"));
|
||||
|
||||
// Option icons are package SVGs, sanitised like every plugin icon.
|
||||
let copy = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(copy.path().join("icons")).unwrap();
|
||||
for f in ["plugin.toml", "settings.schema.json"] {
|
||||
std::fs::copy(root.join(f), copy.path().join(f)).unwrap();
|
||||
}
|
||||
for f in ["compact.svg", "compact_dark.svg", "comfortable.svg"] {
|
||||
std::fs::copy(root.join("icons").join(f), copy.path().join("icons").join(f)).unwrap();
|
||||
}
|
||||
assert!(check(&source, copy.path()).unwrap_err().contains("icons/react.svg"));
|
||||
std::fs::write(copy.path().join("icons/react.svg"), "<svg><script>alert(1)</script></svg>").unwrap();
|
||||
let err = check(&source, copy.path()).unwrap_err();
|
||||
assert!(err.contains("setting \"packs\"") && err.contains("not allowed"), "{err}");
|
||||
let schema = std::fs::read_to_string(root.join("settings.schema.json")).unwrap();
|
||||
std::fs::write(copy.path().join("settings.schema.json"), schema.replace("icons/react.svg", "../react.svg"))
|
||||
.unwrap();
|
||||
assert!(check(&source, copy.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_panels_validate_api_width_when_capability_and_page() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/editor-panel");
|
||||
@@ -2162,4 +2744,48 @@ title = \"Prepare\"\n"
|
||||
assert!(locales(&pkg, toml::Value::Table(Default::default())).is_err(), "{name}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_console_toolbar_and_owns_before_launch_require_api_21() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("web")).unwrap();
|
||||
std::fs::write(dir.path().join("web/form.html"), "<html></html>").unwrap();
|
||||
|
||||
let bad_menu = ide_extension::Manifest::parse(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.20\"\n\
|
||||
[[contributes.commands]]\nid = \"redeploy\"\ntitle = \"Redeploy\"\n\
|
||||
[[contributes.menus]]\nmenu = \"runConsole.toolbar\"\ncommand = \"redeploy\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let decl = bad_menu.declarations(MENUS).into_iter().next().unwrap();
|
||||
assert!(menu(&Package::new(bad_menu, dir.path().to_path_buf()), decl).is_err());
|
||||
|
||||
let good_menu = ide_extension::Manifest::parse(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n\
|
||||
[[contributes.commands]]\nid = \"redeploy\"\ntitle = \"Redeploy\"\n\
|
||||
[[contributes.menus]]\nmenu = \"runConsole.toolbar\"\ncommand = \"redeploy\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let decl = good_menu.declarations(MENUS).into_iter().next().unwrap();
|
||||
assert!(menu(&Package::new(good_menu, dir.path().to_path_buf()), decl).is_ok());
|
||||
|
||||
let bad_rc = ide_extension::Manifest::parse(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.20\"\n\
|
||||
[[contributes.runConfigTypes]]\nid = \"t\"\nlabel = \"T\"\nweb = \"web/form.html\"\nownsBeforeLaunch = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
let decl = bad_rc.declarations(RUN_CONFIG_TYPES).into_iter().next().unwrap();
|
||||
assert!(run_config_type(&Package::new(bad_rc, dir.path().to_path_buf()), decl).is_err());
|
||||
|
||||
let good_rc = ide_extension::Manifest::parse(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n\
|
||||
[[contributes.runConfigTypes]]\nid = \"t\"\nlabel = \"T\"\nweb = \"web/form.html\"\nownsBeforeLaunch = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
let decl = good_rc.declarations(RUN_CONFIG_TYPES).into_iter().next().unwrap();
|
||||
assert!(
|
||||
run_config_type(&Package::new(good_rc, dir.path().to_path_buf()), decl).unwrap().json["ownsBeforeLaunch"]
|
||||
== true
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -498,6 +498,7 @@ impl Host {
|
||||
let phpstan = crate::phpstan::Phpstan::new(
|
||||
root.clone(),
|
||||
self.config_dir.clone(),
|
||||
self.data_dir.clone(),
|
||||
settings.clone(),
|
||||
sink.clone(),
|
||||
trusted.clone(),
|
||||
@@ -598,7 +599,10 @@ impl Host {
|
||||
// A framework's root marker (`angular.json`) created or deleted: its
|
||||
// templates gain or lose their mode. Markers in `node_modules` only
|
||||
// count here when the folder isn't excluded (it is by default).
|
||||
if batch.created.iter().chain(&batch.removed).any(|p| languages.is_framework_marker(p)) {
|
||||
// Dependency files count when edited in place too.
|
||||
if batch.created.iter().chain(&batch.removed).any(|p| languages.is_framework_marker(p))
|
||||
|| batch.modified.iter().any(|p| languages.is_content_marker(p))
|
||||
{
|
||||
documents.redetect_languages();
|
||||
}
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
@@ -951,6 +955,11 @@ impl Host {
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
|
||||
}
|
||||
project.agents.set_skills_policy_hook(self.make_skills_policy_hook(
|
||||
project.settings.clone(),
|
||||
project.root.clone(),
|
||||
Some(Arc::downgrade(&project.index)),
|
||||
));
|
||||
// Before anything starts a language server or a tool in the project; a trusted project only.
|
||||
crate::xcode_env::apply(&project);
|
||||
self.insert_project(window, project.clone());
|
||||
@@ -1110,27 +1119,7 @@ impl Host {
|
||||
let approvals = self.mcp_approvals.clone();
|
||||
let secrets = self.agent_secrets.clone();
|
||||
let root = root.to_path_buf();
|
||||
// The skill policies sessions resolve against: both settings layers and the
|
||||
// workspace's trust as it stands when a session starts.
|
||||
let skill_settings = settings.clone();
|
||||
let skill_root = root.clone();
|
||||
let trust = self.trust.clone();
|
||||
let plugin_host = self.plugin_host.read().clone();
|
||||
agents.set_skills_policy_hook(Box::new(move || {
|
||||
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
|
||||
let workspace_trusted = trust.window_trusted(&skill_root).unwrap_or(false);
|
||||
let plugin_dirs = plugin_host
|
||||
.upgrade()
|
||||
.map(|plugins| plugins.skill_dirs(Some(&skill_root), workspace_trusted))
|
||||
.unwrap_or_default();
|
||||
ide_agent::SkillsPolicy {
|
||||
user: layer(ide_workspace::settings::SettingsScope::Global),
|
||||
workspace: layer(ide_workspace::settings::SettingsScope::Project),
|
||||
workspace_trusted,
|
||||
workspace_roots: crate::ops::agent::workspace_skill_roots(&skill_root),
|
||||
plugin_dirs,
|
||||
}
|
||||
}));
|
||||
agents.set_skills_policy_hook(self.make_skills_policy_hook(settings.clone(), root.clone(), None));
|
||||
let mem_settings = settings.clone();
|
||||
let mem_root = root.clone();
|
||||
let mem_trust = self.trust.clone();
|
||||
@@ -1168,6 +1157,40 @@ impl Host {
|
||||
}
|
||||
agents
|
||||
}
|
||||
|
||||
/// Builds the skill-policy hook sessions resolve against: both settings layers, current
|
||||
/// workspace trust, plugin skill dirs, and (when a project index exists) all non-ignored
|
||||
/// indexed `SKILL.md` files for deep monorepo discovery.
|
||||
fn make_skills_policy_hook(
|
||||
&self,
|
||||
settings: Arc<SettingsStore>,
|
||||
root: PathBuf,
|
||||
index: Option<std::sync::Weak<ProjectIndex>>,
|
||||
) -> Box<ide_agent::SkillsPolicyFn> {
|
||||
let trust = self.trust.clone();
|
||||
let plugin_host = self.plugin_host.read().clone();
|
||||
Box::new(move || {
|
||||
let layer = |scope| settings.layer(scope).agents.skills.clone();
|
||||
let workspace_trusted = trust.window_trusted(&root).unwrap_or(false);
|
||||
let plugin_dirs = plugin_host
|
||||
.upgrade()
|
||||
.map(|plugins| plugins.skill_dirs(Some(&root), workspace_trusted))
|
||||
.unwrap_or_default();
|
||||
let indexed_skill_files = index
|
||||
.as_ref()
|
||||
.and_then(std::sync::Weak::upgrade)
|
||||
.map(|idx| crate::ops::agent::indexed_skill_files(&idx))
|
||||
.unwrap_or_default();
|
||||
ide_agent::SkillsPolicy {
|
||||
user: layer(ide_workspace::settings::SettingsScope::Global),
|
||||
workspace: layer(ide_workspace::settings::SettingsScope::Project),
|
||||
workspace_trusted,
|
||||
workspace_roots: crate::ops::agent::workspace_skill_roots(&root),
|
||||
plugin_dirs,
|
||||
indexed_skill_files,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Host {
|
||||
@@ -2521,22 +2544,26 @@ pub(crate) fn unlinked_maven_poms(root: &Path, settings: &ide_core::settings::Se
|
||||
}
|
||||
|
||||
/// The unlinked Maven POMs jdtls leaves out, and the build files (`file:` URIs) it is to
|
||||
/// import when that takes more than exclusions: an unlinked module of a linked reactor.
|
||||
/// Those then include the Gradle build, which jdtls would otherwise find by itself.
|
||||
/// import when that takes more than exclusions: an unlinked module of a linked reactor, a
|
||||
/// POM linked below another Maven project's folder (jdtls's folder scan never reaches it),
|
||||
/// or linked Gradle builds. Those then include the Gradle build, which jdtls would otherwise
|
||||
/// find by itself.
|
||||
pub(crate) fn jdtls_maven_import(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
) -> (Vec<PathBuf>, Option<Vec<String>>) {
|
||||
let maven = &settings.languages.java.maven;
|
||||
let gradle = &settings.languages.java.gradle;
|
||||
if maven.unlinked_projects.is_empty() && gradle.linked_projects.is_none() {
|
||||
let hidden_links = !ide_build::maven::linked_poms_below_projects(root, &maven.linked_projects).is_empty();
|
||||
if maven.unlinked_projects.is_empty() && gradle.linked_projects.is_none() && !hidden_links {
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
let model = ide_build::maven::load_linked(root, maven);
|
||||
let unlinked = ide_build::maven::UnlinkedProjects::from_model(&model, maven);
|
||||
let excluded = unlinked.poms().map(PathBuf::from).collect();
|
||||
let explicit = gradle.linked_projects.is_some() || hidden_links;
|
||||
let poms = unlinked.import_poms(&model).or_else(|| {
|
||||
gradle.linked_projects.as_ref().map(|_| {
|
||||
explicit.then(|| {
|
||||
model
|
||||
.projects
|
||||
.iter()
|
||||
@@ -2551,11 +2578,7 @@ pub(crate) fn jdtls_maven_import(
|
||||
let names = ide_build::gradle::SETTINGS_FILES.iter().chain(ide_build::gradle::BUILD_FILES);
|
||||
names.map(|n| dir.join(n)).find(|f| f.is_file())
|
||||
});
|
||||
let eclipse = if settings.languages.java.gradle.linked_projects.is_some() {
|
||||
independent_eclipse_projects(root)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let eclipse = if explicit { independent_eclipse_projects(root) } else { Vec::new() };
|
||||
poms.iter()
|
||||
.map(|pom| root.join(pom))
|
||||
.chain(gradle)
|
||||
@@ -2967,6 +2990,34 @@ mod maven_linkage_tests {
|
||||
assert_eq!(super::jdtls_maven_import(root, &settings).1, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_imports_a_pom_linked_below_a_reactor_that_does_not_list_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for (dir, body) in [
|
||||
("repo", "<packaging>pom</packaging><modules><module>api</module></modules>"),
|
||||
("repo/api", ""),
|
||||
("repo/command", "<parent><artifactId>repo</artifactId></parent>"),
|
||||
("other", ""),
|
||||
] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
std::fs::write(root.join(dir).join("pom.xml"), format!("<project>{body}</project>")).unwrap();
|
||||
}
|
||||
let mut settings = ide_core::settings::Settings::default();
|
||||
// A link the folder scan finds by itself keeps the scan.
|
||||
settings.languages.java.maven.linked_projects = vec!["other/pom.xml".into()];
|
||||
assert_eq!(super::jdtls_maven_import(root, &settings), (Vec::new(), None));
|
||||
settings.languages.java.maven.linked_projects.push("repo/command/pom.xml".into());
|
||||
let (excluded, files) = super::jdtls_maven_import(root, &settings);
|
||||
assert!(excluded.is_empty());
|
||||
let uri = |f: &str| ide_lsp::path_to_uri_string(&root.join(f));
|
||||
let files = files.unwrap();
|
||||
for pom in ["repo/pom.xml", "other/pom.xml", "repo/command/pom.xml"] {
|
||||
assert!(files.contains(&uri(pom)), "{pom} in {files:?}");
|
||||
}
|
||||
assert!(!files.contains(&uri("repo/api/pom.xml")), "a module comes with its reactor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_maven_link_is_a_content_root_and_not_its_sibling_module() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
"""Move top-level functions, classes and variables of a Python module to another module.
|
||||
|
||||
Run by the IDE like `python_signature.py`: one JSON request on stdin, one JSON answer on stdout.
|
||||
It only turns texts into texts: the IDE reads the files, updates their `from … import` statements
|
||||
with its module-move rewriter, and passes the results here. This script moves the code, writes the
|
||||
imports the two modules need and rewrites `module.name` uses. rope's `MoveGlobal` is not used: it
|
||||
overwrites nothing but happily defines a name twice, empties re-exports and drops imports.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""A move that can't be carried out; the message is shown to the user."""
|
||||
|
||||
|
||||
class Unparsable(Refused):
|
||||
"""A file with a syntax error."""
|
||||
|
||||
|
||||
def parse(text, path):
|
||||
try:
|
||||
return ast.parse(text)
|
||||
except SyntaxError as e:
|
||||
raise Unparsable(f"Syntax error in {path}: {e.msg} (line {e.lineno})")
|
||||
|
||||
|
||||
def lines_of(text):
|
||||
return [line for line in re.split(r"(?<=\n)", text) if line]
|
||||
|
||||
|
||||
class Src:
|
||||
def __init__(self, text):
|
||||
self.text, self.lines, self.starts = text, lines_of(text), [0]
|
||||
for line in self.lines:
|
||||
self.starts.append(self.starts[-1] + len(line))
|
||||
|
||||
def off(self, lineno, col): # `ast` columns are UTF-8 byte offsets
|
||||
line = self.lines[lineno - 1]
|
||||
return self.starts[lineno - 1] + len(line.encode("utf-8")[:col].decode("utf-8", "ignore"))
|
||||
|
||||
def span(self, node):
|
||||
return self.off(node.lineno, node.col_offset), self.off(node.end_lineno, node.end_col_offset)
|
||||
|
||||
|
||||
def splice(text, edits):
|
||||
for start, end, new in sorted(set(edits), reverse=True):
|
||||
text = text[:start] + new + text[end:]
|
||||
return text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- what a module defines
|
||||
|
||||
|
||||
def targets(node):
|
||||
"""The names a top-level statement defines that can be moved."""
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
return [(node.name, "function")]
|
||||
if isinstance(node, ast.ClassDef):
|
||||
return [(node.name, "class")]
|
||||
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
||||
return [(node.targets[0].id, "variable")]
|
||||
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:
|
||||
return [(node.target.id, "variable")]
|
||||
return []
|
||||
|
||||
|
||||
def first_line(node):
|
||||
return min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])])
|
||||
|
||||
|
||||
def resolve(level, module, package):
|
||||
"""The absolute module of `from <level dots><module> import …` inside `package`."""
|
||||
if not level:
|
||||
return module or ""
|
||||
parts = package.split(".") if package else []
|
||||
keep = len(parts) - (level - 1)
|
||||
if keep <= 0:
|
||||
raise Refused("A relative import reaches above the top-level package")
|
||||
return ".".join(parts[:keep] + ([module] if module else []))
|
||||
|
||||
|
||||
class Binding:
|
||||
def __init__(self, statement=None, defined=False, conditional=False):
|
||||
# `statement`: the import that recreates the name elsewhere
|
||||
self.statement, self.defined, self.conditional = statement, defined, conditional
|
||||
self.statements = [] # `import a.b` and `import a.c` both bind `a`
|
||||
self.count = 0
|
||||
|
||||
|
||||
def bindings(tree, package):
|
||||
"""Every name bound at module level, through `if` / `try` / `with` / loops."""
|
||||
found = {}
|
||||
|
||||
def add(name, conditional, statement=None, defined=False):
|
||||
b = found.setdefault(name, Binding(statement, defined, conditional))
|
||||
b.count += 1
|
||||
if statement and statement not in b.statements:
|
||||
b.statements.append(statement)
|
||||
|
||||
def walk(node, conditional):
|
||||
if isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
if a.asname:
|
||||
add(a.asname, conditional, f"import {a.name} as {a.asname}")
|
||||
else:
|
||||
add(a.name.split(".")[0], conditional, f"import {a.name}")
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
module = resolve(node.level, node.module, package)
|
||||
for a in node.names:
|
||||
if a.name != "*":
|
||||
tail = f" as {a.asname}" if a.asname else ""
|
||||
add(a.asname or a.name, conditional, f"from {module} import {a.name}{tail}")
|
||||
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
||||
add(node.name, conditional, defined=True)
|
||||
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
||||
add(node.id, conditional, defined=True)
|
||||
elif not isinstance(node, (ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
|
||||
inner = conditional or isinstance(node, (ast.If, ast.Try, ast.For, ast.While, ast.With, getattr(ast, "Match", ())))
|
||||
for child in ast.iter_child_nodes(node):
|
||||
walk(child, inner)
|
||||
|
||||
for statement in tree.body:
|
||||
walk(statement, False)
|
||||
return found
|
||||
|
||||
|
||||
def names_read(nodes):
|
||||
"""Every name the code reads, string annotations included."""
|
||||
found = set()
|
||||
for node in nodes:
|
||||
for n in ast.walk(node):
|
||||
if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Store):
|
||||
found.add(n.id)
|
||||
for note in (getattr(n, "annotation", None), getattr(n, "returns", None)):
|
||||
for c in ast.walk(note) if note is not None else ():
|
||||
if isinstance(c, ast.Constant) and isinstance(c.value, str):
|
||||
try:
|
||||
found |= names_read([ast.parse(c.value, mode="eval")])
|
||||
except SyntaxError:
|
||||
pass
|
||||
return found
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- editing a module
|
||||
|
||||
|
||||
def import_position(src, tree):
|
||||
"""The line index new imports go to: after the leading imports, the docstring or the comments."""
|
||||
last = 0
|
||||
for i, node in enumerate(tree.body):
|
||||
docstring = i == 0 and isinstance(node, ast.Expr) and isinstance(getattr(node.value, "value", None), str)
|
||||
if not docstring and not isinstance(node, (ast.Import, ast.ImportFrom)):
|
||||
break
|
||||
last = node.end_lineno
|
||||
if not last:
|
||||
while last < len(src.lines) and src.lines[last].startswith("#"):
|
||||
last += 1
|
||||
return last
|
||||
|
||||
|
||||
def add_imports(text, statements, path):
|
||||
if not statements:
|
||||
return text
|
||||
src, tree = Src(text), parse(text, path)
|
||||
future = [s for s in statements if s.startswith("from __future__ ")]
|
||||
rest = [s for s in statements if s not in future]
|
||||
at = import_position(src, tree)
|
||||
head, tail = "".join(src.lines[:at]), "".join(src.lines[at:])
|
||||
if head and not head.endswith("\n"):
|
||||
head += "\n"
|
||||
if future: # must precede every other import
|
||||
first = next((n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom))), None)
|
||||
cut = src.starts[first.lineno - 1] if first else len(head)
|
||||
head = head[:cut] + "".join(s + "\n" for s in future) + head[cut:]
|
||||
block = "".join(s + "\n" for s in rest)
|
||||
if block and head and not any(isinstance(n, (ast.Import, ast.ImportFrom)) for n in tree.body):
|
||||
block = "\n" + block
|
||||
if tail.strip() and not tail.startswith("\n") and (rest or future):
|
||||
tail = "\n\n" + tail
|
||||
return head + block + tail
|
||||
|
||||
|
||||
def cut_blocks(src, tree, nodes):
|
||||
"""(line ranges, texts) of the statements to move, with their decorators and leading comments."""
|
||||
ranges, texts = [], []
|
||||
for node in nodes:
|
||||
start, end = first_line(node) - 1, node.end_lineno
|
||||
for other in tree.body:
|
||||
if other is not node and first_line(other) <= end and other.end_lineno > start:
|
||||
raise Refused("A statement shares its line with another one; split them first")
|
||||
above = max((o.end_lineno for o in tree.body if o.end_lineno <= start), default=0)
|
||||
top = start
|
||||
while top > above and src.lines[top - 1].startswith("#") and not re.match(r"#!|#.*coding[:=]", src.lines[top - 1]):
|
||||
top -= 1
|
||||
# comments reaching the top of the file are its header (copyright, license), not the node's
|
||||
if top and any(line.strip() and not line.startswith("#") for line in src.lines[:top]):
|
||||
start = top
|
||||
# indented comments after the body belong to it
|
||||
probe = end
|
||||
while probe < len(src.lines) and (not src.lines[probe].strip() or src.lines[probe][0] in " \t"):
|
||||
if src.lines[probe].strip().startswith("#"):
|
||||
end = probe + 1
|
||||
elif src.lines[probe].strip():
|
||||
break
|
||||
probe += 1
|
||||
ranges.append((start, end))
|
||||
texts.append("".join(src.lines[start:end]).rstrip("\n"))
|
||||
return ranges, texts
|
||||
|
||||
|
||||
def remove_ranges(src, ranges):
|
||||
lines = list(src.lines)
|
||||
for start, end in sorted(ranges, reverse=True):
|
||||
before, after = "".join(lines[:start]).rstrip("\n"), "".join(lines[end:]).lstrip("\n")
|
||||
if before and after:
|
||||
joined = before + "\n\n\n" + after
|
||||
else:
|
||||
joined = before + "\n" if before else after
|
||||
lines = lines_of(joined)
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- `module.name` uses
|
||||
|
||||
|
||||
def chain(node):
|
||||
parts = []
|
||||
while isinstance(node, ast.Attribute):
|
||||
parts.append(node.attr)
|
||||
node = node.value
|
||||
return ".".join([node.id] + parts[::-1]) if isinstance(node, ast.Name) else None
|
||||
|
||||
|
||||
def takes(tree, module):
|
||||
"""Whether the first part of `module` is already bound here to something else."""
|
||||
root = module.split(".")[0]
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id == root:
|
||||
return True
|
||||
if isinstance(node, ast.arg) and node.arg == root:
|
||||
return True
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.name == root:
|
||||
return True
|
||||
if isinstance(node, ast.ImportFrom) and any((a.asname or a.name) == root for a in node.names):
|
||||
return True
|
||||
if isinstance(node, ast.Import) and any(a.asname == root and a.name != root for a in node.names):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def rewrite_uses(path, text, package, names, source, dest, is_dest, warnings, show):
|
||||
"""`source.name` uses become `dest.name` (a bare `name` in the destination itself)."""
|
||||
src, tree = Src(text), parse(text, path)
|
||||
modules = {} # how this file spells the source module -> its import statements
|
||||
stars = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
if a.name == source:
|
||||
modules.setdefault(a.asname or a.name, []).append(node)
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
try:
|
||||
module = resolve(node.level, node.module, package)
|
||||
except Refused:
|
||||
continue
|
||||
for a in node.names:
|
||||
if a.name == "*" and module == source:
|
||||
stars.append(node)
|
||||
elif a.name != "*" and f"{module}.{a.name}".lstrip(".") == source:
|
||||
modules.setdefault(a.asname or a.name, []).append(node)
|
||||
rebound = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)}
|
||||
rebound |= {n.arg for n in ast.walk(tree) if isinstance(n, ast.arg)}
|
||||
edits, after = [], {} # after: import node -> statements to put behind it
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
if any(node.value == f"{source}.{n}" or node.value.startswith(f"{source}.{n}.") for n in names):
|
||||
warnings.append(f"{show}:{node.lineno}: the string '{node.value}' still names the old module.")
|
||||
if not (isinstance(node, ast.Attribute) and node.attr in names):
|
||||
continue
|
||||
spelled = chain(node.value)
|
||||
if spelled not in modules:
|
||||
continue
|
||||
if spelled.split(".")[0] in rebound:
|
||||
warnings.append(f"{show}:{node.lineno}: '{spelled}' is also a local name here; '{spelled}.{node.attr}' was not updated.")
|
||||
continue
|
||||
start, end = src.span(node)
|
||||
if is_dest:
|
||||
edits.append((start, end, node.attr))
|
||||
else:
|
||||
if takes(tree, dest):
|
||||
raise Refused(f"{show} already uses the name '{dest.split('.')[0]}' for something else")
|
||||
edits.append((start, end, f"{dest}.{node.attr}"))
|
||||
for statement in modules[spelled]:
|
||||
after.setdefault(statement, set()).add(f"import {dest}")
|
||||
used = names_read([tree])
|
||||
for node in stars:
|
||||
wanted = sorted(used & set(names))
|
||||
if wanted and not is_dest:
|
||||
after.setdefault(node, set()).add(f"from {dest} import {', '.join(wanted)}")
|
||||
warnings.append(f"{show}:{node.lineno}: 'import *' no longer brings {', '.join(wanted)}; an explicit import was added.")
|
||||
for node, statements in after.items():
|
||||
start, end = src.span(node)
|
||||
before = src.text[src.starts[node.lineno - 1]:start]
|
||||
rest = src.text[end:src.starts[node.end_lineno]].strip()
|
||||
if before.strip() or (rest and not rest.startswith("#")):
|
||||
# shares its line (`import a; a.f()`, `try: import a`)
|
||||
edits.append((end, end, "".join(f"; {s}" for s in sorted(statements))))
|
||||
else:
|
||||
end = src.starts[node.end_lineno - 1] + len(src.lines[node.end_lineno - 1].rstrip("\r\n"))
|
||||
edits.append((end, end, "".join(f"\n{before}{s}" for s in sorted(statements))))
|
||||
return splice(text, edits)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- where the code goes
|
||||
|
||||
DEFS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
|
||||
|
||||
|
||||
def import_time(node):
|
||||
"""The parts of a statement that run when its module is imported."""
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
args = node.args
|
||||
notes = [a.annotation for a in args.posonlyargs + args.args + args.kwonlyargs + [args.vararg, args.kwarg] if a]
|
||||
return [n for n in node.decorator_list + args.defaults + args.kw_defaults + notes + [node.returns] if n]
|
||||
if isinstance(node, ast.ClassDef):
|
||||
head = node.decorator_list + node.bases + [k.value for k in node.keywords]
|
||||
return head + [part for child in node.body for part in import_time(child)]
|
||||
return [node]
|
||||
|
||||
|
||||
def is_main_guard(node):
|
||||
return isinstance(node, ast.If) and "__name__" in names_read([node.test])
|
||||
|
||||
|
||||
def place(text, code, moved_nodes, names, path):
|
||||
"""`text` with `code` after what it needs to be defined and before what needs it at import."""
|
||||
src, tree = Src(text), parse(text, path)
|
||||
needs = names_read([part for n in moved_nodes for part in import_time(n)]) - set(names)
|
||||
# local functions and classes that read a moved name: calling them at import needs it too
|
||||
users, grew = set(names), True
|
||||
while grew:
|
||||
grew = False
|
||||
for node in tree.body:
|
||||
if isinstance(node, DEFS) and node.name not in users and names_read([node]) & users:
|
||||
users.add(node.name)
|
||||
grew = True
|
||||
lower, upper = 0, None
|
||||
for node in tree.body:
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
||||
bound = {(a.asname or a.name).split(".")[0] for a in node.names}
|
||||
elif isinstance(node, DEFS):
|
||||
bound = {node.name}
|
||||
else:
|
||||
bound = {n.id for n in ast.walk(node) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)}
|
||||
if upper is None and (is_main_guard(node) or names_read(import_time(node)) & users):
|
||||
upper = first_line(node) - 1
|
||||
if bound & needs:
|
||||
if upper is not None:
|
||||
raise Refused(f"{path} uses a moved name before what the moved code needs is defined")
|
||||
lower = node.end_lineno
|
||||
if upper is None:
|
||||
return (text.rstrip("\n") + "\n\n\n" if text.strip() else "") + code + "\n"
|
||||
while upper > lower and src.lines[upper - 1].startswith("#"):
|
||||
upper -= 1
|
||||
# as early as the imports and the needed definitions allow when something below uses it
|
||||
at = upper
|
||||
head, tail = "".join(src.lines[:at]).rstrip("\n"), "".join(src.lines[at:]).lstrip("\n")
|
||||
return (head + "\n\n\n" if head else "") + code + "\n\n\n" + tail
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the move
|
||||
|
||||
|
||||
def symbols(req):
|
||||
"""The movable names of the module; `selected` marks the one at the caret line."""
|
||||
tree = parse(req["text"], "the file")
|
||||
line = req["line"] + 1
|
||||
out = []
|
||||
for node in tree.body:
|
||||
for name, kind in targets(node):
|
||||
if all(s["name"] != name for s in out):
|
||||
out.append({"name": name, "kind": kind, "selected": first_line(node) <= line <= node.end_lineno})
|
||||
if not out:
|
||||
raise Refused("There are no top-level functions, classes or variables to move")
|
||||
return out
|
||||
|
||||
|
||||
def move(req):
|
||||
source, dest, names = req["source"], req["dest"], req["names"]
|
||||
if not names:
|
||||
raise Refused("Select something to move")
|
||||
src, tree = Src(source["text"]), parse(source["text"], source["show"])
|
||||
dest_text = dest["text"] or ""
|
||||
dest_tree = parse(dest_text, dest["show"])
|
||||
here = bindings(tree, source["package"])
|
||||
there = bindings(dest_tree, dest["package"])
|
||||
warnings = []
|
||||
|
||||
nodes = [n for n in tree.body if any(name in names for name, _ in targets(n))]
|
||||
missing = set(names) - {name for n in nodes for name, _ in targets(n)}
|
||||
if missing:
|
||||
raise Refused(f"'{sorted(missing)[0]}' is not a top-level function, class or variable")
|
||||
for name in names:
|
||||
if here[name].count > 1:
|
||||
raise Refused(f"'{name}' is assigned or defined in several places; move it by hand")
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Global) and set(node.names) & set(names):
|
||||
raise Refused(f"'{sorted(set(node.names) & set(names))[0]}' is written through 'global'")
|
||||
for node in (n for m in nodes for n in ast.walk(m)):
|
||||
if isinstance(node, ast.Global) and set(node.names) - set(names):
|
||||
raise Refused(f"The moved code writes the global '{node.names[0]}' of its module")
|
||||
|
||||
# the destination may already import what is moving there
|
||||
own_imports = {f"from {source['module']} import {n}": n for n in names}
|
||||
for name in names:
|
||||
existing = there.get(name)
|
||||
if existing and (existing.defined or existing.statement not in own_imports):
|
||||
raise Refused(f"'{name}' is already defined in {dest['show']}")
|
||||
|
||||
# what the moved code needs where it lands
|
||||
read = names_read(nodes)
|
||||
needed, from_source = [], []
|
||||
for name in sorted(read - set(names)):
|
||||
b = here.get(name)
|
||||
if b is None:
|
||||
continue
|
||||
wanted = [f"from {source['module']} import {name}"] if b.defined else b.statements
|
||||
if any(w.startswith(f"from {dest['module']} import ") for w in wanted):
|
||||
continue # it comes from the destination itself
|
||||
if not b.defined and b.conditional and len(wanted) > 1 and not all(w.startswith("import ") for w in wanted):
|
||||
wanted = wanted[:1] # `try: import ujson as json` / `except: import json`
|
||||
other = there.get(name)
|
||||
if other:
|
||||
# `import a.b` and `import a.c` agree on what `a` is
|
||||
plain = all(w.startswith("import ") and " as " not in w for w in wanted + other.statements)
|
||||
if other.defined or not (plain or set(wanted) & set(other.statements)):
|
||||
raise Refused(f"'{name}' means something else in {dest['show']}")
|
||||
wanted = [w for w in wanted if w not in other.statements]
|
||||
if wanted and b.conditional and not b.defined:
|
||||
warnings.append(f"'{name}' is imported conditionally; {dest['show']} imports it unconditionally.")
|
||||
(from_source if b.defined else needed).extend(wanted)
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.ImportFrom):
|
||||
if node.module == "__future__":
|
||||
statement = f"from __future__ import {', '.join(a.name for a in node.names)}"
|
||||
if statement not in ast.unparse(dest_tree).split("\n"):
|
||||
needed.append(statement)
|
||||
elif any(a.name == "*" for a in node.names):
|
||||
warnings.append(f"{source['show']} uses 'import *'; check that {dest['show']} imports what the moved code needs.")
|
||||
for name in sorted(read & {"__file__", "__name__", "__package__"}):
|
||||
warnings.append(f"The moved code reads {name}, which changes with the module.")
|
||||
|
||||
ranges, blocks = cut_blocks(src, tree, nodes)
|
||||
|
||||
# the source keeps importing what it still uses
|
||||
left = remove_ranges(src, ranges)
|
||||
left_tree = parse(left, source["show"])
|
||||
exported = {
|
||||
c.value
|
||||
for n in left_tree.body if isinstance(n, (ast.Assign, ast.AnnAssign, ast.AugAssign))
|
||||
if any(isinstance(t, ast.Name) and t.id == "__all__" for t in ast.walk(n))
|
||||
for c in ast.walk(n) if isinstance(c, ast.Constant)
|
||||
}
|
||||
still = sorted(set(names) & (names_read([left_tree]) | exported))
|
||||
if still:
|
||||
left = add_imports(left, [f"from {dest['module']} import {', '.join(still)}"], source["show"])
|
||||
if still and from_source:
|
||||
warnings.append(f"{source['show']} and {dest['show']} would import each other.")
|
||||
|
||||
# the destination: drop its imports of the moved names, add what is needed, then the code
|
||||
edits, dest_src = [], Src(dest_text)
|
||||
for node in ast.walk(dest_tree):
|
||||
if isinstance(node, ast.ImportFrom) and resolve(node.level, node.module, dest["package"]) == source["module"]:
|
||||
if any(a.name in names and a.asname for a in node.names):
|
||||
raise Refused(f"{dest['show']} imports a moved name under another name; remove the alias first")
|
||||
kept = [a for a in node.names if a.name not in names]
|
||||
if len(kept) == len(node.names):
|
||||
continue
|
||||
start, end = dest_src.span(node)
|
||||
alone = node in dest_tree.body and not dest_src.text[end:dest_src.starts[node.end_lineno]].strip()
|
||||
if kept:
|
||||
node.names = kept
|
||||
edits.append((start, end, ast.unparse(node)))
|
||||
elif alone and not node.col_offset:
|
||||
edits.append((dest_src.starts[node.lineno - 1], dest_src.starts[node.end_lineno], ""))
|
||||
else:
|
||||
edits.append((start, end, "pass"))
|
||||
new = splice(dest_text, edits)
|
||||
new = rewrite_uses(dest["show"], new, dest["package"], names, source["module"], dest["module"], True, warnings, dest["show"])
|
||||
new = add_imports(new, needed + from_source, dest["show"])
|
||||
new = place(new, "\n\n\n".join(blocks), nodes, names, dest["show"])
|
||||
|
||||
files = {source["path"]: left, dest["path"]: new}
|
||||
for path, other in req["others"].items():
|
||||
try:
|
||||
files[path] = rewrite_uses(
|
||||
path, other["text"], other["package"], names, source["module"], dest["module"], False, warnings, other["show"]
|
||||
)
|
||||
except Unparsable:
|
||||
warnings.append(f"{other['show']} has a syntax error and was not checked.")
|
||||
for path, text in files.items():
|
||||
original = other_text(req, path)
|
||||
if text != original:
|
||||
try:
|
||||
ast.parse(text)
|
||||
except SyntaxError as e:
|
||||
raise Refused(f"The move would make {path} invalid: {e.msg} (line {e.lineno})")
|
||||
return {"files": files, "warnings": sorted(set(warnings), key=warnings.index)}
|
||||
|
||||
|
||||
def other_text(req, path):
|
||||
for side in (req["source"], req["dest"]):
|
||||
if side["path"] == path:
|
||||
return side["text"]
|
||||
return req["others"][path]["text"]
|
||||
|
||||
|
||||
def main():
|
||||
req = json.loads(sys.stdin.buffer.read())
|
||||
try:
|
||||
out = {"ok": True, "result": symbols(req) if req["op"] == "symbols" else move(req)}
|
||||
except Refused as e:
|
||||
out = {"ok": False, "error": str(e)}
|
||||
json.dump(out, sys.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Move top-level Python functions, classes and variables to another module. The IDE reads the
|
||||
//! files and updates `from … import` with its module-move rewriter; `python_move.py` moves the code
|
||||
//! and rewrites `module.name` uses. Nothing is written here: the answer is a workspace edit.
|
||||
use crate::Host;
|
||||
use crate::ops::refactor::{is_python, python_module, python_package};
|
||||
use crate::python_signature::{Context, run, to_edit};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, DocId, FileEdit, IdeError, IdeResult, IpcPath, Pos, Range, TextEdit, WorkspaceEdit};
|
||||
use ide_lsp::types::{ProblemSeverity, RefactoringProblem, ServerRefactored};
|
||||
use ide_workspace::file_moves::read_text;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
const HELPER: &str = include_str!("python_move.py");
|
||||
/// What the dialog sends back to accept the warnings of the first answer.
|
||||
const CONFIRMATION: &str = "python-move";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Arguments {
|
||||
names: Vec<String>,
|
||||
/// The destination module file, absolute or relative to the project.
|
||||
file: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Moved {
|
||||
files: BTreeMap<PathBuf, String>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn open(host: &Host, window: &str, doc: DocId) -> IdeResult<(Arc<crate::Project>, PathBuf, String)> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if !snap.path.0.is_absolute() || !snap.path.0.starts_with(&*project.root) {
|
||||
return Err(IdeError::invalid("Move needs a Python file of this project"));
|
||||
}
|
||||
Ok((project.clone(), snap.path.0.clone(), snap.text))
|
||||
}
|
||||
|
||||
fn context(project: &crate::Project, file: PathBuf, line: u32) -> Context {
|
||||
Context { root: project.root.to_path_buf(), file, pos: Pos::new(line, 0), overlay: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The movable names of the module (`{name, kind, selected}`); `args` carries the caret `line`.
|
||||
pub async fn symbols(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
args: Value,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<Value>> {
|
||||
let (project, file, text) = open(host, window, doc)?;
|
||||
let line = args["line"].as_u64().unwrap_or(0) as u32;
|
||||
let request = json!({ "op": "symbols", "text": text });
|
||||
match run(host, HELPER, request, &context(&project, file, line), &cancel).await? {
|
||||
Value::Array(found) => Ok(found),
|
||||
_ => Err(IdeError::new(ErrorKind::Protocol, "unexpected answer")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The destination as an absolute path inside the project.
|
||||
fn destination(root: &Path, file: &str) -> IdeResult<PathBuf> {
|
||||
let path = root.join(file.trim());
|
||||
let inside = path.starts_with(root) && !path.components().any(|c| matches!(c, Component::ParentDir));
|
||||
if !inside || path.extension().is_none_or(|e| e != "py") {
|
||||
return Err(IdeError::invalid("The destination must be a .py file inside the project"));
|
||||
}
|
||||
// a linked folder may lead outside the project
|
||||
let real = path.ancestors().find_map(|p| dunce::canonicalize(p).ok());
|
||||
if !real.zip(dunce::canonicalize(root).ok()).is_some_and(|(real, root)| real.starts_with(root)) {
|
||||
return Err(IdeError::invalid("The destination must be a .py file inside the project"));
|
||||
}
|
||||
// `utils.py` next to the package `utils/` (or inside a folder shadowed by `pkg.py`) is never imported
|
||||
let package = |p: &Path| p.join("__init__.py").is_file();
|
||||
let shadowed =
|
||||
path.ancestors().skip(1).take_while(|p| *p != root).any(|p| p.with_extension("py").is_file() && !package(p));
|
||||
if package(&path.with_extension("")) || shadowed {
|
||||
return Err(IdeError::invalid("A package and a module of the same name exist there"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
struct Request {
|
||||
json: Value,
|
||||
/// The text each file had when the request was built.
|
||||
before: BTreeMap<PathBuf, String>,
|
||||
create: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn request(
|
||||
project: &crate::Project,
|
||||
syntax: &ide_language::Syntax,
|
||||
source: &Path,
|
||||
text: String,
|
||||
args: Arguments,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Request> {
|
||||
let root: &Path = &project.root;
|
||||
let roots = project.roots();
|
||||
let dest = destination(root, &args.file)?;
|
||||
if dest == source {
|
||||
return Err(IdeError::invalid("The destination is the file itself"));
|
||||
}
|
||||
let show = |p: &Path| p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
|
||||
let module = |p: &Path| {
|
||||
python_module(root, &roots, p, false)
|
||||
.map(|(m, _)| m)
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} can't be imported as a Python module", show(p))))
|
||||
};
|
||||
let (old, new) = (module(source)?, module(&dest)?);
|
||||
if old == new {
|
||||
return Err(IdeError::invalid("The destination has the same module name"));
|
||||
}
|
||||
let existing = if dest.exists() { Some(read_text(&project.documents, &dest)?) } else { None };
|
||||
let mut before = BTreeMap::from([(source.to_path_buf(), text.clone())]);
|
||||
if let Some(existing) = &existing {
|
||||
before.insert(dest.clone(), existing.clone());
|
||||
}
|
||||
let moves: Vec<(String, String)> =
|
||||
args.names.iter().map(|n| (format!("{old}.{n}"), format!("{new}.{n}"))).collect();
|
||||
let last = old.rsplit('.').next().unwrap_or(&old);
|
||||
let init = source.file_stem().is_some_and(|s| s == "__init__");
|
||||
// (path, the file as it is, the file with its `from … import` updated)
|
||||
let found: Mutex<Vec<(PathBuf, String, String)>> = Mutex::new(Vec::new());
|
||||
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
|
||||
if cancel.is_cancelled() || !is_python(path) || path == source || path == dest {
|
||||
return;
|
||||
}
|
||||
// An unsaved buffer may mention the module although the file on disk doesn't.
|
||||
let open = project.documents.text_of(path);
|
||||
// Names a package defines are also reached as `from . import name`.
|
||||
let mentions = |text: &str| text.contains(last) || (init && args.names.iter().any(|n| text.contains(n)));
|
||||
// UTF-16 can't be searched as bytes.
|
||||
let may = |b: Vec<u8>| {
|
||||
b.starts_with(&[0xff, 0xfe]) || b.starts_with(&[0xfe, 0xff]) || mentions(&String::from_utf8_lossy(&b))
|
||||
};
|
||||
if open.is_none() && !std::fs::read(path).is_ok_and(may) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = open.map_or_else(|| read_text(&project.documents, path), Ok) else { return };
|
||||
if !mentions(&text) {
|
||||
return;
|
||||
}
|
||||
let package = python_package(root, &roots, path);
|
||||
let mut updated = ide_text::Document::new(&text);
|
||||
if updated.apply_edits(&syntax.python_import_edits(&text, &package, &package, &moves)).is_ok() {
|
||||
found.lock().push((path.to_path_buf(), text, updated.text()));
|
||||
}
|
||||
});
|
||||
let mut others = serde_json::Map::new();
|
||||
for (path, text, updated) in found.into_inner() {
|
||||
let entry = json!({ "text": updated, "package": python_package(root, &roots, &path), "show": show(&path) });
|
||||
others.insert(path.to_string_lossy().into_owned(), entry);
|
||||
before.insert(path, text);
|
||||
}
|
||||
let side = |path: &Path, module: &str, text: Option<&String>| {
|
||||
json!({
|
||||
"path": path, "show": show(path), "module": module, "text": text,
|
||||
"package": python_package(root, &roots, path),
|
||||
})
|
||||
};
|
||||
let json = json!({
|
||||
"op": "move",
|
||||
"names": args.names,
|
||||
"source": side(source, &old, Some(&text)),
|
||||
"dest": side(&dest, &new, existing.as_ref()),
|
||||
"others": others,
|
||||
});
|
||||
Ok(Request { json, before, create: existing.is_none().then_some(dest) })
|
||||
}
|
||||
|
||||
/// Checks the move and computes its edit. Warnings (strings naming the module, import cycles…)
|
||||
/// come back first, with a token that accepts them.
|
||||
pub async fn move_symbols(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
args: Value,
|
||||
confirmation: Option<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let (project, source, text) = open(host, window, doc)?;
|
||||
let args: Arguments =
|
||||
serde_json::from_value(args).map_err(|e| IdeError::invalid(format!("invalid refactoring arguments: {e}")))?;
|
||||
let syntax = host.syntax();
|
||||
let built = {
|
||||
let (project, source, cancel) = (project.clone(), source.clone(), cancel.clone());
|
||||
crate::ops::blocking(move || request(&project, &syntax, &source, text, args, &cancel)).await?
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let result = run(host, HELPER, built.json, &context(&project, source, 0), &cancel).await?;
|
||||
let mut moved: Moved =
|
||||
serde_json::from_value(result).map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?;
|
||||
let problems: Vec<RefactoringProblem> = moved
|
||||
.warnings
|
||||
.into_iter()
|
||||
.map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message })
|
||||
.collect();
|
||||
// The token names the warnings shown: others that appear meanwhile are asked about again.
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
problems.iter().for_each(|p| p.message.hash(&mut hasher));
|
||||
let token = format!("{CONFIRMATION}:{:x}", hasher.finish());
|
||||
if !problems.is_empty() && confirmation.as_deref() != Some(&token) {
|
||||
return Ok(ServerRefactored { problems, edit: None, confirmation: Some(token) });
|
||||
}
|
||||
let mut edit = WorkspaceEdit::default();
|
||||
if let Some(dest) = built.create {
|
||||
let text = moved.files.remove(&dest).unwrap_or_default();
|
||||
if dest.exists() {
|
||||
return Err(IdeError::invalid("The destination was created meanwhile; run it again"));
|
||||
}
|
||||
let start = Range::new(Pos::new(0, 0), Pos::new(0, 0));
|
||||
edit.files.push(FileEdit::Create { path: IpcPath(dest.clone()), overwrite: false });
|
||||
edit.files.push(FileEdit::Edit {
|
||||
path: IpcPath(dest),
|
||||
edits: vec![TextEdit { range: start, new_text: text }],
|
||||
version: None,
|
||||
});
|
||||
}
|
||||
edit.files.extend(to_edit(&project, moved.files, &built.before)?.files);
|
||||
Ok(ServerRefactored { problems: Vec::new(), edit: Some(edit), confirmation: None })
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
"""Change Signature for Python on top of rope.
|
||||
|
||||
Run by the IDE with the interpreter of the pylsp-rope environment: one JSON request on stdin,
|
||||
one JSON answer on stdout. Nothing is written to disk. Unsaved editor buffers arrive in
|
||||
`overlay` and rope reads them instead of the files; the answer carries the new text of every
|
||||
file that changes.
|
||||
|
||||
rope finds the function, its calls and its overrides and renames parameters (it knows scopes).
|
||||
The parameter list and the call arguments are rewritten here from the `ast`: rope's own
|
||||
rewriting drops annotations, keyword-only markers and positional arguments after a removal.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import bisect
|
||||
import io
|
||||
import json
|
||||
import keyword
|
||||
import re
|
||||
import sys
|
||||
import tokenize
|
||||
|
||||
from rope.base import evaluate, libutils, pyobjects
|
||||
from rope.base.change import ChangeContents
|
||||
from rope.base.exceptions import RopeError
|
||||
from rope.base.project import Project
|
||||
from rope.base.resources import File
|
||||
from rope.refactor import occurrences
|
||||
from rope.refactor.change_signature import ChangeSignature
|
||||
from rope.refactor.rename import Rename
|
||||
|
||||
OVERLAY = {} # real path -> text (rope reads these instead of the files)
|
||||
IGNORED = [
|
||||
"*.pyc", "*~", ".*", "__pycache__", "venv", "node_modules", "site-packages", "*.egg-info",
|
||||
]
|
||||
LINE_END = re.compile(r"\r\n|\n|\r")
|
||||
TRANSPARENT = {"staticmethod", "classmethod", "abstractmethod", "override", "final", "overload"}
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""A request that can't be carried out; the message is shown to the user."""
|
||||
|
||||
|
||||
class Skip(Exception):
|
||||
"""A call that can't be rewritten; the message says why."""
|
||||
|
||||
|
||||
def install_overlay(overlay):
|
||||
OVERLAY.update(overlay)
|
||||
read_bytes = File.read_bytes
|
||||
|
||||
def patched(self):
|
||||
text = OVERLAY.get(self.real_path)
|
||||
if text is not None:
|
||||
return text.encode("utf-8")
|
||||
# a byte order mark would be a syntax error to `ast`; the IDE's text has none either
|
||||
data = read_bytes(self)
|
||||
return data[3:] if data.startswith(b"\xef\xbb\xbf") else data
|
||||
|
||||
File.read_bytes = patched
|
||||
|
||||
|
||||
class Src:
|
||||
"""A file's text with the line tables `ast` positions need."""
|
||||
|
||||
def __init__(self, text):
|
||||
self.text = text
|
||||
self.lines = [m for m in re.split(r"(?<=\n)", text) if m]
|
||||
self.starts = [0]
|
||||
for line in self.lines:
|
||||
self.starts.append(self.starts[-1] + len(line))
|
||||
|
||||
def off(self, lineno, col): # `ast` columns are UTF-8 byte offsets
|
||||
line = self.lines[lineno - 1] if lineno <= len(self.lines) else ""
|
||||
return self.starts[lineno - 1] + len(line.encode("utf-8")[:col].decode("utf-8", "ignore"))
|
||||
|
||||
def span(self, node):
|
||||
return self.off(node.lineno, node.col_offset), self.off(node.end_lineno, node.end_col_offset)
|
||||
|
||||
def pos(self, line, utf16_col): # an LSP position to an offset
|
||||
text = self.lines[line] if line < len(self.lines) else ""
|
||||
units = 0
|
||||
for i, ch in enumerate(text):
|
||||
if units >= utf16_col:
|
||||
return self.starts[line] + i
|
||||
units += 2 if ord(ch) > 0xFFFF else 1
|
||||
return self.starts[line] + len(text.rstrip("\r\n"))
|
||||
|
||||
def wrap(self, start, end, lo, hi):
|
||||
"""Widens an expression's span over the parentheses around it, which `ast` leaves out."""
|
||||
while True:
|
||||
i, j = start - 1, end
|
||||
while i >= lo and self.text[i] in " \t\r\n\\":
|
||||
i -= 1
|
||||
while j < hi and self.text[j] in " \t\r\n\\":
|
||||
j += 1
|
||||
if not (i >= lo and j < hi and self.text[i] == "(" and self.text[j] == ")"):
|
||||
return start, end
|
||||
start, end = i, j + 1
|
||||
|
||||
def line_of(self, offset):
|
||||
return bisect.bisect_right(self.starts, offset)
|
||||
|
||||
def indent_at(self, offset):
|
||||
start = self.starts[self.line_of(offset) - 1]
|
||||
line = self.text[start:offset]
|
||||
return line[: len(line) - len(line.lstrip())]
|
||||
|
||||
|
||||
class Row:
|
||||
"""One entry of the parameter table: a parameter or the `/` and `*` markers."""
|
||||
|
||||
def __init__(self, index, name, kind, text="", default="", annotation="", span=None):
|
||||
self.index, self.name, self.kind = index, name, kind
|
||||
self.text, self.default, self.annotation, self.span = text, default, annotation, span
|
||||
|
||||
def base(self):
|
||||
return self.name.lstrip("*")
|
||||
|
||||
def as_json(self):
|
||||
return {"name": self.name, "defaultValue": self.default, "originalIndex": self.index, "type": self.annotation}
|
||||
|
||||
|
||||
class Def:
|
||||
def __init__(self, node, src):
|
||||
self.node, self.src = node, src
|
||||
a = node.args
|
||||
positional = a.posonlyargs + a.args
|
||||
defaults = [None] * (len(positional) - len(a.defaults)) + list(a.defaults)
|
||||
self.rows = []
|
||||
|
||||
def add(arg, default, kind, stars=""):
|
||||
start, end = src.span(arg)
|
||||
name_end, size = start + len(arg.arg), len(src.text)
|
||||
annotation = value = ""
|
||||
if arg.annotation is not None:
|
||||
a_start, a_end = src.wrap(*src.span(arg.annotation), name_end, size)
|
||||
annotation, end = src.text[a_start:a_end], max(end, a_end)
|
||||
if default is not None:
|
||||
d_start, d_end = src.wrap(*src.span(default), name_end, size)
|
||||
value, end = src.text[d_start:d_end], max(end, d_end)
|
||||
text = stars + src.text[start:end]
|
||||
row = Row(len(self.rows), stars + arg.arg, kind, text, value, annotation, (start - len(stars), end))
|
||||
self.rows.append(row)
|
||||
|
||||
for i, (arg, default) in enumerate(zip(positional, defaults)):
|
||||
add(arg, default, "posonly" if i < len(a.posonlyargs) else "normal")
|
||||
if a.posonlyargs and i == len(a.posonlyargs) - 1:
|
||||
self.rows.append(Row(len(self.rows), "/", "marker"))
|
||||
if a.vararg:
|
||||
add(a.vararg, None, "vararg", "*")
|
||||
elif a.kwonlyargs:
|
||||
self.rows.append(Row(len(self.rows), "*", "marker"))
|
||||
for arg, default in zip(a.kwonlyargs, a.kw_defaults):
|
||||
add(arg, default, "kwonly")
|
||||
if a.kwarg:
|
||||
add(a.kwarg, None, "kwarg", "**")
|
||||
self.name_offset = self._name_offset()
|
||||
|
||||
def _name_offset(self):
|
||||
# `lineno` is the `def` line even when decorated
|
||||
start = self.src.off(self.node.lineno, self.node.col_offset)
|
||||
m = re.compile(r"(?:async\s+)?def\s+(\w+)").match(self.src.text, start)
|
||||
if not m:
|
||||
raise Refused("Cannot read the function header")
|
||||
return m.start(1)
|
||||
|
||||
def decorators(self):
|
||||
names = []
|
||||
for d in self.node.decorator_list:
|
||||
d = d.func if isinstance(d, ast.Call) else d
|
||||
names.append(ast.unparse(d))
|
||||
return names
|
||||
|
||||
def kind(self, in_class):
|
||||
if not in_class:
|
||||
return "function"
|
||||
names = {n.split(".")[-1] for n in self.decorators()}
|
||||
return "static" if "staticmethod" in names else "class" if "classmethod" in names else "method"
|
||||
|
||||
def region(self, whole=False):
|
||||
"""The text range between the parentheses, without the outer blanks and a trailing comma
|
||||
unless `whole`."""
|
||||
text = self.src.text
|
||||
i = self.name_offset + len(self.node.name)
|
||||
while text[i] != "(": # PEP 695 `def f[T](…)`
|
||||
if text[i] == "[":
|
||||
depth = 0
|
||||
while True:
|
||||
depth += {"[": 1, "]": -1}.get(text[i], 0)
|
||||
i += 1
|
||||
if depth == 0:
|
||||
break
|
||||
elif text[i] in " \t\r\n\\":
|
||||
i += 1
|
||||
else:
|
||||
raise Refused("Cannot read the parameter list")
|
||||
open_at = i
|
||||
params = [r.span for r in self.rows if r.span]
|
||||
scan = max(e for _, e in params) if params else open_at + 1
|
||||
while text[scan] in " \t\r\n,/*\\":
|
||||
scan += 1
|
||||
if text[scan] != ")":
|
||||
raise Refused("Cannot read the parameter list (comments inside it?)")
|
||||
inner = text[open_at + 1 : scan]
|
||||
if "#" in inner:
|
||||
raise Refused("The parameter list contains comments; edit it by hand")
|
||||
if whole:
|
||||
return open_at + 1, scan
|
||||
end = scan
|
||||
while end > open_at + 1 and text[end - 1] in " \t\r\n\\":
|
||||
end -= 1
|
||||
if end > open_at + 1 and text[end - 1] == ",":
|
||||
end -= 1
|
||||
start = open_at + 1
|
||||
while start < end and text[start] in " \t\r\n\\":
|
||||
start += 1
|
||||
return start, end
|
||||
|
||||
|
||||
def join_items(src, start, end, items):
|
||||
"""Joins call arguments or parameters like the text they replace: one line or one per line."""
|
||||
if "\n" in src.text[start:end] and len(items) > 1:
|
||||
return (",\n" + src.indent_at(end - 1 if end > start else start)).join(items)
|
||||
return ", ".join(items)
|
||||
|
||||
|
||||
def classify(rows):
|
||||
kinds = []
|
||||
slash = next((i for i, r in enumerate(rows) if r["name"] == "/"), None)
|
||||
star = False
|
||||
for i, r in enumerate(rows):
|
||||
n = r["name"]
|
||||
if n in ("/", "*"):
|
||||
kinds.append("marker")
|
||||
star = star or n == "*"
|
||||
elif n.startswith("**"):
|
||||
kinds.append("kwarg")
|
||||
elif n.startswith("*"):
|
||||
kinds.append("vararg")
|
||||
star = True
|
||||
elif star:
|
||||
kinds.append("kwonly")
|
||||
elif slash is not None and i < slash:
|
||||
kinds.append("posonly")
|
||||
else:
|
||||
kinds.append("normal")
|
||||
return kinds
|
||||
|
||||
|
||||
def is_expression(text):
|
||||
"""One expression that can stand as a default: no top-level comma, comment or assignment."""
|
||||
try:
|
||||
call = ast.parse(f"_({text}\n)", mode="eval").body
|
||||
tokens = list(tokenize.generate_tokens(io.StringIO(text).readline))
|
||||
ast.parse(f"def _(_={text}\n): pass")
|
||||
except (SyntaxError, tokenize.TokenError):
|
||||
return False
|
||||
return (
|
||||
isinstance(call, ast.Call) and len(call.args) == 1 and not call.keywords
|
||||
and not isinstance(call.args[0], ast.Starred)
|
||||
and not any(t.type == tokenize.COMMENT for t in tokens)
|
||||
)
|
||||
|
||||
|
||||
def validate(rows, old, method_kind):
|
||||
names = set()
|
||||
kinds = classify(rows)
|
||||
stars = [r["name"] for r in rows if r["name"] in ("*",) or (r["name"].startswith("*") and not r["name"].startswith("**"))]
|
||||
if len(stars) > 1:
|
||||
raise Refused("Only one '*' or '*args' parameter is allowed")
|
||||
if sum(r["name"] == "/" for r in rows) > 1:
|
||||
raise Refused("Only one '/' marker is allowed")
|
||||
for i, r in enumerate(rows):
|
||||
n = r["name"]
|
||||
if n in ("/", "*"):
|
||||
continue
|
||||
if n.startswith("*"):
|
||||
r["defaultValue"] = "" # the dialog has no default field for these rows
|
||||
base = n.lstrip("*")
|
||||
if len(n) - len(base) > 2 or not base.isidentifier() or keyword.iskeyword(base):
|
||||
raise Refused(f"'{n}' is not a valid parameter name")
|
||||
if base in names:
|
||||
raise Refused(f"Duplicate parameter name '{base}'")
|
||||
names.add(base)
|
||||
if n.startswith("**") and i != len(rows) - 1:
|
||||
raise Refused("'**' parameter must be last")
|
||||
if rows and rows[0]["name"] == "/":
|
||||
raise Refused("'/' needs a parameter before it")
|
||||
slash = next((i for i, r in enumerate(rows) if r["name"] == "/"), None)
|
||||
if slash is not None and any(r["name"].startswith("*") for r in rows[:slash]):
|
||||
raise Refused("'/' must come before '*'")
|
||||
for i, r in enumerate(rows):
|
||||
if r["name"] == "*" and not any(k == "kwonly" for k in kinds[i:]):
|
||||
raise Refused("'*' needs a keyword-only parameter after it")
|
||||
if r["name"] == "/" and i > 0 and kinds[i - 1] == "marker":
|
||||
raise Refused("'/' needs a parameter before it")
|
||||
seen_default = False
|
||||
for r, k in zip(rows, kinds):
|
||||
if k in ("posonly", "normal"):
|
||||
if r["defaultValue"].strip():
|
||||
seen_default = True
|
||||
elif seen_default:
|
||||
raise Refused(f"Non-default parameter '{r['name']}' follows a parameter with a default value")
|
||||
if r["originalIndex"] < 0 and not r["defaultValue"].strip() and k in ("posonly", "normal", "kwonly"):
|
||||
raise Refused("Default value is not specified for a new parameter")
|
||||
if r["defaultValue"].strip():
|
||||
if not is_expression(r["defaultValue"].strip()):
|
||||
raise Refused(f"Default value of '{r['name']}' is not a valid expression")
|
||||
implicit = 0 if method_kind in ("function", "static") else 1
|
||||
for i in range(implicit):
|
||||
if not rows or rows[0]["originalIndex"] != 0 or rows[0]["name"] != old.rows[0].name:
|
||||
raise Refused(f"The first parameter '{old.rows[0].name}' of a method cannot be changed")
|
||||
return kinds
|
||||
|
||||
|
||||
def param_text(row, old_row):
|
||||
if row["name"] in ("/", "*"):
|
||||
return row["name"]
|
||||
default = row["defaultValue"].strip()
|
||||
if old_row is not None and old_row.name == row["name"] and old_row.default.strip() == default:
|
||||
return old_row.text
|
||||
stars = row["name"][: len(row["name"]) - len(row["name"].lstrip("*"))]
|
||||
annotation = old_row.annotation if old_row is not None else ""
|
||||
out = row["name"]
|
||||
if annotation:
|
||||
out += ": " + annotation
|
||||
if default:
|
||||
out += (" = " if annotation else "=") + default
|
||||
return out
|
||||
|
||||
|
||||
def definition_edit(d, rows):
|
||||
items = [param_text(r, d.rows[r["originalIndex"]] if r["originalIndex"] >= 0 else None) for r in rows]
|
||||
start, end = d.region(whole=not items)
|
||||
return start, end, join_items(d.src, start, end, items)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- calls
|
||||
|
||||
|
||||
class Arg:
|
||||
def __init__(self, value, raw, keyword=None):
|
||||
self.value, self.raw, self.keyword = value, raw, keyword
|
||||
|
||||
|
||||
def call_parts(src, call):
|
||||
"""The range between a call's parentheses and the span of every argument in it, wrapping
|
||||
parentheses included: (lo, hi, positional spans, [(keyword span, value span)])."""
|
||||
i = src.span(call.func)[1]
|
||||
while src.text[i] != "(":
|
||||
if src.text[i] == "#":
|
||||
i = src.text.index("\n", i)
|
||||
i += 1
|
||||
lo, hi = i + 1, src.span(call)[1] - 1
|
||||
positional = [src.wrap(*src.span(a), lo, hi) for a in call.args]
|
||||
keywords = []
|
||||
for k in call.keywords:
|
||||
start, end = src.span(k)
|
||||
after = src.text.index("=", start) + 1 if k.arg else start
|
||||
value = src.wrap(*src.span(k.value), after, hi)
|
||||
keywords.append(((start, max(end, value[1])), value))
|
||||
return lo, hi, positional, keywords
|
||||
|
||||
|
||||
def read_call(call, src, parts, render, implicit, d):
|
||||
"""Binds the arguments of `call` to the parameters of `d` (post-rename names). `render` gives
|
||||
a span's text with the calls inside it already rewritten."""
|
||||
if any(isinstance(a, ast.Starred) for a in call.args) or any(k.arg is None for k in call.keywords):
|
||||
raise Skip("uses * or ** unpacking")
|
||||
if len(call.args) == 1 and not call.keywords and isinstance(call.args[0], ast.GeneratorExp):
|
||||
s, e = src.span(call.args[0])
|
||||
if src.text[s] == "(" and src.span(call)[1] == e:
|
||||
raise Skip("passes a generator expression")
|
||||
positional = [r for r in d.rows if r.kind in ("posonly", "normal")][implicit:]
|
||||
named = {r.base(): r for r in d.rows if r.kind in ("normal", "kwonly")}
|
||||
has_varargs = any(r.kind == "vararg" for r in d.rows)
|
||||
has_kwargs = any(r.kind == "kwarg" for r in d.rows)
|
||||
_, _, spans, keyword_spans = parts
|
||||
bound, extras, kwextra = {}, [], []
|
||||
for i, span in enumerate(spans):
|
||||
arg = Arg(render(*span), None)
|
||||
if i < len(positional):
|
||||
bound[positional[i].index] = arg
|
||||
elif has_varargs:
|
||||
extras.append(arg)
|
||||
else:
|
||||
raise Skip("passes too many arguments")
|
||||
for k, (whole, value) in zip(call.keywords, keyword_spans):
|
||||
arg = Arg(render(*value), render(*whole), k.arg)
|
||||
row = named.get(k.arg)
|
||||
if row is not None:
|
||||
if row.index in bound:
|
||||
raise Skip("passes an argument twice")
|
||||
bound[row.index] = arg
|
||||
elif has_kwargs:
|
||||
kwextra.append(arg)
|
||||
else:
|
||||
raise Skip(f"passes an unknown keyword '{k.arg}'")
|
||||
items = [render(*span) for span in spans] + [render(*whole) for whole, _ in keyword_spans]
|
||||
return bound, extras, kwextra, items
|
||||
|
||||
|
||||
def keyword_item(name, arg):
|
||||
return arg.raw if arg.raw is not None and arg.keyword == name else f"{name}={arg.value}"
|
||||
|
||||
|
||||
def check_kinds(rows, kinds, old_rows, bound, extras, kwextra):
|
||||
"""Refuses a call whose values a kept parameter can't take any more because its kind changed."""
|
||||
now = {r["originalIndex"]: k for r, k in zip(rows, kinds) if r["originalIndex"] >= 0}
|
||||
lost = [old_rows[i].name for i in bound if now.get(i) in ("vararg", "kwarg")]
|
||||
for kind, values in (("vararg", extras), ("kwarg", kwextra)):
|
||||
old = next((r for r in old_rows if r.kind == kind), None)
|
||||
if values and old is not None and old.index in now and now[old.index] != kind:
|
||||
lost.append(old.name)
|
||||
if lost:
|
||||
raise Skip(f"passes values that '{lost[0].lstrip('*')}' can't take after its kind changes")
|
||||
|
||||
|
||||
def emit_call(rows, kinds, implicit, bound, extras, kwextra):
|
||||
items, in_order, skipped = [], True, 0
|
||||
# defaults of new parameters stand in for them while a later argument is still positional
|
||||
pending = []
|
||||
for r, k in zip(rows, kinds):
|
||||
base = r["name"].lstrip("*")
|
||||
fresh = r["originalIndex"] < 0
|
||||
arg = None if fresh else bound.get(r["originalIndex"])
|
||||
if k in ("posonly", "normal"):
|
||||
if skipped < implicit:
|
||||
skipped += 1
|
||||
continue
|
||||
if arg is None:
|
||||
if fresh and in_order:
|
||||
pending.append(r["defaultValue"].strip())
|
||||
else:
|
||||
in_order, pending = False, []
|
||||
elif in_order and arg.keyword is None:
|
||||
items += pending + [arg.value]
|
||||
pending = []
|
||||
elif arg.keyword is not None and k != "posonly":
|
||||
# passed by keyword before: it stays that way, and what follows can't be positional
|
||||
in_order, pending = False, []
|
||||
items.append(keyword_item(base, arg))
|
||||
elif k == "posonly":
|
||||
raise Skip(f"cannot pass '{base}' by keyword (positional-only)")
|
||||
else:
|
||||
items.append(keyword_item(base, arg))
|
||||
elif k == "vararg":
|
||||
if extras and not in_order:
|
||||
raise Skip("passes extra positional arguments after an omitted one")
|
||||
items += (pending if extras else []) + [a.value for a in extras]
|
||||
pending = []
|
||||
elif k == "kwonly":
|
||||
if arg is not None:
|
||||
items.append(keyword_item(base, arg))
|
||||
elif k == "kwarg":
|
||||
items += [keyword_item(a.keyword, a) for a in kwextra]
|
||||
return items
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- project
|
||||
|
||||
|
||||
def override_rows(rows, base, own):
|
||||
"""The new rows for an override: a default the dialog didn't change stays the override's own."""
|
||||
out = []
|
||||
for r in rows:
|
||||
i = r["originalIndex"]
|
||||
if i >= 0 and r["defaultValue"].strip() == base.rows[i].default.strip():
|
||||
r = dict(r, defaultValue=own.rows[i].default)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def shape(d):
|
||||
return [(r.kind, r.name) for r in d.rows]
|
||||
|
||||
|
||||
def splice(text, lo, hi, found):
|
||||
"""`text[lo:hi]` with the edits inside it applied; one inside another edit is already part of it."""
|
||||
out, pos = [], lo
|
||||
for start, end, new in sorted(found, key=lambda e: (e[0], -e[1])):
|
||||
if start < pos or end > hi:
|
||||
continue
|
||||
out += [text[pos:start], new]
|
||||
pos = end
|
||||
return "".join(out) + text[pos:hi]
|
||||
|
||||
|
||||
def calls_of(tree):
|
||||
return [n for n in ast.walk(tree) if isinstance(n, ast.Call)]
|
||||
|
||||
|
||||
def value_uses(src, tree):
|
||||
"""End offsets of names and attributes that are read but not called."""
|
||||
called = {id(c.func) for c in calls_of(tree)}
|
||||
return {
|
||||
src.span(n)[1] for n in ast.walk(tree)
|
||||
if isinstance(n, (ast.Name, ast.Attribute)) and isinstance(n.ctx, ast.Load) and id(n) not in called
|
||||
}
|
||||
|
||||
|
||||
def passes_class(func):
|
||||
"""`type(self).m(self)` and `self.__class__.m(self)` call through the class."""
|
||||
value = func.value if isinstance(func, ast.Attribute) else None
|
||||
if isinstance(value, ast.Call):
|
||||
return isinstance(value.func, ast.Name) and value.func.id == "type"
|
||||
return isinstance(value, ast.Attribute) and value.attr == "__class__"
|
||||
|
||||
|
||||
def read_sites(project, req, names, ctor):
|
||||
"""The references a type-aware server reported, read before anything is renamed. Only those
|
||||
naming the function (or its class, or an import alias of either) count. Calls are kept by their
|
||||
position among the file's calls, which renames don't move."""
|
||||
calls, values = {}, []
|
||||
grouped = {}
|
||||
for site in req.get("sites", []):
|
||||
grouped.setdefault(site["path"], []).append(site)
|
||||
for path, found in grouped.items():
|
||||
src = Src(to_resource(project, path).read())
|
||||
try:
|
||||
tree = ast.parse(src.text)
|
||||
except SyntaxError:
|
||||
continue
|
||||
aliases = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
||||
for a in node.names:
|
||||
if a.asname and a.name.split(".")[-1] in names:
|
||||
aliases[a.asname] = a.name.split(".")[-1]
|
||||
by_end = {src.span(c.func)[1]: i for i, c in enumerate(calls_of(tree))}
|
||||
uses = value_uses(src, tree)
|
||||
for site in found:
|
||||
begin = src.pos(site["line"], site["col"])
|
||||
end = begin + site["len"]
|
||||
word = src.text[begin:end]
|
||||
target = aliases.get(word, word)
|
||||
if target not in names:
|
||||
continue
|
||||
if end in by_end:
|
||||
calls.setdefault(path, {})[by_end[end]] = target == ctor
|
||||
elif end in uses and target != ctor:
|
||||
values.append((path, src.line_of(begin)))
|
||||
return calls, values
|
||||
|
||||
|
||||
def open_project(root):
|
||||
return Project(root, ropefolder=None, ignored_resources=IGNORED)
|
||||
|
||||
|
||||
def to_resource(project, path):
|
||||
return libutils.path_to_resource(project, path)
|
||||
|
||||
|
||||
PROPERTY = ("property", "setter", "getter", "deleter", "cached_property")
|
||||
|
||||
|
||||
def check_not_property(d):
|
||||
if any(n.split(".")[-1] in PROPERTY for n in d.decorators()):
|
||||
raise Refused("Cannot change the signature of a property")
|
||||
|
||||
|
||||
def function_at(project, path, caret):
|
||||
"""The ChangeSignature of the function at `caret`, or of the `def` header the caret is in."""
|
||||
res = to_resource(project, path)
|
||||
try:
|
||||
return ChangeSignature(project, res, caret)
|
||||
except RopeError as first:
|
||||
text = res.read()
|
||||
src = Src(text)
|
||||
try:
|
||||
tree = ast.parse(text)
|
||||
except SyntaxError as e:
|
||||
raise Refused(f"Syntax error: {e.msg} (line {e.lineno})")
|
||||
line = src.line_of(caret)
|
||||
best = None
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
header_end = node.body[0].lineno - 1 if node.body[0].lineno > node.lineno else node.lineno
|
||||
if node.lineno <= line <= max(header_end, node.lineno):
|
||||
best = node
|
||||
if best is None:
|
||||
raise Refused("Caret should be on a function, a method or a call of one")
|
||||
found = Def(best, src)
|
||||
check_not_property(found)
|
||||
return ChangeSignature(project, res, found.name_offset)
|
||||
|
||||
|
||||
def defs_by_name_offset(src):
|
||||
tree = ast.parse(src.text)
|
||||
out = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
d = Def(node, src)
|
||||
out[d.name_offset] = (d, node)
|
||||
return out, tree
|
||||
|
||||
|
||||
def locate(cs):
|
||||
"""(path, Def, in_class) of the function the ChangeSignature is about."""
|
||||
func = cs.pyname.get_object()
|
||||
res = func.get_module().get_resource()
|
||||
src = Src(res.read())
|
||||
lineno = func.get_ast().lineno
|
||||
tree = ast.parse(src.text)
|
||||
in_class = isinstance(func.parent, pyobjects.PyClass)
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.lineno == lineno:
|
||||
return res, Def(node, src), in_class
|
||||
raise Refused("The function is defined outside a Python source file")
|
||||
|
||||
|
||||
def check_collision(res, d, new_name):
|
||||
"""Refuses a function name that another definition or variable of the same scope has."""
|
||||
for parent in ast.walk(ast.parse(d.src.text)):
|
||||
body = getattr(parent, "body", None)
|
||||
mine = [n for n in body or [] if getattr(n, "lineno", 0) == d.node.lineno and getattr(n, "name", None) == d.node.name]
|
||||
if not isinstance(body, list) or not mine:
|
||||
continue
|
||||
for node in body:
|
||||
if node is mine[0]:
|
||||
continue
|
||||
names = []
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
||||
names = [node.name]
|
||||
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
||||
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
||||
names = [t.id for t in targets if isinstance(t, ast.Name)]
|
||||
if new_name in names:
|
||||
raise Refused(f"'{new_name}' is already defined in the same scope")
|
||||
|
||||
|
||||
def info(req):
|
||||
project = open_project(req["root"])
|
||||
try:
|
||||
cs = function_at(project, req["file"], caret_offset(project, req))
|
||||
res, d, in_class = locate(cs)
|
||||
kind = d.kind(in_class)
|
||||
decorators = d.decorators()
|
||||
check_not_property(d)
|
||||
return {
|
||||
"name": d.node.name,
|
||||
"kind": kind,
|
||||
"isInit": d.node.name == "__init__",
|
||||
"params": [r.as_json() for r in d.rows],
|
||||
"returnType": d.src.text[slice(*d.src.span(d.node.returns))] if d.node.returns else "",
|
||||
"decorators": decorators,
|
||||
"implicit": 0 if kind in ("function", "static") else 1,
|
||||
"file": res.real_path,
|
||||
"line": d.src.line_of(d.name_offset) - 1,
|
||||
"col": len(d.src.text[d.src.starts[d.src.line_of(d.name_offset) - 1] : d.name_offset].encode("utf-16-le")) // 2,
|
||||
}
|
||||
finally:
|
||||
project.close()
|
||||
|
||||
|
||||
def caret_offset(project, req):
|
||||
text = to_resource(project, req["file"]).read()
|
||||
return Src(text).pos(req["line"], req["col"])
|
||||
|
||||
|
||||
BEFORE = {} # path -> text before this request changed it
|
||||
|
||||
|
||||
def apply_changes(changes):
|
||||
for c in changes.changes:
|
||||
if isinstance(c, ChangeContents):
|
||||
BEFORE.setdefault(c.resource.real_path, c.resource.read())
|
||||
OVERLAY[c.resource.real_path] = c.new_contents
|
||||
|
||||
|
||||
def change(req):
|
||||
spec = req["change"]
|
||||
rows = spec["params"]
|
||||
project = open_project(req["root"])
|
||||
warnings = []
|
||||
try:
|
||||
cs = function_at(project, req["file"], caret_offset(project, req))
|
||||
res, d, in_class = locate(cs)
|
||||
kind = d.kind(in_class)
|
||||
check_not_property(d)
|
||||
old_name = d.node.name
|
||||
new_name = spec["name"].strip()
|
||||
if new_name != old_name and (old_name == "__init__" or not new_name.isidentifier() or keyword.iskeyword(new_name)):
|
||||
raise Refused("Cannot rename the function to '%s'" % new_name)
|
||||
kinds = validate(rows, d, kind)
|
||||
if new_name != old_name:
|
||||
check_collision(res, d, new_name)
|
||||
hierarchy = bool(spec.get("hierarchy")) and in_class
|
||||
kept = {r["originalIndex"] for r in rows}
|
||||
used = {n.id for stmt in d.node.body for n in ast.walk(stmt) if isinstance(n, ast.Name)}
|
||||
for row in d.rows:
|
||||
if row.kind != "marker" and row.index not in kept and row.base() in used:
|
||||
warnings.append(f"Parameter '{row.base()}' is removed but still used in the body of '{old_name}'.")
|
||||
path, def_line, def_name_off = res.real_path, d.node.lineno, d.name_offset
|
||||
for n in d.decorators():
|
||||
if n.split(".")[-1] not in TRANSPARENT:
|
||||
warnings.append(f"'{old_name}' is decorated with @{n}: calls through the decorator may not match the new signature.")
|
||||
renamed = [
|
||||
(r["originalIndex"], r["name"].lstrip("*"))
|
||||
for r in rows
|
||||
if r["originalIndex"] >= 0 and r["name"] not in ("/", "*")
|
||||
and r["name"].lstrip("*") != d.rows[r["originalIndex"]].base()
|
||||
]
|
||||
olds = {r.base() for r in d.rows if r.kind != "marker"}
|
||||
in_body = used | {a.arg for stmt in d.node.body for a in ast.walk(stmt) if isinstance(a, ast.arg)}
|
||||
for i, name in renamed:
|
||||
if name in olds - {d.rows[i].base()}:
|
||||
raise Refused(f"Cannot rename '{d.rows[i].base()}' to '{name}': another parameter has that name")
|
||||
if name in in_body:
|
||||
warnings.append(f"'{name}' is already used in the body of '{old_name}': the renamed parameter '{d.rows[i].base()}' will share it.")
|
||||
|
||||
ctor = cs.others[0] if cs.others else None
|
||||
names = {old_name, ctor} - {None}
|
||||
site_calls, site_values = read_sites(project, req, names, ctor)
|
||||
# the function and, for a method, the overrides that take the same parameters
|
||||
targets = [(path, def_line)]
|
||||
if hierarchy and renamed and cs.is_method():
|
||||
finder = occurrences.create_finder(project, cs.name, cs.pyname, instance=cs.primary, in_hierarchy=True)
|
||||
for resource in project.get_python_files():
|
||||
if old_name not in resource.read():
|
||||
continue
|
||||
try:
|
||||
file_defs, _ = defs_by_name_offset(Src(resource.read()))
|
||||
except SyntaxError:
|
||||
continue
|
||||
for occ in finder.find_occurrences(resource):
|
||||
entry = file_defs.get(occ.get_word_range()[0]) if occ.is_defined() else None
|
||||
key = entry and (resource.real_path, entry[1].lineno)
|
||||
if entry and key not in targets and shape(entry[0]) == shape(d):
|
||||
targets.append(key)
|
||||
project.close()
|
||||
|
||||
def find_def(project, file, line):
|
||||
r = to_resource(project, file)
|
||||
defs, _ = defs_by_name_offset(Src(r.read()))
|
||||
return r, next(v for v in defs.values() if v[0].node.lineno == line)[0]
|
||||
|
||||
steps = [(path, def_line, None)] if new_name != old_name else []
|
||||
steps += [(file, line, one) for file, line in targets for one in renamed]
|
||||
for file, line, step in steps:
|
||||
project = open_project(req["root"])
|
||||
try:
|
||||
r, target = find_def(project, file, line)
|
||||
if step is None:
|
||||
rename = Rename(project, r, target.name_offset)
|
||||
apply_changes(rename.get_changes(new_name, in_hierarchy=hierarchy, docs=True))
|
||||
else:
|
||||
i, name = step
|
||||
row = target.rows[i]
|
||||
if row.base() == name:
|
||||
continue
|
||||
offset = row.span[0] + (len(row.name) - len(row.base()))
|
||||
rename = Rename(project, r, offset)
|
||||
apply_changes(rename.get_changes(name, in_hierarchy=False, docs=False))
|
||||
finally:
|
||||
project.close()
|
||||
|
||||
project = open_project(req["root"])
|
||||
try:
|
||||
r = to_resource(project, path)
|
||||
src = Src(r.read())
|
||||
defs, _ = defs_by_name_offset(src)
|
||||
target = next(v for v in defs.values() if v[0].node.lineno == def_line)[0]
|
||||
cs = ChangeSignature(project, r, target.name_offset)
|
||||
edits = {} # path -> [(start, end, text)]
|
||||
|
||||
def add(p, start, end, text):
|
||||
edits.setdefault(p, []).append((start, end, text))
|
||||
|
||||
finder = occurrences.create_finder(
|
||||
project, cs.name, cs.pyname, instance=cs.primary, in_hierarchy=hierarchy and cs.is_method()
|
||||
)
|
||||
finders = [(finder, False)]
|
||||
if cs.others:
|
||||
finders.append((occurrences.create_finder(project, cs.others[0], cs.others[1], only_calls=True), True))
|
||||
implicit_default = 0 if kind in ("function", "static") else 1
|
||||
same_shape = shape(target)
|
||||
# appending parameters leaves a call through a stored reference valid; anything else may not
|
||||
reshaped = [(r["originalIndex"], k) for r, k in zip(rows, kinds)][: len(target.rows)] != [
|
||||
(r.index, r.kind) for r in target.rows
|
||||
]
|
||||
|
||||
def used_as_value(file, line):
|
||||
if reshaped:
|
||||
message = f"{rel(req, file)}:{line}: '{new_name}' is used as a value; calls through it were not updated."
|
||||
if message not in warnings:
|
||||
warnings.append(message)
|
||||
|
||||
for file, line in site_values:
|
||||
used_as_value(file, line)
|
||||
for resource in project.get_python_files():
|
||||
text = resource.read()
|
||||
words = (cs.name, ctor or cs.name, old_name)
|
||||
if not any(w in text for w in words) and resource.real_path not in site_calls:
|
||||
continue
|
||||
s = Src(text)
|
||||
try:
|
||||
tree = ast.parse(text)
|
||||
except SyntaxError:
|
||||
continue
|
||||
every = calls_of(tree)
|
||||
calls = {s.span(node.func)[1]: node for node in every}
|
||||
uses = value_uses(s, tree)
|
||||
file_defs, _ = defs_by_name_offset(s)
|
||||
found_calls = {} # end of the callee -> (node, is_ctor, receiver_is_class)
|
||||
definitions = []
|
||||
|
||||
for f, is_ctor in finders:
|
||||
for occ in f.find_occurrences(resource):
|
||||
start, end = occ.get_word_range()
|
||||
if occ.is_defined() and not is_ctor:
|
||||
entry = file_defs.get(start)
|
||||
if entry is None:
|
||||
continue
|
||||
od = entry[0]
|
||||
own = resource.real_path == path and od.node.lineno == target.node.lineno
|
||||
if not own and shape(od) != same_shape:
|
||||
warnings.append(f"{rel(req, resource.real_path)}:{od.node.lineno}: the override has a different parameter list and was not updated.")
|
||||
continue
|
||||
es, ee, et = definition_edit(od, rows if own else override_rows(rows, target, od))
|
||||
if et != s.text[es:ee]:
|
||||
definitions.append((es, ee, et))
|
||||
elif occ.is_called():
|
||||
node = calls.get(end)
|
||||
if node is None:
|
||||
continue
|
||||
primary, _ = occ.get_primary_and_pyname()
|
||||
is_class = primary is not None and isinstance(primary.get_object(), pyobjects.PyClass)
|
||||
found_calls.setdefault(end, (node, is_ctor, is_class))
|
||||
elif not is_ctor and end in uses:
|
||||
used_as_value(resource.real_path, s.line_of(start))
|
||||
for index, is_ctor in site_calls.get(resource.real_path, {}).items():
|
||||
node = every[index]
|
||||
end = s.span(node.func)[1]
|
||||
is_class = False
|
||||
if isinstance(node.func, ast.Attribute):
|
||||
try:
|
||||
py = evaluate.eval_location(project.get_pymodule(resource), s.span(node.func.value)[1] - 1)
|
||||
is_class = py is not None and isinstance(py.get_object(), pyobjects.PyClass)
|
||||
except RopeError:
|
||||
pass
|
||||
found_calls.setdefault(end, (node, is_ctor, is_class))
|
||||
# rope renames only the calls it resolves
|
||||
callee = getattr(node.func, "attr", getattr(node.func, "id", None))
|
||||
if new_name != old_name and callee == old_name and not is_ctor:
|
||||
add(resource.real_path, end - len(old_name), end, new_name)
|
||||
|
||||
def render(lo, hi):
|
||||
return splice(s.text, lo, hi, edits.get(resource.real_path, []))
|
||||
|
||||
def rewrite(node, is_ctor, receiver_is_class):
|
||||
where = f"{rel(req, resource.real_path)}:{node.lineno}"
|
||||
try:
|
||||
implicit = implicit_default
|
||||
through_class = receiver_is_class or passes_class(node.func)
|
||||
if kind == "method" and not is_ctor and (isinstance(node.func, ast.Name) or through_class):
|
||||
implicit = 0
|
||||
parts = call_parts(s, node)
|
||||
bound, extras, kwextra, old_items = read_call(node, s, parts, render, implicit, target)
|
||||
check_kinds(rows, kinds, target.rows, bound, extras, kwextra)
|
||||
items = emit_call(rows, kinds, implicit, bound, extras, kwextra)
|
||||
if items == old_items:
|
||||
return
|
||||
lo, hi, positional, keywords = parts
|
||||
spans = positional + [whole for whole, _ in keywords]
|
||||
start, end = lo, hi
|
||||
if items and spans:
|
||||
start, end = min(x[0] for x in spans), max(x[1] for x in spans)
|
||||
if "#" in s.text[start:end]:
|
||||
raise Skip("has comments between its arguments")
|
||||
for kind_, values in (("vararg", extras), ("kwarg", kwextra)):
|
||||
if values and kind_ not in kinds:
|
||||
warnings.append(f"{where}: the values passed to the removed '{'*' if kind_ == 'vararg' else '**'}' parameter are dropped from the call.")
|
||||
add(resource.real_path, start, end, join_items(s, start, end, items))
|
||||
except Skip as why:
|
||||
warnings.append(f"{where}: the call {why} and was not updated.")
|
||||
|
||||
# innermost first, so an outer call carries the rewritten inner ones
|
||||
for node, is_ctor, is_class in sorted(
|
||||
found_calls.values(), key=lambda c: s.span(c[0])[1] - s.span(c[0])[0]
|
||||
):
|
||||
rewrite(node, is_ctor, is_class)
|
||||
for es, ee, et in definitions:
|
||||
if any(es <= a and b <= ee for a, b, _ in edits.get(resource.real_path, [])):
|
||||
raise Refused("A default value calls the function itself; edit it by hand")
|
||||
add(resource.real_path, es, ee, et)
|
||||
files = {}
|
||||
for p, found in edits.items():
|
||||
text = to_resource(project, p).read()
|
||||
BEFORE.setdefault(p, text)
|
||||
files[p] = splice(text, 0, len(text), set(found))
|
||||
for p, text in OVERLAY.items(): # files only the renames touched
|
||||
files.setdefault(p, text)
|
||||
before = {}
|
||||
for p in list(files):
|
||||
old = BEFORE.get(p)
|
||||
if old is None:
|
||||
old = req["original"][p] if p in req["original"] else to_resource(project, p).read()
|
||||
if files[p] == old:
|
||||
del files[p]
|
||||
continue
|
||||
try:
|
||||
ast.parse(files[p])
|
||||
except SyntaxError as e:
|
||||
raise Refused(f"The new signature would make {rel(req, p)} invalid: {e.msg} (line {e.lineno})")
|
||||
before[p] = old
|
||||
return {"files": files, "before": before, "warnings": warnings}
|
||||
finally:
|
||||
project.close()
|
||||
finally:
|
||||
project.close()
|
||||
|
||||
|
||||
def rel(req, path):
|
||||
root = req["root"].rstrip("/")
|
||||
return path[len(root) + 1 :] if path.startswith(root + "/") else path
|
||||
|
||||
|
||||
def main():
|
||||
req = json.loads(sys.stdin.buffer.read()) # not the ANSI code page of Windows
|
||||
overlay = req.get("overlay", {})
|
||||
install_overlay(overlay)
|
||||
# what the editor shows before any change, to compare and to restore CRLF
|
||||
req["original"] = dict(overlay)
|
||||
try:
|
||||
out = {"ok": True, "result": info(req) if req["op"] == "info" else change(req)}
|
||||
except Refused as e:
|
||||
out = {"ok": False, "error": str(e)}
|
||||
except RopeError as e:
|
||||
out = {"ok": False, "error": str(e)}
|
||||
json.dump(out, sys.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Change Signature for Python. rope (from the pylsp-rope environment) finds the function, its
|
||||
//! overrides and calls and renames parameters; `python_signature.py` rewrites the parameter list
|
||||
//! and the arguments. The language server adds the call sites rope can't resolve without types.
|
||||
//! Nothing is written here: the answer is a workspace edit for the preview and undo.
|
||||
use crate::Host;
|
||||
use ide_core::TextEdit;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, DocId, FileEdit, IdeError, IdeResult, IpcPath, Pos, WorkspaceEdit};
|
||||
use ide_lsp::types::{MethodSignature, ProblemSeverity, RefactoringProblem, ServerRefactored, SignatureParameter};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
const HELPER: &str = include_str!("python_signature.py");
|
||||
/// Windows limits a command line to 32767 characters, so the helper arrives on stdin: its length
|
||||
/// on the first line, the script, then the request.
|
||||
const BOOTSTRAP: &str = "import sys; r = sys.stdin.buffer; \
|
||||
exec(compile(r.read(int(r.readline())), 'python_signature.py', 'exec'))";
|
||||
const TIMEOUT: Duration = Duration::from_secs(180);
|
||||
/// What the dialog sends back to accept the warnings of the first answer.
|
||||
const CONFIRMATION: &str = "python-signature";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Answer {
|
||||
ok: bool,
|
||||
error: Option<String>,
|
||||
result: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Info {
|
||||
name: String,
|
||||
params: Vec<Row>,
|
||||
#[serde(rename = "returnType")]
|
||||
return_type: String,
|
||||
file: PathBuf,
|
||||
line: u32,
|
||||
col: u32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Row {
|
||||
name: String,
|
||||
default_value: String,
|
||||
original_index: i32,
|
||||
#[serde(rename = "type")]
|
||||
type_name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Changed {
|
||||
files: BTreeMap<PathBuf, String>,
|
||||
/// The text each file had when the new one was computed from it.
|
||||
before: BTreeMap<PathBuf, String>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct Context {
|
||||
pub(crate) root: PathBuf,
|
||||
pub(crate) file: PathBuf,
|
||||
pub(crate) pos: Pos,
|
||||
pub(crate) overlay: BTreeMap<PathBuf, String>,
|
||||
}
|
||||
|
||||
fn context(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<(std::sync::Arc<crate::Project>, Context)> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
return Err(IdeError::invalid("Change Signature of a Python function needs a Python file"));
|
||||
}
|
||||
let mut overlay = BTreeMap::new();
|
||||
for id in project.documents.open_documents() {
|
||||
if let Ok(other) = project.documents.snapshot(id)
|
||||
&& other.language.as_str() == "python"
|
||||
&& (other.dirty || id == doc)
|
||||
&& other.path.0.is_absolute()
|
||||
{
|
||||
overlay.insert(other.path.0.clone(), other.text);
|
||||
}
|
||||
}
|
||||
let file = snap.path.0.clone();
|
||||
Ok((project.clone(), Context { root: project.root.to_path_buf(), file, pos, overlay }))
|
||||
}
|
||||
|
||||
/// Runs the helper with `request`; its answer is the `result`, a refusal is an invalid-input error.
|
||||
pub(crate) async fn run(
|
||||
host: &Host,
|
||||
helper: &str,
|
||||
mut request: Value,
|
||||
cx: &Context,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Value> {
|
||||
request["root"] = json!(cx.root);
|
||||
request["file"] = json!(cx.file);
|
||||
request["line"] = json!(cx.pos.line);
|
||||
request["col"] = json!(cx.pos.col);
|
||||
request["overlay"] = json!(cx.overlay);
|
||||
let tools = ide_tools::Tools::new(&host.local_data_dir);
|
||||
let mut command = tools.rope_command()?;
|
||||
command.arg("-c").arg(BOOTSTRAP);
|
||||
ide_core::process::prepare(&mut command);
|
||||
ide_core::process::own_group(&mut command);
|
||||
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut command = tokio::process::Command::from(command);
|
||||
command.kill_on_drop(true);
|
||||
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start Python: {e}")))?;
|
||||
let pid = child.id();
|
||||
let mut stdin = child.stdin.take().expect("piped");
|
||||
let payload = format!("{}\n{helper}{request}", helper.len());
|
||||
tokio::spawn(async move {
|
||||
let _ = stdin.write_all(payload.as_bytes()).await;
|
||||
});
|
||||
let cancelled = async {
|
||||
cancel.cancelled().await;
|
||||
if let Some(pid) = pid {
|
||||
let _ = tokio::task::spawn_blocking(move || ide_core::process::kill_tree_of(pid)).await;
|
||||
}
|
||||
};
|
||||
let output = tokio::select! {
|
||||
output = tokio::time::timeout(TIMEOUT, child.wait_with_output()) => match output {
|
||||
Ok(output) => output.map_err(|e| IdeError::internal(e.to_string()))?,
|
||||
Err(_) => return Err(IdeError::unavailable("rope took too long to analyse the project")),
|
||||
},
|
||||
() = cancelled => return Err(IdeError::cancelled()),
|
||||
};
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let answer: Answer = match serde_json::from_slice(&output.stdout) {
|
||||
Ok(answer) => answer,
|
||||
Err(_) if stderr.contains("No module named 'rope'") => return Err(IdeError::missing_tool("pylsp")),
|
||||
Err(_) => {
|
||||
let last = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no answer");
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("rope failed: {last}")));
|
||||
}
|
||||
};
|
||||
match (answer.ok, answer.result) {
|
||||
(true, Some(result)) => Ok(result),
|
||||
_ => Err(IdeError::invalid(answer.error.unwrap_or_else(|| "rope refused the change".into()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature of the Python function at `pos`, for the dialog: parameters are rows of the
|
||||
/// parameter list in source order, `*args` / `**kwargs` / `*` / `/` among them.
|
||||
pub async fn signature_info(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<MethodSignature> {
|
||||
let (_, cx) = context(host, window, doc, pos)?;
|
||||
let info: Info = serde_json::from_value(run(host, HELPER, json!({ "op": "info" }), &cx, &cancel).await?)
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?;
|
||||
Ok(MethodSignature {
|
||||
method_identifier: String::new(),
|
||||
modifier: String::new(),
|
||||
return_type: info.return_type,
|
||||
method_name: info.name,
|
||||
parameters: info
|
||||
.params
|
||||
.into_iter()
|
||||
.map(|r| SignatureParameter {
|
||||
type_name: r.type_name,
|
||||
name: r.name,
|
||||
default_value: r.default_value,
|
||||
original_index: r.original_index,
|
||||
})
|
||||
.collect(),
|
||||
exceptions: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks the new signature and computes the edit for the function, its overrides and its calls.
|
||||
/// Warnings (calls that can't be updated, decorators) come back first, with a token that accepts them.
|
||||
pub async fn change_signature(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
signature: MethodSignature,
|
||||
confirmation: Option<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let (project, cx) = context(host, window, doc, pos)?;
|
||||
// Calls a type-aware server resolves and rope can't (`def f(o: Base): o.run()`). They are asked
|
||||
// for at the function's own name: the caret may be on something else in its header.
|
||||
let info: Info = serde_json::from_value(run(host, HELPER, json!({ "op": "info" }), &cx, &cancel).await?)
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?;
|
||||
let at = if info.file == cx.file { Pos::new(info.line, info.col) } else { pos };
|
||||
let sites = match project.lsp.references_streaming(doc, at, false, true, false, cancel.clone(), None).await {
|
||||
Ok(found) => found
|
||||
.locations
|
||||
.iter()
|
||||
.filter(|l| l.uri.is_none() && l.range.start.line == l.range.end.line)
|
||||
.map(|l| {
|
||||
json!({
|
||||
"path": l.path.0, "line": l.range.start.line, "col": l.range.start.col,
|
||||
"len": l.range.end.col - l.range.start.col,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Err(_) => Vec::<Value>::new(),
|
||||
};
|
||||
let rows: Vec<Value> = signature
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| json!({ "name": p.name, "defaultValue": p.default_value, "originalIndex": p.original_index, "type": "" }))
|
||||
.collect();
|
||||
let request = json!({
|
||||
"op": "change",
|
||||
"sites": sites,
|
||||
"change": { "name": signature.method_name, "params": rows, "hierarchy": true },
|
||||
});
|
||||
let changed: Changed = serde_json::from_value(run(host, HELPER, request, &cx, &cancel).await?)
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, e.to_string()))?;
|
||||
let problems: Vec<RefactoringProblem> = changed
|
||||
.warnings
|
||||
.iter()
|
||||
.map(|message| RefactoringProblem { severity: ProblemSeverity::Warning, message: message.clone() })
|
||||
.collect();
|
||||
if !problems.is_empty() && confirmation.as_deref() != Some(CONFIRMATION) {
|
||||
return Ok(ServerRefactored { problems, edit: None, confirmation: Some(CONFIRMATION.into()) });
|
||||
}
|
||||
let edit = to_edit(&project, changed.files, &changed.before)?;
|
||||
Ok(ServerRefactored { problems: Vec::new(), edit: Some(edit), confirmation: None })
|
||||
}
|
||||
|
||||
/// The text of `path` as the editor has it or would open it: decoded in its own encoding and
|
||||
/// without a byte order mark, so the edits computed against it apply to the same characters.
|
||||
fn current_text(project: &crate::Project, path: &std::path::Path) -> IdeResult<String> {
|
||||
ide_workspace::file_moves::read_text(&project.documents, path)
|
||||
}
|
||||
|
||||
/// Editor text and the helper's compare without byte order mark and line ending differences.
|
||||
fn same_text(a: &str, b: &str) -> bool {
|
||||
let plain = |t: &str| t.trim_start_matches('\u{feff}').replace("\r\n", "\n");
|
||||
plain(a) == plain(b)
|
||||
}
|
||||
|
||||
/// One edit per changed line when no line is added or removed, so the preview counts each changed
|
||||
/// call instead of one block of adjacent lines.
|
||||
fn line_edits(before: &str, after: &str) -> Vec<TextEdit> {
|
||||
let (old, new): (Vec<_>, Vec<_>) = (before.split('\n').collect(), after.split('\n').collect());
|
||||
if old.len() != new.len() {
|
||||
return crate::formatter::diff_edits(&ide_text::Document::new(before), after);
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
for (line, (a, b)) in old.iter().zip(&new).enumerate().filter(|(_, (a, b))| a != b) {
|
||||
for mut edit in crate::formatter::diff_edits(&ide_text::Document::new(a), b) {
|
||||
edit.range.start.line = line as u32;
|
||||
edit.range.end.line = line as u32;
|
||||
edits.push(edit);
|
||||
}
|
||||
}
|
||||
edits
|
||||
}
|
||||
|
||||
pub(crate) fn to_edit(
|
||||
project: &crate::Project,
|
||||
files: BTreeMap<PathBuf, String>,
|
||||
computed_from: &BTreeMap<PathBuf, String>,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let mut edit = WorkspaceEdit::default();
|
||||
for (path, after) in files {
|
||||
let before = current_text(project, &path)?;
|
||||
if computed_from.get(&path).is_some_and(|seen| !same_text(seen, &before)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} changed while the refactoring was being computed; run it again",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
let edits = line_edits(&before, &after);
|
||||
if !edits.is_empty() {
|
||||
edit.files.push(FileEdit::Edit { path: IpcPath(path), edits, version: None });
|
||||
}
|
||||
}
|
||||
Ok(edit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adjacent_changed_lines_stay_separate_edits() {
|
||||
let edits = line_edits("f(1, 2)\nf(3, 4)\n", "f(2, 1)\nf(4, 3)\n");
|
||||
assert_eq!(edits.iter().map(|e| e.range.start.line).collect::<Vec<_>>(), [0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_changed_meanwhile_is_told_apart_from_line_endings() {
|
||||
assert!(same_text("\u{feff}a\r\n", "a\n"));
|
||||
assert!(!same_text("a\n", "b\n"));
|
||||
}
|
||||
}
|
||||
@@ -616,6 +616,82 @@ async fn crud_boot_service_lifecycle_and_markdown_roundtrip() {
|
||||
assert!(!imported.enabled, "imported .automation.md must default to disabled");
|
||||
assert_eq!(imported.max_runs, Some(50));
|
||||
|
||||
// Add a sooner OneShot schedule and verify `list()` orders by soonest `next_run_ms` first,
|
||||
// followed by enabled idle/manual schedules, then paused automations at the bottom.
|
||||
let sooner_ms = cron_auto.next_run_ms.unwrap() - 60_000.0;
|
||||
let sooner_auto = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "Sooner OneShot".into(),
|
||||
enabled: true,
|
||||
prompt: AgentPrompt { text: "soon".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(root.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: false,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![],
|
||||
permissions: AutomationPermissionMode::Default,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::OneShot { run_at_ms: sooner_ms },
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let enabled_manual = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "Enabled Manual".into(),
|
||||
enabled: true,
|
||||
prompt: AgentPrompt { text: "manual".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(root.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: false,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![],
|
||||
permissions: AutomationPermissionMode::Default,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let ordered_ids: Vec<String> = host.automations.list(Some(&root)).into_iter().map(|a| a.id).collect();
|
||||
assert_eq!(
|
||||
ordered_ids[..3],
|
||||
[sooner_auto.id.clone(), cron_auto.id.clone(), enabled_manual.id.clone()],
|
||||
"active schedules must sort soonest next_run_ms first, then enabled idle, then paused: {ordered_ids:?}"
|
||||
);
|
||||
assert!(
|
||||
ordered_ids[3..].contains(&imported.id) && ordered_ids[3..].contains(&manual.id),
|
||||
"paused automations must appear after active/enabled schedules: {ordered_ids:?}"
|
||||
);
|
||||
|
||||
// Turning off autoStartService in settings unregisters the OS boot service immediately
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.autoStartService", serde_json::json!(false))
|
||||
@@ -634,6 +710,8 @@ async fn crud_boot_service_lifecycle_and_markdown_roundtrip() {
|
||||
assert!(paused >= 1);
|
||||
assert!(!service_file.exists());
|
||||
|
||||
agent_automation_delete(&host, "main", sooner_auto.id).await.unwrap();
|
||||
agent_automation_delete(&host, "main", enabled_manual.id).await.unwrap();
|
||||
agent_automation_delete(&host, "main", manual.id).await.unwrap();
|
||||
agent_automation_delete(&host, "main", cron_auto.id).await.unwrap();
|
||||
agent_automation_delete(&host, "main", imported.id).await.unwrap();
|
||||
|
||||
@@ -6,8 +6,8 @@ use ide_agent::{McpScope, McpServer, McpServerInput};
|
||||
use ide_core::settings::McpTransport;
|
||||
use ide_host::Host;
|
||||
use ide_host::ops::agent::{
|
||||
agent_mcp_import as mcp_import, agent_mcp_list as mcp_list, agent_mcp_save as mcp_save,
|
||||
agent_mcp_set_enabled as mcp_set_enabled,
|
||||
agent_mcp_import as mcp_import, agent_mcp_list as mcp_list, agent_mcp_remove as mcp_remove,
|
||||
agent_mcp_save as mcp_save, agent_mcp_set_enabled as mcp_set_enabled,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -58,6 +58,8 @@ async fn workspace_servers_from_the_project_file_stay_off_until_the_user_turns_t
|
||||
url: None,
|
||||
headers: vec![],
|
||||
agents: vec![],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -69,3 +71,64 @@ async fn workspace_servers_from_the_project_file_stay_off_until_the_user_turns_t
|
||||
assert!(!enabled(&imported, "workspace::imported"));
|
||||
assert!(enabled(&imported, "workspace::mine"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn registry_provenance_round_trips_survives_edit_and_uninstalls_cleanly() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (host, _root) = open(tmp.path());
|
||||
|
||||
// Install from registry into User scope.
|
||||
let saved = mcp_save(
|
||||
&host,
|
||||
"main",
|
||||
McpServerInput {
|
||||
id: None,
|
||||
name: "playwright-mcp".into(),
|
||||
scope: McpScope::User,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled: true,
|
||||
command: Some("npx".into()),
|
||||
args: vec!["-y".into(), "@playwright/mcp".into()],
|
||||
env: vec![],
|
||||
url: None,
|
||||
headers: vec![],
|
||||
agents: vec![],
|
||||
registry_name: Some("microsoft/playwright-mcp".into()),
|
||||
registry_url: Some("https://api.mcp.github.com".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed = saved.iter().find(|s| s.id == "user::playwright-mcp").expect("installed server present");
|
||||
assert_eq!(installed.registry_name.as_deref(), Some("microsoft/playwright-mcp"));
|
||||
assert_eq!(installed.registry_url.as_deref(), Some("https://api.mcp.github.com"));
|
||||
|
||||
// Updating the server without re-sending registry fields preserves provenance.
|
||||
let edited = mcp_save(
|
||||
&host,
|
||||
"main",
|
||||
McpServerInput {
|
||||
id: Some("user::playwright-mcp".into()),
|
||||
name: "playwright-mcp".into(),
|
||||
scope: McpScope::User,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled: true,
|
||||
command: Some("npx".into()),
|
||||
args: vec!["-y".into(), "@playwright/mcp".into(), "--headless".into()],
|
||||
env: vec![],
|
||||
url: None,
|
||||
headers: vec![],
|
||||
agents: vec!["copilot".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let after_edit = edited.iter().find(|s| s.id == "user::playwright-mcp").expect("edited server present");
|
||||
assert_eq!(after_edit.registry_name.as_deref(), Some("microsoft/playwright-mcp"));
|
||||
assert_eq!(after_edit.registry_url.as_deref(), Some("https://api.mcp.github.com"));
|
||||
assert_eq!(after_edit.agents, vec!["copilot"]);
|
||||
|
||||
// One-click uninstall removes the server cleanly.
|
||||
let after_remove = mcp_remove(&host, "main", "user::playwright-mcp".into()).unwrap();
|
||||
assert!(!after_remove.iter().any(|s| s.id == "user::playwright-mcp"));
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The PHP of a Docker and of a Compose run target, against a real daemon. Ignored by default:
|
||||
//! `docker` with the Compose plugin must be on `PATH` and able to pull `php:8.3-cli`.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_host::{Host, ops};
|
||||
use std::sync::Arc;
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires a Docker daemon"]
|
||||
async fn reads_the_php_of_docker_and_compose_targets() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(project.path()).unwrap();
|
||||
std::fs::write(root.join("compose.yaml"), "services:\n app:\n image: php:8.3-cli\n").unwrap();
|
||||
let state = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(Host::new(common::host_config(state.path())));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project(WINDOW, &root).unwrap();
|
||||
let targets = serde_json::json!([
|
||||
{ "kind": "docker", "id": "image", "name": "PHP image", "image": "php:8.3-cli" },
|
||||
{ "kind": "compose", "id": "app", "name": "Compose app", "service": "app" },
|
||||
{ "kind": "docker", "id": "none", "name": "No PHP", "image": "php:8.3-cli", "php": "/opt/missing/php" },
|
||||
{ "kind": "ssh", "id": "box", "name": "Box" },
|
||||
]);
|
||||
ops::project::set_settings(
|
||||
&host,
|
||||
WINDOW,
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"runTargets",
|
||||
&targets.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for (id, name) in [("image", "PHP image"), ("app", "Compose app")] {
|
||||
let php = ops::sdk::sdk_container_php(&host, WINDOW, id.into(), false).await.unwrap();
|
||||
eprintln!("{id}: {php:?}");
|
||||
assert_eq!((php.target.as_str(), php.name.as_str()), (id, name));
|
||||
assert!(php.php_version.starts_with("8.3."), "{php:?}");
|
||||
assert_eq!(php.xdebug, None, "the official image has no Xdebug");
|
||||
// The answer is kept, and asked again on refresh.
|
||||
assert_eq!(ops::sdk::sdk_container_php(&host, WINDOW, id.into(), false).await.unwrap(), php);
|
||||
assert_eq!(ops::sdk::sdk_container_php(&host, WINDOW, id.into(), true).await.unwrap(), php);
|
||||
}
|
||||
|
||||
let missing = ops::sdk::sdk_container_php(&host, WINDOW, "none".into(), false).await.unwrap_err();
|
||||
eprintln!("no php: {}", missing.message);
|
||||
assert!(missing.message.contains("/opt/missing/php"), "{}", missing.message);
|
||||
let ssh = ops::sdk::sdk_container_php(&host, WINDOW, "box".into(), false).await.unwrap_err();
|
||||
assert!(ssh.message.contains("not a container"), "{}", ssh.message);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Reformat Code with CSharpier (#7626), against the real `dotnet` and CSharpier from NuGet.
|
||||
//! It downloads CSharpier, so it runs only on request:
|
||||
//! `cargo test -p ide-host --test csharpier -- --ignored`; skipped without a .NET SDK.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeEvent, IdeResult, Pos, Range, TextEdit};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::FormatOptions;
|
||||
use ide_workspace::SettingsScope;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
const MESSY: &str = "class A{void M( ){var x=1;}}\n";
|
||||
const TIDY: &str = "class A\n{\n void M()\n {\n var x = 1;\n }\n}\n";
|
||||
|
||||
fn dotnet(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("dotnet").args(args).current_dir(dir).output().expect("dotnet");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"dotnet {args:?}: {}{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
fn has_dotnet() -> bool {
|
||||
Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A tool manifest in `dir` with CSharpier `version`, restored.
|
||||
fn local_tool(dir: &Path, manifest: &str, version: &str, command: &str) {
|
||||
write(
|
||||
&dir.join(manifest),
|
||||
&format!(
|
||||
r#"{{"version":1,"isRoot":true,"tools":{{"csharpier":{{"version":"{version}","commands":["{command}"]}}}}}}"#
|
||||
),
|
||||
);
|
||||
dotnet(dir, &["tool", "restore"]);
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
host: Arc<Host>,
|
||||
notices: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new(trusted: bool) -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let notices = Arc::new(Mutex::new(Vec::new()));
|
||||
let seen = notices.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let seen = seen.clone();
|
||||
Arc::new(move |event: IdeEvent| {
|
||||
if let IdeEvent::Notify { body: Some(body), .. } = event {
|
||||
seen.lock().unwrap().push(body);
|
||||
}
|
||||
})
|
||||
}),
|
||||
..common::host_config(&base.join("host"))
|
||||
}));
|
||||
host.set_project_trust(&root, trusted, false).await.unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
Self { _tmp: tmp, root, host, notices }
|
||||
}
|
||||
|
||||
/// Reformat Code on the open document of `name` holding `text`; the result applied to it.
|
||||
async fn format(&self, name: &str, text: &str, range: Option<Range>, on_save: bool) -> IdeResult<String> {
|
||||
let path = self.root.join(name);
|
||||
write(&path, text);
|
||||
let doc = ops::doc::doc_open(&self.host, "main", path.clone()).await?;
|
||||
let options = FormatOptions { tab_size: 4, insert_spaces: true, on_save, tool: None };
|
||||
let edits: Vec<TextEdit> = ops::lsp::lsp_format(&self.host, "main", doc.id, range, options).await?;
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), text, "formatting must not write the file");
|
||||
// The open buffer holds no byte order mark (saving writes it back).
|
||||
let mut formatted = ide_text::Document::new(text.trim_start_matches('\u{feff}'));
|
||||
formatted.apply_edits(&edits).unwrap();
|
||||
ops::doc::doc_close(&self.host, "main", doc.id).await?;
|
||||
Ok(formatted.text())
|
||||
}
|
||||
|
||||
fn notices(&self) -> Vec<String> {
|
||||
std::mem::take(&mut self.notices.lock().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
||||
async fn a_local_csharpier_formats_the_unsaved_document() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(true).await;
|
||||
local_tool(&f.root, "dotnet-tools.json", "1.4.2", "csharpier");
|
||||
|
||||
// The manifest alone makes the project a CSharpier one.
|
||||
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
||||
|
||||
// A configuration in a subfolder applies there only.
|
||||
write(&f.root.join("sub/.csharpierrc"), "indentSize: 2\n");
|
||||
assert_eq!(f.format("sub/A.cs", MESSY, None, false).await.unwrap(), TIDY.replace(" ", " "));
|
||||
assert_eq!(f.format("B.cs", MESSY, None, false).await.unwrap(), TIDY);
|
||||
assert!(f.notices().is_empty());
|
||||
|
||||
// `.csharpierignore`d and generated files stay as they are, with a notice.
|
||||
write(&f.root.join(".csharpierignore"), "Ignored.cs\n");
|
||||
assert_eq!(f.format("Ignored.cs", MESSY, None, false).await.unwrap(), MESSY);
|
||||
assert_eq!(f.notices(), ["CSharpier left the file unchanged: its configuration excludes it"]);
|
||||
assert_eq!(f.format("Form.g.cs", MESSY, None, false).await.unwrap(), MESSY);
|
||||
f.notices();
|
||||
|
||||
// A syntax error is the tool's message and no edits.
|
||||
let error = f.format("Broken.cs", "class B{ void M( { \n", None, false).await.unwrap_err();
|
||||
assert!(error.message.contains("syntax errors"), "{}", error.message);
|
||||
|
||||
// CRLF, a byte order mark and non-ASCII text survive; the document keeps its line endings.
|
||||
let crlf = "\u{feff}class 中{void M( ){var s=\"日本語 é 😀\";}}\r\n";
|
||||
let formatted = f.format("Unicode.cs", crlf, None, false).await.unwrap();
|
||||
assert!(formatted.contains("class 中\n{") && formatted.contains("var s = \"日本語 é 😀\";"), "{formatted:?}");
|
||||
|
||||
// A selection is the language server's (none runs here), never a whole-file rewrite.
|
||||
let selection = Some(Range::new(Pos::new(0, 0), Pos::new(0, 7)));
|
||||
if let Ok(text) = f.format("Selected.cs", MESSY, selection, false).await {
|
||||
assert_eq!(text, MESSY);
|
||||
}
|
||||
assert!(f.notices().is_empty());
|
||||
|
||||
// Saving formats only with format on save.
|
||||
let on_save = |enabled: bool| {
|
||||
let value = enabled.to_string();
|
||||
ops::project::set_settings(&f.host, "main", SettingsScope::Global, "editor.formatOnSave", &value).unwrap();
|
||||
};
|
||||
on_save(false);
|
||||
assert_eq!(f.format("Save.cs", MESSY, None, true).await.unwrap(), MESSY);
|
||||
on_save(true);
|
||||
assert_eq!(f.format("Save.cs", MESSY, None, true).await.unwrap(), TIDY);
|
||||
|
||||
// A large file is within the formatter's time limit.
|
||||
let methods: String = (0..4000).map(|i| format!("void M{i}( ){{var x={i};}}\n")).collect();
|
||||
let large = f.format("Large.cs", &format!("class L{{\n{methods}}}\n"), None, false).await.unwrap();
|
||||
assert!(large.contains(" void M3999()\n"));
|
||||
|
||||
// `format_text` (a document that is not open, as the commit dialog's) uses it too.
|
||||
let options = FormatOptions { tab_size: 4, insert_spaces: true, on_save: false, tool: None };
|
||||
let edits = ops::lsp::lsp_format_text(&f.host, "main", f.root.join("A.cs"), MESSY.into(), options).await.unwrap();
|
||||
assert!(!edits.is_empty());
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
||||
async fn an_unrestored_local_tool_reports_dotnets_message() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(true).await;
|
||||
write(
|
||||
&f.root.join(".config/dotnet-tools.json"),
|
||||
r#"{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"9.9.9","commands":["csharpier"]}}}"#,
|
||||
);
|
||||
let error = f.format("A.cs", MESSY, None, false).await.unwrap_err();
|
||||
assert!(error.message.contains("dotnet tool restore"), "{}", error.message);
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
||||
async fn csharpier_before_1_0_formats_through_its_pipe() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(true).await;
|
||||
local_tool(&f.root, ".config/dotnet-tools.json", "0.30.6", "dotnet-csharpier");
|
||||
write(&f.root.join(".csharpierignore"), "Ignored.cs\n");
|
||||
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
||||
assert_eq!(f.format("Ignored.cs", MESSY, None, false).await.unwrap(), MESSY);
|
||||
let error = f.format("Broken.cs", "class B{ \n", None, false).await.unwrap_err();
|
||||
assert!(error.message.contains("Broken.cs") || error.message.contains("compile"), "{}", error.message);
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
||||
async fn an_installed_global_tool_formats_a_configured_project() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(true).await;
|
||||
write(&f.root.join(".csharpierrc.json"), "{}");
|
||||
// The install Settings runs, into the host's own data folder.
|
||||
let data = f.root.parent().unwrap().join("host").join("data");
|
||||
let languages: Vec<_> = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
ide_tools::Tools::new(&data).install("csharpier", &languages, &Default::default(), &|_| {}).unwrap();
|
||||
assert_eq!(f.format("A.cs", MESSY, None, false).await.unwrap(), TIDY);
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "downloads CSharpier and needs the .NET SDK"]
|
||||
async fn restricted_mode_runs_no_csharpier() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let f = Fixture::new(false).await;
|
||||
write(
|
||||
&f.root.join("dotnet-tools.json"),
|
||||
r#"{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"1.4.2","commands":["csharpier"]}}}"#,
|
||||
);
|
||||
// The language server's path: nothing runs, so nothing changes.
|
||||
match f.format("A.cs", MESSY, None, false).await {
|
||||
Ok(text) => assert_eq!(text, MESSY),
|
||||
Err(e) => assert_ne!(e.kind, ErrorKind::Internal, "{}", e.message),
|
||||
}
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
@@ -2525,6 +2525,54 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
|
||||
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn indexed_project_discovers_deeply_nested_skills_and_skips_gitignored_and_fixture_files() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
|
||||
let write_file = |rel: &str, body: &str| {
|
||||
let p = h.root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, body).unwrap();
|
||||
};
|
||||
// Initialize a minimal `.git` directory so `.gitignore` rules apply during indexing.
|
||||
std::fs::create_dir_all(h.root.join(".git")).unwrap();
|
||||
write_file(".gitignore", "ignored-tree/\n");
|
||||
write_file(
|
||||
"mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md",
|
||||
"---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n",
|
||||
);
|
||||
write_file(
|
||||
"crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md",
|
||||
"---\nname: fixture-only\ndescription: Unrelated fixture\n---\n",
|
||||
);
|
||||
write_file(
|
||||
"ignored-tree/a/b/c/.github/skills/ignored-skill/SKILL.md",
|
||||
"---\nname: ignored-skill\ndescription: Gitignored deep skill\n---\n",
|
||||
);
|
||||
|
||||
h.host.close_project("main");
|
||||
let project = h.host.open_project("main", &h.root).unwrap();
|
||||
assert!(project.index.wait_idle(std::time::Duration::from_secs(10)));
|
||||
|
||||
let skills = ide_host::ops::agent::agent_skills_list(&h.host, "main").await.unwrap();
|
||||
assert!(
|
||||
skills.iter().any(|s| {
|
||||
s.skill.name == "edit-grafana-dashboards" && s.skill.source == ide_agent::AgentSkillSource::GithubWorkspace
|
||||
}),
|
||||
"deeply nested skill discovered via ProjectIndex: {skills:?}"
|
||||
);
|
||||
assert!(!skills.iter().any(|s| s.skill.name == "fixture-only"), "unrelated fixture ignored");
|
||||
assert!(!skills.iter().any(|s| s.skill.name == "ignored-skill"), "gitignored deep skill ignored");
|
||||
|
||||
// AgentManager::commands uses the project's skills_policy_hook and also surfaces the deep skill.
|
||||
let commands = project.agents.commands("copilot", None).await.unwrap();
|
||||
assert!(
|
||||
commands.iter().any(|c| c.name == "edit-grafana-dashboards"),
|
||||
"deeply nested skill surfaced in session slash commands: {commands:?}"
|
||||
);
|
||||
}
|
||||
|
||||
const DEV_CONTAINER_TOOLS: [&str; 5] =
|
||||
["devcontainer_status", "devcontainer_logs", "devcontainer_up", "devcontainer_exec", "devcontainer_stop"];
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ fn input(name: &str, scope: McpScope) -> McpServerInput {
|
||||
url: Some("https://mcp.example/v1".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: format!("Bearer {VALUE}") }],
|
||||
agents: vec![],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ fn method() -> SymbolTag {
|
||||
kind: SymbolKind::Method,
|
||||
container: None,
|
||||
range: Range::new(Pos::new(0, 4), Pos::new(0, 8)),
|
||||
definition: true,
|
||||
bases: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +221,7 @@ async fn indexed_usages_rename_preview_staleness_and_grouped_undo() {
|
||||
kind: ide_core::SymbolKind::Method,
|
||||
container: None,
|
||||
range: ide_core::Range::new(Pos::new(0, 4), Pos::new(0, 5)),
|
||||
definition: true,
|
||||
bases: Vec::new(),
|
||||
};
|
||||
plugins
|
||||
|
||||
@@ -3609,6 +3609,26 @@ fn settings_actions_choose_their_layer_without_losing_the_project() {
|
||||
}
|
||||
}
|
||||
|
||||
/// API 1.21: radio, segmented, slider, colour and checkbox-list settings, `enumOptions` with
|
||||
/// icons and `when` conditions reach the page; the option icons are served sanitised.
|
||||
#[test]
|
||||
fn settings_controls_project_with_their_option_icons() {
|
||||
let f = fixture(Limits::default());
|
||||
let info = f.install(&sample("settings-controls"));
|
||||
assert!(info.error.is_none(), "{:?}", info.error);
|
||||
let settings = f.host.ui_items("settings").into_iter().find(|s| s.plugin_id == "settings-controls").unwrap();
|
||||
let props = settings.decl["properties"].as_array().unwrap();
|
||||
let presentations: Vec<_> = props.iter().map(|p| p["presentation"].as_str().unwrap_or("")).collect();
|
||||
assert_eq!(presentations, ["segmented", "slider", "radio", "color", "checkbox-list", "slider", ""]);
|
||||
assert_eq!(props[0]["enumOptions"][0]["label"], "Compact");
|
||||
assert_eq!(props[3]["when"], serde_json::json!({"key": "folders", "in": ["specific", "classic"]}));
|
||||
assert!(settings.decl["iconRevision"].is_string());
|
||||
let icons: Vec<_> =
|
||||
f.host.assets("settings-controls", "settingIcon/").unwrap().into_iter().map(|(id, _)| id).collect();
|
||||
assert_eq!(icons.len(), 4, "{icons:?}");
|
||||
assert!(icons.contains(&"settingIcon/density/0/dark".to_owned()));
|
||||
}
|
||||
|
||||
/// API 1.19: a plugin opens Settings at its own node, one of its declared pages or its
|
||||
/// permissions, in the invoking window; it can't name a page it doesn't declare. Its
|
||||
/// `[capabilities.reasons]` come with the permissions, translated.
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
//! Python Move through the commands the app calls, on real files: each moved project is run with
|
||||
//! Python before and after, and must print the same. `#[ignore]`d: it needs `pylsp` on `PATH`
|
||||
//! (the helper runs with that environment's Python).
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, IdeEvent, RequestId, SharedSink, TextChange};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::ServerRefactored;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Project {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
host: Host,
|
||||
events: Arc<Mutex<Vec<IdeEvent>>>,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
async fn new(files: &[(&str, &str)]) -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("app");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
|
||||
for (name, text) in files {
|
||||
let path = root.join(name);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
};
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| sink.clone()),
|
||||
..common::host_config(&root.join(".app"))
|
||||
});
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
Self { _tmp: tmp, root, host, events }
|
||||
}
|
||||
|
||||
/// Moves `names` of `source` to `dest`, accepting any warnings, and applies the edit.
|
||||
async fn try_move(&self, source: &str, names: &[&str], dest: &str) -> Result<Vec<String>, String> {
|
||||
let doc = ops::doc::doc_open(&self.host, "main", self.root.join(source)).await.unwrap();
|
||||
let args = json!({ "names": names, "file": dest }).to_string();
|
||||
let send = |confirmation| {
|
||||
ops::lsp::lsp_java_move(
|
||||
&self.host,
|
||||
"main",
|
||||
RequestId(1),
|
||||
doc.id,
|
||||
"python".into(),
|
||||
args.clone(),
|
||||
confirmation,
|
||||
)
|
||||
};
|
||||
let mut answer: ServerRefactored = send(None).await.map_err(|e| e.message)?;
|
||||
let mut warnings = Vec::new();
|
||||
if answer.confirmation.is_some() {
|
||||
assert!(answer.edit.is_none(), "nothing before the confirmation");
|
||||
warnings = answer.problems.iter().map(|p| p.message.clone()).collect();
|
||||
answer = send(answer.confirmation).await.map_err(|e| e.message)?;
|
||||
}
|
||||
ops::lsp::apply_workspace_edit(&self.host, "main", answer.edit.expect("an edit")).await.unwrap();
|
||||
Ok(warnings)
|
||||
}
|
||||
|
||||
async fn text(&self, file: &str) -> String {
|
||||
let doc = ops::doc::doc_open(&self.host, "main", self.root.join(file)).await.unwrap();
|
||||
ops::doc::doc_snapshot(&self.host, "main", doc.id).await.unwrap().text
|
||||
}
|
||||
|
||||
/// Writes the editors' texts out and runs `main.py`.
|
||||
async fn output(&self) -> String {
|
||||
self.output_without(&[]).await
|
||||
}
|
||||
|
||||
async fn output_without(&self, skipped: &[&str]) -> String {
|
||||
for file in walk(&self.root).into_iter().filter(|f| !skipped.contains(&f.as_str())) {
|
||||
let text = self.text(&file).await;
|
||||
std::fs::write(self.root.join(file), text).unwrap();
|
||||
}
|
||||
let out = std::process::Command::new(if cfg!(windows) { "python" } else { "python3" })
|
||||
.args(["-B", "main.py"])
|
||||
.current_dir(&self.root)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
|
||||
}
|
||||
}
|
||||
|
||||
fn walk(root: &std::path::Path) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut folders = vec![root.to_path_buf()];
|
||||
while let Some(folder) = folders.pop() {
|
||||
for entry in std::fs::read_dir(folder).unwrap().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() && !entry.file_name().to_string_lossy().starts_with('.') {
|
||||
folders.push(path);
|
||||
} else if path.extension().is_some_and(|e| e == "py") {
|
||||
found.push(path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
const LIB: &str = r#""""Library."""
|
||||
import os
|
||||
from math import floor
|
||||
|
||||
SEP = os.sep
|
||||
LIMIT: int = 3
|
||||
|
||||
|
||||
def helper(x):
|
||||
return floor(x) + LIMIT
|
||||
|
||||
|
||||
# The thing to move.
|
||||
# 中文注释 🎉
|
||||
@staticmethod
|
||||
def double(x) -> "int":
|
||||
return helper(x) * 2
|
||||
|
||||
|
||||
class Box:
|
||||
def __init__(self, v=LIMIT):
|
||||
self.v = double(v)
|
||||
|
||||
|
||||
def keep():
|
||||
return Box().v
|
||||
"#;
|
||||
|
||||
const MAIN: &str = r#"import pkg.lib
|
||||
import pkg.lib as aliased
|
||||
from pkg import lib
|
||||
from pkg.lib import Box, double as twice, keep
|
||||
from pkg import Box as Exported
|
||||
|
||||
print(pkg.lib.Box(1).v, aliased.double(1), lib.double(2))
|
||||
print(Box(2).v, twice(3), keep(), Exported().v)
|
||||
"#;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn moves_into_a_new_module_and_updates_every_spelling_then_undoes_it() {
|
||||
let p = Project::new(&[
|
||||
("pkg/__init__.py", "from .lib import Box\n"),
|
||||
("pkg/lib.py", LIB),
|
||||
("pkg/rel.py", "from . import lib\nfrom .lib import Box\n\n\ndef f():\n return lib.Box().v + Box().v\n"),
|
||||
("main.py", &format!("{MAIN}from pkg.rel import f\nprint(f())\n")),
|
||||
])
|
||||
.await;
|
||||
let before = p.output().await;
|
||||
let warnings = p.try_move("pkg/lib.py", &["double", "Box"], "pkg/shapes/box.py").await.unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("import each other")), "{warnings:?}");
|
||||
|
||||
let lib = p.text("pkg/lib.py").await;
|
||||
assert!(lib.contains("from pkg.shapes.box import Box\n"), "{lib}");
|
||||
assert!(!lib.contains("def double") && !lib.contains("class Box") && !lib.contains("中文"), "{lib}");
|
||||
let moved = p.text("pkg/shapes/box.py").await;
|
||||
assert!(moved.contains("# The thing to move.\n# 中文注释 🎉\n@staticmethod\ndef double"), "{moved}");
|
||||
assert!(moved.contains("from pkg.lib import LIMIT\n") && moved.contains("from pkg.lib import helper\n"), "{moved}");
|
||||
assert_eq!(p.text("pkg/__init__.py").await, "from .shapes.box import Box\n");
|
||||
// The two modules now import each other, which is the one warning.
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
|
||||
let id = p
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
ops::lsp::undo_workspace_edit(&p.host, "main", id).await.unwrap();
|
||||
assert!(!p.root.join("pkg/shapes").join("box.py").exists(), "the new module is removed again");
|
||||
assert_eq!(p.text("pkg/lib.py").await, LIB);
|
||||
assert_eq!(p.output().await, before);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn the_moved_project_runs_the_same() {
|
||||
let p = Project::new(&[
|
||||
("pkg/__init__.py", "from .lib import Box\n"),
|
||||
(
|
||||
"pkg/lib.py",
|
||||
"from __future__ import annotations\n\nimport json\nfrom . import consts\nfrom .consts import N as COUNT\n\n\nclass Box:\n v: int = COUNT + consts.N\n\n def dump(self) -> str:\n return json.dumps(self.v)\n\n\ndef make():\n return Box()\n\n\nprint(make().dump())\n",
|
||||
),
|
||||
("pkg/consts.py", "N = 2\n"),
|
||||
("pkg/other.py", "\"\"\"Doc.\"\"\"\nimport sys\n\nHAVE = sys.maxsize > 0\n"),
|
||||
(
|
||||
"main.py",
|
||||
"import pkg.lib\nfrom pkg.lib import *\nfrom pkg import lib as l\nfrom pkg import Box as B\n\nprint(Box().dump(), l.make().v, pkg.lib.Box.v, B.v, make().v)\n",
|
||||
),
|
||||
])
|
||||
.await;
|
||||
let before = p.output().await;
|
||||
let warnings = p.try_move("pkg/lib.py", &["Box"], "pkg/other.py").await.unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("import *")), "{warnings:?}");
|
||||
let other = p.text("pkg/other.py").await;
|
||||
assert!(other.starts_with("\"\"\"Doc.\"\"\"\nfrom __future__ import annotations\n"), "{other}");
|
||||
assert!(other.contains("from pkg.consts import N as COUNT\n") && other.contains("import json\n"), "{other}");
|
||||
assert_eq!(p.output().await, before);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn a_destination_that_uses_the_name_gets_it_defined_first() {
|
||||
let p = Project::new(&[
|
||||
("a.py", "def f():\n return 1\n\n\ndef g():\n return 2\n"),
|
||||
("b.py", "import a\nfrom a import f, g\n\nX = f() + a.f() + g()\n"),
|
||||
("main.py", "import b\nprint(b.X, b.f())\n"),
|
||||
])
|
||||
.await;
|
||||
let before = p.output().await;
|
||||
// unsaved: a use that exists only in the editor
|
||||
let doc = ops::doc::doc_open(&p.host, "main", p.root.join("main.py")).await.unwrap();
|
||||
let at = doc.text.len() as u32;
|
||||
let change =
|
||||
ChangeSet { changes: vec![TextChange { from: at, to: at, insert: "import a\nprint(a.f())\n".into() }] };
|
||||
ops::doc::doc_edit(&p.host, "main", doc.id, doc.version, change).await.unwrap();
|
||||
p.try_move("a.py", &["f"], "b.py").await.unwrap();
|
||||
let b = p.text("b.py").await;
|
||||
assert!(b.find("def f").unwrap() < b.find("X = ").unwrap(), "{b}");
|
||||
assert!(b.contains("X = f() + f() + g()"), "{b}");
|
||||
assert!(p.text("main.py").await.contains("print(b.f())"), "{}", p.text("main.py").await);
|
||||
assert_eq!(p.output().await, format!("{before}1\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn refuses_what_it_cannot_move_safely_and_changes_nothing() {
|
||||
let source = "import os\n\nA = 1\nA = 2\n\n\ndef f():\n return os.sep\n\n\ndef g():\n global C\n C = 1\n\n\nC = 0\nD = 1; E = 2\n";
|
||||
let p = Project::new(&[
|
||||
("a.py", source),
|
||||
("taken.py", "def f():\n pass\n"),
|
||||
("os_is_mine.py", "os = 1\n"),
|
||||
("alias.py", "from a import f as h\n"),
|
||||
("broken.py", "def (:\n"),
|
||||
])
|
||||
.await;
|
||||
for (names, dest, reason) in [
|
||||
(vec!["f"], "taken.py", "already defined"),
|
||||
(vec!["f"], "os_is_mine.py", "means something else"),
|
||||
(vec!["f"], "alias.py", "another name"),
|
||||
(vec!["f"], "broken.py", "Syntax error"),
|
||||
(vec!["f"], "a.py", "itself"),
|
||||
(vec!["f"], "new.txt", ".py file"),
|
||||
(vec!["f"], "../out.py", ".py file"),
|
||||
(vec!["f"], "1bad.py", "Python module"),
|
||||
(vec!["A"], "new.py", "several places"),
|
||||
(vec!["g"], "new.py", "global"),
|
||||
(vec!["C"], "new.py", "global"),
|
||||
(vec!["D"], "new.py", "shares its line"),
|
||||
(vec!["missing"], "new.py", "not a top-level"),
|
||||
(vec![], "new.py", "Select"),
|
||||
] {
|
||||
let error = p.try_move("a.py", &names, dest).await.unwrap_err();
|
||||
assert!(error.contains(reason), "{names:?} -> {dest}: {error}");
|
||||
}
|
||||
assert_eq!(p.text("a.py").await, source);
|
||||
assert!(!p.root.join("new.py").exists());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn reports_what_it_leaves_alone() {
|
||||
let p = Project::new(&[
|
||||
("a.py", "def f():\n return __name__\n"),
|
||||
("use.py", "import a\n\nTARGET = 'a.f'\n\n\ndef g(a):\n return a.f\n"),
|
||||
("broken.py", "import a\ndef (:\n"),
|
||||
])
|
||||
.await;
|
||||
let warnings = p.try_move("a.py", &["f"], "b.py").await.unwrap();
|
||||
for part in ["__name__", "the string 'a.f'", "local name", "syntax error"] {
|
||||
assert!(warnings.iter().any(|w| w.contains(part)), "{part}: {warnings:?}");
|
||||
}
|
||||
assert!(p.text("use.py").await.ends_with("def g(a):\n return a.f\n"));
|
||||
assert_eq!(p.text("a.py").await, "");
|
||||
assert_eq!(p.text("b.py").await, "def f():\n return __name__\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn lists_the_movable_names_and_marks_the_one_at_the_caret() {
|
||||
let p = Project::new(&[("lib.py", LIB)]).await;
|
||||
let doc = ops::doc::doc_open(&p.host, "main", p.root.join("lib.py")).await.unwrap();
|
||||
let line = LIB.lines().position(|l| l == "@staticmethod").unwrap();
|
||||
let args = json!({ "line": line }).to_string();
|
||||
let found = ops::lsp::lsp_java_move_destinations(&p.host, "main", RequestId(1), doc.id, "python".into(), args)
|
||||
.await
|
||||
.unwrap();
|
||||
let found: Vec<serde_json::Value> = found.iter().map(|s| serde_json::from_str(s).unwrap()).collect();
|
||||
let names: Vec<_> = found.iter().map(|s| s["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["SEP", "LIMIT", "helper", "double", "Box", "keep"]);
|
||||
let selected: Vec<_> = found.iter().filter(|s| s["selected"] == true).map(|s| &s["name"]).collect();
|
||||
assert_eq!(selected, ["double"]);
|
||||
}
|
||||
|
||||
/// Order at import time: moved code goes after what it needs and before what needs it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn places_the_code_where_the_destination_still_runs() {
|
||||
let p = Project::new(&[
|
||||
("a.py", "def f():\n return 1\n # end of f\n\n\nclass C(__import__('b').Base):\n pass\n"),
|
||||
(
|
||||
"b.py",
|
||||
"class Base:\n pass\n\n\ndef main():\n print(f())\n\n\nif __name__ == '__main__':\n main()\n\n\ndef lazy():\n from a import f\n return f()\n",
|
||||
),
|
||||
("main.py", "import runpy\n\nimport b\n\nrunpy.run_path('b.py', run_name='__main__')\nprint(b.lazy())\n"),
|
||||
])
|
||||
.await;
|
||||
p.try_move("a.py", &["f"], "b.py").await.unwrap();
|
||||
let b = p.text("b.py").await;
|
||||
assert!(b.find("def f").unwrap() < b.find("if __name__").unwrap(), "{b}");
|
||||
assert!(b.contains("# end of f") && !p.text("a.py").await.contains("end of f"), "{b}");
|
||||
assert_eq!(p.output().await, "1\n1\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn every_import_of_the_module_gets_the_new_one() {
|
||||
let p = Project::new(&[
|
||||
("a.py", "import urllib.parse\nimport urllib.request\n\n\ndef f():\n return urllib.parse.quote(' '), urllib.request.__name__\n"),
|
||||
(
|
||||
"main.py",
|
||||
"def g():\n import a\n return a.f()\n\n\ndef h():\n import a\n return a.f()\n\n\nimport a; print(a.f())\ntry: import a\nexcept ImportError: pass\nprint(g(), h(), a.f())\n",
|
||||
),
|
||||
])
|
||||
.await;
|
||||
let before = p.output().await;
|
||||
p.try_move("a.py", &["f"], "b.py").await.unwrap();
|
||||
assert_eq!(p.output().await, before);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn refuses_shadowed_names_and_shadowed_destinations() {
|
||||
let source = "def f():\n pass\n";
|
||||
let p = Project::new(&[
|
||||
("a.py", source),
|
||||
("use.py", "import a\n\n\ndef g(b):\n return a.f(), b\n"),
|
||||
("utils/__init__.py", ""),
|
||||
("pkg.py", ""),
|
||||
("early.py", "X = f()\n\n\nclass Base:\n pass\n"),
|
||||
("c.py", "from early import Base\n\n\nclass D(Base):\n pass\n"),
|
||||
])
|
||||
.await;
|
||||
for (dest, reason) in [("b.py", "already uses the name 'b'"), ("utils.py", "same name"), ("pkg/x.py", "same name")]
|
||||
{
|
||||
let error = p.try_move("a.py", &["f"], dest).await.unwrap_err();
|
||||
assert!(error.contains(reason), "{dest}: {error}");
|
||||
}
|
||||
p.try_move("c.py", &["D"], "early.py").await.unwrap();
|
||||
assert!(p.text("early.py").await.find("class Base").unwrap() < p.text("early.py").await.find("class D").unwrap());
|
||||
assert_eq!(p.text("a.py").await, source);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn refuses_a_destination_behind_a_link_out_of_the_project() {
|
||||
let p = Project::new(&[("a.py", "def f():\n pass\n")]).await;
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
std::os::unix::fs::symlink(outside.path(), p.root.join("linked")).unwrap();
|
||||
let error = p.try_move("a.py", &["f"], "linked/b.py").await.unwrap_err();
|
||||
assert!(error.contains("inside the project"), "{error}");
|
||||
}
|
||||
|
||||
/// Closed files keep their byte order mark and encoding; a package's `from . import name` follows.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp on PATH"]
|
||||
async fn closed_files_in_other_encodings_and_package_imports() {
|
||||
let p = Project::new(&[
|
||||
("pkg/__init__.py", "# Copyright ACME\ndef helper():\n return 1\n"),
|
||||
("pkg/rel.py", "from . import helper\n\nX = helper()\n"),
|
||||
("bom.py", "\u{feff}import os\nfrom pkg import helper\nprint(helper(), os.sep != '')\n"),
|
||||
("main.py", "import bom\nfrom pkg.rel import X\nprint(X)\n"),
|
||||
])
|
||||
.await;
|
||||
// GBK, not UTF-8
|
||||
std::fs::write(p.root.join("gbk.py"), b"# -*- coding: gbk -*-\n# \xd6\xd0\nimport os\n").unwrap();
|
||||
let before = p.output_without(&["gbk.py"]).await;
|
||||
p.try_move("pkg/__init__.py", &["helper"], "pkg/tools.py").await.unwrap();
|
||||
assert!(std::fs::read(p.root.join("bom.py")).unwrap().starts_with("\u{feff}import os\n".as_bytes()));
|
||||
assert!(p.text("pkg/__init__.py").await.starts_with("# Copyright ACME"));
|
||||
assert!(p.text("pkg/rel.py").await.contains("tools import helper"), "{}", p.text("pkg/rel.py").await);
|
||||
assert_eq!(p.output_without(&["gbk.py"]).await, before);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Python rename's "Search in comments and strings" against the real basedpyright: the rename, the
|
||||
//! merged edit the preview shows, applying it and undoing it in one step. Needs
|
||||
//! `basedpyright-langserver` on PATH:
|
||||
//! `cargo test -p ide-host --test python_rename_comments -- --ignored`
|
||||
mod common;
|
||||
|
||||
use ide_core::{IdeEvent, Pos, RequestId, WorkspaceEdit};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use parking_lot::Mutex;
|
||||
use std::{path::Path, sync::Arc, time::Duration};
|
||||
|
||||
const LIB: &str = r#"__all__ = ["load_user"]
|
||||
|
||||
|
||||
def load_user(user_id):
|
||||
"""Run load_user(user_id) for one user_id.
|
||||
|
||||
>>> load_user(1)
|
||||
"""
|
||||
# load_user reads user_id; reload_user and load_users stay.
|
||||
label = f"load_user {user_id} \"user_id\" \nuser_id"
|
||||
return user_id, label
|
||||
|
||||
|
||||
class Repo:
|
||||
def load_user(self):
|
||||
# unrelated method of the same name
|
||||
return None
|
||||
|
||||
|
||||
def other():
|
||||
# user_id outside load_user
|
||||
return "user_id"
|
||||
"#;
|
||||
|
||||
const APP: &str = r#"from lib import load_user
|
||||
|
||||
# 😀 café: load_user
|
||||
print("😀 load_user", load_user(user_id=1))
|
||||
"#;
|
||||
|
||||
/// The position of the first `needle` in `file`.
|
||||
fn at(text: &str, needle: &str) -> Pos {
|
||||
let byte = text.find(needle).unwrap();
|
||||
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
|
||||
Pos::new(text[..byte].matches('\n').count() as u32, text[start..byte].encode_utf16().count() as u32)
|
||||
}
|
||||
|
||||
async fn rename(host: &Host, doc: ide_core::DocId, pos: Pos, old: &str, new: &str, files: usize) -> WorkspaceEdit {
|
||||
for _ in 0..120 {
|
||||
let renamed = ops::lsp::lsp_rename(host, "main", RequestId(1), doc, pos, new.into()).await;
|
||||
if let Ok(renamed) = renamed
|
||||
&& renamed.edit.files.len() >= files
|
||||
{
|
||||
return ops::refactor::refactor_python_mention_edits(
|
||||
host,
|
||||
"main",
|
||||
RequestId(2),
|
||||
old.into(),
|
||||
new.into(),
|
||||
renamed.edit,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.edit;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
panic!("basedpyright did not rename {old}");
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs basedpyright-langserver on PATH"]
|
||||
async fn python_rename_searches_comments_and_strings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let (lib, app, notes, closed) =
|
||||
(root.join("lib.py"), root.join("app.py"), root.join("notes.md"), root.join("x.py"));
|
||||
std::fs::write(&lib, LIB).unwrap();
|
||||
std::fs::write(&app, APP).unwrap();
|
||||
std::fs::write(¬es, "load_user\n").unwrap();
|
||||
// A file that is not open and has no code reference, with a BOM and CRLF.
|
||||
std::fs::write(&closed, "\u{feff}# load_user\r\nload_user = 1\r\n").unwrap();
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let sink = events.clone();
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let sink = sink.clone();
|
||||
Arc::new(move |e| sink.lock().push(e))
|
||||
}),
|
||||
..common::host_config(&tmp.path().join("ide"))
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let doc = ops::doc::doc_open(&host, "main", lib.clone()).await.unwrap();
|
||||
let app_doc = ops::doc::doc_open(&host, "main", app.clone()).await.unwrap();
|
||||
// An unsaved comment line exists only in the buffer.
|
||||
let end = APP.encode_utf16().count() as u32;
|
||||
let changes = ide_core::ChangeSet {
|
||||
changes: vec![ide_core::TextChange { from: end, to: end, insert: "# unsaved load_user\n".into() }],
|
||||
};
|
||||
ops::doc::doc_edit(&host, "main", app_doc.id, app_doc.version, changes).await.unwrap();
|
||||
|
||||
// A local (a parameter): only its own function's mentions change, not the same text in another one.
|
||||
let edit = rename(&host, doc.id, at(LIB, "user_id):"), "user_id", "uid", 1).await;
|
||||
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
let after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
|
||||
assert!(after.contains("def load_user(uid):\n \"\"\"Run load_user(uid) for one uid."), "{after}");
|
||||
assert!(after.contains(r#"f"load_user {uid} \"uid\" \nuid""#), "{after}");
|
||||
assert!(after.contains("# user_id outside load_user\n return \"user_id\""), "{after}");
|
||||
let undo = |events: &Mutex<Vec<IdeEvent>>| {
|
||||
events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
|
||||
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
|
||||
|
||||
// A module-level function: comments and strings in all of the project's Python files.
|
||||
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "fetch_user", 2).await;
|
||||
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
let lib_after = ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text;
|
||||
assert!(lib_after.starts_with("__all__ = [\"fetch_user\"]"), "{lib_after}");
|
||||
assert!(lib_after.contains(">>> fetch_user(1)"), "{lib_after}");
|
||||
assert!(lib_after.contains("# fetch_user reads user_id; reload_user and load_users stay."), "{lib_after}");
|
||||
// An unrelated method with the same name: its code is left alone.
|
||||
assert!(lib_after.contains("def load_user(self):"), "{lib_after}");
|
||||
let app_after = ops::doc::doc_snapshot(&host, "main", app_doc.id).await.unwrap().text;
|
||||
assert_eq!(app_after, format!("{APP}# unsaved load_user\n").replace("load_user", "fetch_user"));
|
||||
let closed_after = read(&closed);
|
||||
assert!(closed_after.contains("# fetch_user\r\nload_user = 1"), "{closed_after:?}");
|
||||
assert_eq!(read(¬es), "load_user\n");
|
||||
|
||||
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
|
||||
assert_eq!(ops::doc::doc_snapshot(&host, "main", doc.id).await.unwrap().text, LIB);
|
||||
assert_eq!(read(&closed), "\u{feff}# load_user\r\nload_user = 1\r\n");
|
||||
|
||||
// Renaming a parameter from a keyword argument in another file: comments change in its function, not at the caller.
|
||||
let (base, caller) = (root.join("base.py"), root.join("caller.py"));
|
||||
std::fs::write(&base, "class Base:\n def run(self, speed):\n return speed # base speed\n").unwrap();
|
||||
let call = "from base import Base\n\n# outside speed\nBase().run(speed=1)\n";
|
||||
std::fs::write(&caller, call).unwrap();
|
||||
let caller_doc = ops::doc::doc_open(&host, "main", caller.clone()).await.unwrap();
|
||||
let edit = rename(&host, caller_doc.id, at(call, "speed=1"), "speed", "pace", 2).await;
|
||||
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
assert!(read(&base).contains("return pace # base pace"), "{}", read(&base));
|
||||
assert!(read(&caller).contains("# outside speed"));
|
||||
ops::lsp::undo_workspace_edit(&host, "main", undo(&events).unwrap()).await.unwrap();
|
||||
|
||||
// A symlink in the project to a file outside it is not changed.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let outside = tmp.path().join("outside.py");
|
||||
std::fs::write(&outside, "# load_user\n").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, root.join("link.py")).unwrap();
|
||||
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
|
||||
let text = format!("{:?}", edit.files);
|
||||
assert!(!text.contains("outside.py") && !text.contains("link.py"), "{text}");
|
||||
}
|
||||
|
||||
// A file with only comment matches changed after the preview: applying must fail rather than write at stale positions.
|
||||
let edit = rename(&host, doc.id, at(LIB, "load_user(user_id):"), "load_user", "get_user", 2).await;
|
||||
std::fs::write(&closed, "keep = 'untouched line'\n# load_user\n").unwrap();
|
||||
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap_err();
|
||||
assert_eq!(read(&closed), "keep = 'untouched line'\n# load_user\n");
|
||||
assert_eq!(read(&lib), LIB);
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
//! Python Change Signature against real rope: the matrix of `python_signature.py`. `#[ignore]`d
|
||||
//! because it needs rope: `cargo test -p ide-host --test python_signature -- --ignored`.
|
||||
//! The interpreter is `$ROPE_PYTHON`,
|
||||
//! else `python3` / `python`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Relative to the crate directory, where `cargo test` and the smoke job run the binary.
|
||||
const HELPER: &str = "src/python_signature.py";
|
||||
|
||||
fn python() -> String {
|
||||
if let Ok(python) = std::env::var("ROPE_PYTHON") {
|
||||
return python;
|
||||
}
|
||||
["python3", "python"]
|
||||
.into_iter()
|
||||
.find(|p| Command::new(p).args(["-c", "import rope"]).output().is_ok_and(|o| o.status.success()))
|
||||
.expect("python with rope (pip install rope) on PATH, or ROPE_PYTHON")
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// A parameter row: name, default, index in the current parameter list (-1: new).
|
||||
type Row = (&'static str, &'static str, i32);
|
||||
|
||||
struct Project {
|
||||
dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
fn new(files: &[(&str, &str)]) -> Self {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (name, text) in files {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
Self { dir }
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
std::fs::canonicalize(self.dir.path()).unwrap()
|
||||
}
|
||||
|
||||
fn run(&self, request: Value) -> Value {
|
||||
let mut child = Command::new(python())
|
||||
.arg(HELPER)
|
||||
// what a Windows console would decode stdin with
|
||||
.env("PYTHONIOENCODING", "cp1252")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.stdin.take().unwrap().write_all(request.to_string().as_bytes()).unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
serde_json::from_slice(&out.stdout).unwrap()
|
||||
}
|
||||
|
||||
/// `word` on the first line of `file` containing `line`, as an LSP position.
|
||||
fn at(&self, file: &str, line: &str, word: &str) -> (usize, usize) {
|
||||
let text = std::fs::read_to_string(self.root().join(file)).unwrap();
|
||||
let (i, l) = text.lines().enumerate().find(|(_, l)| l.contains(line)).expect("line");
|
||||
(i, l[..l.find(line).unwrap() + line.find(word).unwrap()].encode_utf16().count())
|
||||
}
|
||||
|
||||
fn request(&self, op: &str, file: &str, at: (usize, usize), overlay: &BTreeMap<String, String>) -> Value {
|
||||
let overlay: BTreeMap<String, &String> =
|
||||
overlay.iter().map(|(k, v)| (self.root().join(k).to_string_lossy().into_owned(), v)).collect();
|
||||
json!({
|
||||
"op": op, "root": self.root(), "file": self.root().join(file), "line": at.0, "col": at.1,
|
||||
"overlay": overlay,
|
||||
})
|
||||
}
|
||||
|
||||
/// The parameter rows rope reads at `at`.
|
||||
fn info(&self, file: &str, line: &str, word: &str) -> Result<Vec<String>, String> {
|
||||
let at = self.at(file, line, word);
|
||||
let answer = self.run(self.request("info", file, at, &BTreeMap::new()));
|
||||
if answer["ok"] != true {
|
||||
return Err(answer["error"].as_str().unwrap().to_owned());
|
||||
}
|
||||
Ok(answer["result"]["params"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| p["name"].as_str().unwrap().to_owned())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn change(&self, c: &Change) -> Result<(BTreeMap<String, String>, Vec<String>), String> {
|
||||
let at = self.at(c.file, c.line, c.word);
|
||||
let mut request = self.request("change", c.file, at, &c.overlay());
|
||||
let rows: Vec<Value> = c
|
||||
.rows
|
||||
.iter()
|
||||
.map(|(n, d, i)| json!({ "name": n, "defaultValue": d, "originalIndex": i, "type": "" }))
|
||||
.collect();
|
||||
request["change"] = json!({ "name": c.name, "params": rows, "hierarchy": true });
|
||||
request["sites"] = c
|
||||
.sites
|
||||
.iter()
|
||||
.map(|(file, line, word)| {
|
||||
let (l, col) = self.at(file, line, word);
|
||||
json!({ "path": self.root().join(file), "line": l, "col": col, "len": word.trim_end_matches('(').len() })
|
||||
})
|
||||
.collect();
|
||||
let answer = self.run(request);
|
||||
if answer["ok"] != true {
|
||||
return Err(answer["error"].as_str().unwrap().to_owned());
|
||||
}
|
||||
let root = self.root();
|
||||
let files = answer["result"]["files"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
Path::new(k).strip_prefix(&root).unwrap().to_string_lossy().into_owned(),
|
||||
v.as_str().unwrap().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let warnings =
|
||||
answer["result"]["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_owned()).collect();
|
||||
Ok((files, warnings))
|
||||
}
|
||||
}
|
||||
|
||||
struct Change {
|
||||
file: &'static str,
|
||||
line: &'static str,
|
||||
word: &'static str,
|
||||
name: &'static str,
|
||||
rows: Vec<Row>,
|
||||
unsaved: Vec<(&'static str, &'static str)>,
|
||||
/// Calls a type-aware server reports: file, a line, and the word on it that names the function.
|
||||
sites: Vec<(&'static str, &'static str, &'static str)>,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
fn overlay(&self) -> BTreeMap<String, String> {
|
||||
self.unsaved.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn change(file: &'static str, line: &'static str, word: &'static str, name: &'static str, rows: Vec<Row>) -> Change {
|
||||
Change { file, line, word, name, rows, unsaved: Vec::new(), sites: Vec::new() }
|
||||
}
|
||||
|
||||
/// Runs `c` on `files` and compares every changed file; `expect` lists exactly the files that change.
|
||||
#[track_caller]
|
||||
fn check(files: &[(&str, &str)], c: Change, expect: &[(&str, &str)]) -> Vec<String> {
|
||||
let project = Project::new(files);
|
||||
let (changed, warnings) = project.change(&c).unwrap_or_else(|e| panic!("refused: {e}"));
|
||||
let want: BTreeMap<String, String> = expect.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
assert_eq!(changed, want);
|
||||
warnings
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn refused(files: &[(&str, &str)], c: Change) -> String {
|
||||
Project::new(files).change(&c).expect_err("should be refused")
|
||||
}
|
||||
|
||||
const LIB: &str = "def f(a, b=2, *args, key=1, **kw):\n return a\n";
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn reads_the_parameter_list_from_a_call_a_header_or_the_class() {
|
||||
let files = [(
|
||||
"lib.py",
|
||||
"class C:\n def __init__(self, a, /, b=1, *, c):\n pass\n\n def m(self, x):\n pass\n\n\ndef f(a, b=2, *args, key=1, **kw):\n return a\n\n\nf(1)\nC(1, c=2).m(3)\n",
|
||||
)];
|
||||
let p = Project::new(&files);
|
||||
let rows = |r: Result<Vec<String>, String>| r.unwrap().join(" ");
|
||||
assert_eq!(rows(p.info("lib.py", "def f(", "f(")), "a b *args key **kw");
|
||||
assert_eq!(rows(p.info("lib.py", "def f(a, b=2", "b=2")), "a b *args key **kw", "caret inside the header");
|
||||
assert_eq!(rows(p.info("lib.py", "f(1)", "f(")), "a b *args key **kw", "caret on a call");
|
||||
assert_eq!(rows(p.info("lib.py", "def __init__", "__init__")), "self a / b * c");
|
||||
assert_eq!(rows(p.info("lib.py", "class C", "C")), "self a / b * c", "the class stands for __init__");
|
||||
assert_eq!(rows(p.info("lib.py", "C(1, c=2).m(3)", "m(")), "self x", "caret on a method call");
|
||||
assert!(p.info("lib.py", " return a", "return").is_err(), "caret in a body is not a function");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn reorders_positional_arguments_in_every_file_through_re_exports_and_relative_imports() {
|
||||
// A call through an alias (`import f as g`) is a reference the language server reports.
|
||||
let mut c = change("pkg/core.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]);
|
||||
c.sites = vec![("top.py", "g(5, 6)", "g")];
|
||||
check(
|
||||
&[
|
||||
("pkg/__init__.py", "from .core import f\n"),
|
||||
("pkg/core.py", "def f(a, b):\n return a - b\n"),
|
||||
("pkg/sub/use.py", "from .. import f\n\nf(1, 2)\nf(b=2, a=1)\n"),
|
||||
("top.py", "import pkg\nfrom pkg.core import f as g\n\npkg.f(3, 4)\ng(5, 6)\n"),
|
||||
],
|
||||
c,
|
||||
&[
|
||||
("pkg/core.py", "def f(b, a):\n return a - b\n"),
|
||||
("pkg/sub/use.py", "from .. import f\n\nf(2, 1)\nf(b=2, a=1)\n"),
|
||||
("top.py", "import pkg\nfrom pkg.core import f as g\n\npkg.f(4, 3)\ng(6, 5)\n"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn keeps_annotations_defaults_decorators_and_the_return_type() {
|
||||
check(
|
||||
&[(
|
||||
"m.py",
|
||||
"import functools\n\n\n@functools.cache\ndef f(a: int, b: str = \"x\", *, flag: bool = False, n: int = 0) -> dict[str, int]: # note\n return {}\n\n\nf(1, \"y\", flag=True)\n",
|
||||
)],
|
||||
change(
|
||||
"m.py",
|
||||
"def f(",
|
||||
"f(",
|
||||
"f",
|
||||
vec![("a", "", 0), ("b", "\"x\"", 1), ("*", "", 2), ("n", "0", 4), ("flag", "False", 3)],
|
||||
),
|
||||
&[(
|
||||
"m.py",
|
||||
"import functools\n\n\n@functools.cache\ndef f(a: int, b: str = \"x\", *, n: int = 0, flag: bool = False) -> dict[str, int]: # note\n return {}\n\n\nf(1, \"y\", flag=True)\n",
|
||||
)],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_a_default_before_a_parameter_without_one() {
|
||||
let e = refused(&[("m.py", LIB)], change("m.py", "def f(", "f(", "f", vec![("b", "2", 1), ("a", "", 0)]));
|
||||
assert!(e.contains("follows a parameter with a default"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn moves_a_defaulted_parameter_to_keyword_style_calls_when_it_is_skipped() {
|
||||
// `f(1, 2)` binds a=1, b=2; with `b` moved after `c=0` the call keeps meaning by naming it.
|
||||
check(
|
||||
&[("m.py", "def f(a, b=2, c=0):\n pass\n\n\nf(1, 5)\nf(1, c=3)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "0", 2), ("b", "2", 1)]),
|
||||
&[("m.py", "def f(a, c=0, b=2):\n pass\n\n\nf(1, b=5)\nf(1, c=3)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn adds_a_parameter_with_a_default_and_calls_stay_valid() {
|
||||
check(
|
||||
&[("m.py", "def f(a, b):\n pass\n\n\nf(1, 2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "", 1), ("c", "None", -1)]),
|
||||
&[("m.py", "def f(a, b, c=None):\n pass\n\n\nf(1, 2)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn an_added_default_stands_in_while_a_later_argument_stays_positional() {
|
||||
check(
|
||||
&[("m.py", "def f(a, b=2):\n pass\n\n\nf(1, 5)\nf(1)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "0", -1), ("b", "2", 1)]),
|
||||
&[("m.py", "def f(a, c=0, b=2):\n pass\n\n\nf(1, 0, 5)\nf(1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_a_new_parameter_without_a_default() {
|
||||
let e = refused(&[("m.py", LIB)], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("z", "", -1)]));
|
||||
assert!(e.contains("Default value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn removes_a_parameter_from_positional_and_keyword_calls() {
|
||||
let warnings = check(
|
||||
&[("m.py", "def f(a, b, c=3):\n return a + c\n\n\nf(1, 2)\nf(1, 2, 4)\nf(1, c=4, b=2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "3", 2)]),
|
||||
&[("m.py", "def f(a, c=3):\n return a + c\n\n\nf(1)\nf(1, 4)\nf(1, c=4)\n")],
|
||||
);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn warns_when_a_removed_parameter_is_still_used() {
|
||||
let warnings = check(
|
||||
&[("m.py", "def f(a, b):\n return a + b\n\n\nf(1, 2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0)]),
|
||||
&[("m.py", "def f(a):\n return a + b\n\n\nf(1)\n")],
|
||||
);
|
||||
assert!(warnings[0].contains("'b' is removed but still used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn renames_parameters_in_the_body_and_in_keyword_arguments_but_not_in_other_scopes() {
|
||||
check(
|
||||
&[
|
||||
(
|
||||
"m.py",
|
||||
"def f(a, b=2):\n xs = [a for a in range(3)]\n\n def g(a):\n return a\n\n return a + b\n",
|
||||
),
|
||||
("u.py", "from m import f\n\nf(a=1)\nf(1, b=3)\n"),
|
||||
],
|
||||
change("m.py", "def f(", "f(", "f", vec![("first", "", 0), ("b", "2", 1)]),
|
||||
&[
|
||||
(
|
||||
"m.py",
|
||||
"def f(first, b=2):\n xs = [a for a in range(3)]\n\n def g(a):\n return a\n\n return first + b\n",
|
||||
),
|
||||
("u.py", "from m import f\n\nf(first=1)\nf(1, b=3)\n"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn renames_the_function_everywhere() {
|
||||
check(
|
||||
&[("m.py", "def f(a):\n pass\n"), ("u.py", "from m import f\n\nf(1)\n")],
|
||||
change("m.py", "def f(", "f(", "run", vec![("a", "", 0)]),
|
||||
&[("m.py", "def run(a):\n pass\n"), ("u.py", "from m import run\n\nrun(1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn variadic_parameters_move_with_their_arguments() {
|
||||
check(
|
||||
&[("m.py", "def f(a, *args, **kw):\n pass\n\n\nf(1, 2, 3, x=4)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("sep", "None", -1), ("*args", "", 1), ("**kw", "", 2)]),
|
||||
&[("m.py", "def f(a, sep=None, *args, **kw):\n pass\n\n\nf(1, None, 2, 3, x=4)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn dropping_args_drops_the_extra_positional_arguments() {
|
||||
let warnings = check(
|
||||
&[("m.py", "def f(a, *args):\n pass\n\n\nf(1, 2, 3)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0)]),
|
||||
&[("m.py", "def f(a):\n pass\n\n\nf(1)\n")],
|
||||
);
|
||||
assert!(warnings[0].contains("removed '*' parameter"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn keyword_only_and_positional_only_markers_follow_their_parameters() {
|
||||
check(
|
||||
&[("m.py", "def f(a, b, /, c, *, d):\n pass\n\n\nf(1, 2, 3, d=4)\nf(1, 2, c=3, d=4)\n")],
|
||||
change(
|
||||
"m.py",
|
||||
"def f(",
|
||||
"f(",
|
||||
"f",
|
||||
vec![("a", "", 0), ("b", "", 1), ("/", "", 2), ("*", "", 4), ("c", "", 3), ("d", "", 5)],
|
||||
),
|
||||
&[("m.py", "def f(a, b, /, *, c, d):\n pass\n\n\nf(1, 2, c=3, d=4)\nf(1, 2, c=3, d=4)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_what_python_rejects() {
|
||||
let at =
|
||||
|rows: Vec<Row>| refused(&[("m.py", "def f(a, b, c):\n pass\n")], change("m.py", "def f(", "f(", "f", rows));
|
||||
assert!(at(vec![("a", "", 0), ("a", "", 1)]).contains("Duplicate parameter name"));
|
||||
assert!(at(vec![("a", "", 0), ("class", "1", -1)]).contains("not a valid parameter name"));
|
||||
assert!(at(vec![("a", "", 0), ("*", "", -1)]).contains("keyword-only"));
|
||||
assert!(at(vec![("**kw", "", -1), ("a", "", 0)]).contains("must be last"));
|
||||
assert!(at(vec![("a", "", 0), ("*x", "", -1), ("*y", "", -1)]).contains("Only one"));
|
||||
assert!(at(vec![("a", "", 0), ("b", "1+", -1)]).contains("not a valid expression"));
|
||||
let e = refused(
|
||||
&[("m.py", "def f(a, b):\n pass\n")],
|
||||
change("m.py", "def f(", "f(", "class", vec![("a", "", 0), ("b", "", 1)]),
|
||||
);
|
||||
assert!(e.contains("Cannot rename"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_renaming_a_parameter_to_the_name_of_another() {
|
||||
let e = refused(
|
||||
&[("m.py", "def f(a, b):\n pass\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 0), ("a", "", 1)]),
|
||||
);
|
||||
assert!(e.contains("another parameter has that name"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn methods_change_with_their_overrides_and_every_kind_of_call() {
|
||||
let files = [
|
||||
(
|
||||
"m.py",
|
||||
"class Base:\n def run(self, x, y):\n return x\n\n\nclass Child(Base):\n def run(self, x, y):\n return super().run(x, y)\n\n\ndef use(o: Base):\n o.run(1, 2)\n Base.run(o, 1, 2)\n Child().run(y=2, x=1)\n",
|
||||
),
|
||||
("n.py", "from m import Base\n\nBase().run(\n 1,\n 2,\n)\n"),
|
||||
];
|
||||
let mut c = change("m.py", "def run(self, x, y)", "run(", "run", vec![("self", "", 0), ("y", "", 2), ("x", "", 1)]);
|
||||
// rope resolves neither an annotated parameter nor `super()`; the language server does.
|
||||
c.sites = vec![("m.py", "o.run(1, 2)", "run("), ("m.py", "super().run(", "run(")];
|
||||
check(
|
||||
&files,
|
||||
c,
|
||||
&[
|
||||
(
|
||||
"m.py",
|
||||
"class Base:\n def run(self, y, x):\n return x\n\n\nclass Child(Base):\n def run(self, y, x):\n return super().run(y, x)\n\n\ndef use(o: Base):\n o.run(2, 1)\n Base.run(o, 2, 1)\n Child().run(y=2, x=1)\n",
|
||||
),
|
||||
("n.py", "from m import Base\n\nBase().run(\n 2,\n 1,\n)\n"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_to_change_the_self_parameter_of_a_method() {
|
||||
let e = refused(
|
||||
&[("m.py", "class C:\n def m(self, x):\n pass\n")],
|
||||
change("m.py", "def m(", "m(", "m", vec![("x", "", 1), ("self", "", 0)]),
|
||||
);
|
||||
assert!(e.contains("cannot be changed"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn static_and_class_methods_bind_like_their_decorators() {
|
||||
check(
|
||||
&[(
|
||||
"m.py",
|
||||
"class C:\n @staticmethod\n def s(p, q):\n pass\n\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.s(1, 2)\nC().s(1, 2)\nC.c(1, 2)\nC().c(1, 2)\n",
|
||||
)],
|
||||
change("m.py", "def s(", "s(", "s", vec![("q", "", 1), ("p", "", 0)]),
|
||||
&[(
|
||||
"m.py",
|
||||
"class C:\n @staticmethod\n def s(q, p):\n pass\n\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.s(2, 1)\nC().s(2, 1)\nC.c(1, 2)\nC().c(1, 2)\n",
|
||||
)],
|
||||
);
|
||||
check(
|
||||
&[("m.py", "class C:\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.c(1, 2)\nC().c(1, 2)\n")],
|
||||
change("m.py", "def c(", "c(", "c", vec![("cls", "", 0), ("q", "", 2), ("p", "", 1)]),
|
||||
&[("m.py", "class C:\n @classmethod\n def c(cls, q, p):\n pass\n\n\nC.c(2, 1)\nC().c(2, 1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn constructors_are_changed_from_the_class_or_the_init_and_subclasses_through_super() {
|
||||
let files = [
|
||||
(
|
||||
"m.py",
|
||||
"class Base:\n def __init__(self, a, b=1):\n self.a = a\n\n\nclass Child(Base):\n def __init__(self, a, b=1):\n super().__init__(a, b)\n\n\nBase(1, b=2)\nBase(3)\n",
|
||||
),
|
||||
("__init__.py", "from m import Base\n"),
|
||||
("u.py", "from . import Base\n\nBase(5, 6)\n"),
|
||||
];
|
||||
let expect: &[(&str, &str)] = &[
|
||||
(
|
||||
"m.py",
|
||||
"class Base:\n def __init__(self, b=1, a=0):\n self.a = a\n\n\nclass Child(Base):\n def __init__(self, b=1, a=0):\n super().__init__(b, a)\n\n\nBase(b=2, a=1)\nBase(a=3)\n",
|
||||
),
|
||||
("u.py", "from . import Base\n\nBase(6, 5)\n"),
|
||||
];
|
||||
let rows = vec![("self", "", 0), ("b", "1", 2), ("a", "0", 1)];
|
||||
let mut c = change("m.py", "def __init__(self, a, b=1):", "__init__", "__init__", rows);
|
||||
c.sites = vec![("m.py", "super().__init__(a, b)", "__init__(")]; // rope doesn't resolve `super()`
|
||||
check(&files, c, expect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_renaming_init() {
|
||||
let e = refused(
|
||||
&[("m.py", "class C:\n def __init__(self, a):\n pass\n")],
|
||||
change("m.py", "def __init__", "__init__", "make", vec![("self", "", 0), ("a", "", 1)]),
|
||||
);
|
||||
assert!(e.contains("Cannot rename"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn an_override_with_another_parameter_list_is_left_with_a_warning() {
|
||||
let warnings = check(
|
||||
&[(
|
||||
"m.py",
|
||||
"class A:\n def m(self, x, y):\n pass\n\n\nclass B(A):\n def m(self, x, y, z=0):\n pass\n",
|
||||
)],
|
||||
change("m.py", "def m(self, x, y):", "m(", "m", vec![("self", "", 0), ("y", "", 2), ("x", "", 1)]),
|
||||
&[(
|
||||
"m.py",
|
||||
"class A:\n def m(self, y, x):\n pass\n\n\nclass B(A):\n def m(self, x, y, z=0):\n pass\n",
|
||||
)],
|
||||
);
|
||||
assert!(warnings[0].contains("m.py:7") && warnings[0].contains("override"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn calls_with_unpacking_or_comments_are_listed_and_left_alone() {
|
||||
let warnings = check(
|
||||
&[(
|
||||
"m.py",
|
||||
"def f(a, b):\n pass\n\n\nargs = (1, 2)\nf(*args)\nf(1, # first\n 2)\nf(**{'a': 1, 'b': 2})\nf(1, 2)\n",
|
||||
)],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]),
|
||||
&[(
|
||||
"m.py",
|
||||
"def f(b, a):\n pass\n\n\nargs = (1, 2)\nf(*args)\nf(1, # first\n 2)\nf(**{'a': 1, 'b': 2})\nf(2, 1)\n",
|
||||
)],
|
||||
);
|
||||
assert_eq!(warnings.len(), 3, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("unpacking")));
|
||||
assert!(warnings.iter().any(|w| w.contains("comments")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn an_unrecognised_decorator_warns() {
|
||||
let warnings = check(
|
||||
&[("m.py", "import deco\n\n\n@deco.wrap\ndef f(a, b):\n pass\n\n\nf(1, 2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]),
|
||||
&[("m.py", "import deco\n\n\n@deco.wrap\ndef f(b, a):\n pass\n\n\nf(2, 1)\n")],
|
||||
);
|
||||
assert!(warnings[0].contains("@deco.wrap"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn properties_are_refused() {
|
||||
let p = Project::new(&[("m.py", "class C:\n @property\n def p(self):\n return 1\n")]);
|
||||
assert!(p.info("m.py", "def p(", "p(").unwrap_err().contains("property"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn multi_line_parameter_lists_and_calls_keep_one_item_per_line() {
|
||||
check(
|
||||
&[("m.py", "def f(\n a,\n b=2,\n c=3,\n):\n pass\n\n\nf(\n 1,\n 2,\n 3,\n)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "3", 2), ("b", "2", 1)]),
|
||||
&[("m.py", "def f(\n a,\n c=3,\n b=2,\n):\n pass\n\n\nf(\n 1,\n 3,\n 2,\n)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn unsaved_buffers_are_what_rope_reads() {
|
||||
let project = Project::new(&[("m.py", "def f(a, b):\n pass\n"), ("u.py", "from m import f\n\nf(1, 2)\n")]);
|
||||
let mut c = change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]);
|
||||
c.unsaved = vec![("u.py", "from m import f\n\nf(1, 2)\nf(3, 4)\n")];
|
||||
let (changed, _) = project.change(&c).unwrap();
|
||||
assert_eq!(changed["u.py"], "from m import f\n\nf(2, 1)\nf(4, 3)\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(project.root().join("u.py")).unwrap(),
|
||||
"from m import f\n\nf(1, 2)\n",
|
||||
"disk untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn call_sites_from_a_type_aware_server_are_updated_too() {
|
||||
let project = Project::new(&[(
|
||||
"m.py",
|
||||
"class A:\n def m(self, x, y):\n pass\n\n\ndef make():\n return get().m(1, 2)\n",
|
||||
)]);
|
||||
let at = project.at("m.py", "def m(", "m(");
|
||||
let mut request = project.request("change", "m.py", at, &BTreeMap::new());
|
||||
let (line, col) = project.at("m.py", "get().m(", "m(");
|
||||
request["sites"] = json!([{ "path": project.root().join("m.py"), "line": line, "col": col, "len": 1 }]);
|
||||
request["change"] = json!({ "name": "m", "hierarchy": true, "params": [
|
||||
{ "name": "self", "defaultValue": "", "originalIndex": 0, "type": "" },
|
||||
{ "name": "y", "defaultValue": "", "originalIndex": 2, "type": "" },
|
||||
{ "name": "x", "defaultValue": "", "originalIndex": 1, "type": "" },
|
||||
]});
|
||||
let answer = project.run(request);
|
||||
let text = answer["result"]["files"].as_object().unwrap().values().next().unwrap().as_str().unwrap().to_owned();
|
||||
assert!(text.contains("get().m(2, 1)"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn unicode_text_and_crlf_files() {
|
||||
check(
|
||||
&[("m.py", "def f(a, b):\n return 'é😀'\n\n\nf('é', '😀')\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]),
|
||||
&[("m.py", "def f(b, a):\n return 'é😀'\n\n\nf('😀', 'é')\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn syntax_errors_in_other_files_do_not_stop_the_change() {
|
||||
check(
|
||||
&[
|
||||
("m.py", "def f(a, b):\n pass\n"),
|
||||
("broken.py", "def (:\nf(1, 2)\n"),
|
||||
("u.py", "from m import f\nf(1, 2)\n"),
|
||||
],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]),
|
||||
&[("m.py", "def f(b, a):\n pass\n"), ("u.py", "from m import f\nf(2, 1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn refuses_a_function_name_that_the_scope_already_has() {
|
||||
let module = "def f(a):\n pass\n\n\ndef run():\n pass\n";
|
||||
let e = refused(&[("m.py", module)], change("m.py", "def f(", "f(", "run", vec![("a", "", 0)]));
|
||||
assert!(e.contains("already defined"), "{e}");
|
||||
let class = "class C:\n def f(self):\n pass\n\n run = 1\n";
|
||||
let e = refused(&[("m.py", class)], change("m.py", "def f(", "f(", "run", vec![("self", "", 0)]));
|
||||
assert!(e.contains("already defined"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn warns_when_a_new_parameter_name_is_used_in_the_body() {
|
||||
let warnings = check(
|
||||
&[("m.py", "def f(a):\n total = a\n return total\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("total", "", 0)]),
|
||||
&[("m.py", "def f(total):\n total = total\n return total\n")],
|
||||
);
|
||||
assert!(warnings[0].contains("'total' is already used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn async_functions_lambdas_and_nested_functions() {
|
||||
check(
|
||||
&[(
|
||||
"m.py",
|
||||
"async def f(a, b):\n def inner(x, y):\n return x\n\n return inner(a, b)\n\n\nasync def main():\n await f(1, 2)\n g = lambda p, q: p\n return g(1, 2)\n",
|
||||
)],
|
||||
change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]),
|
||||
&[(
|
||||
"m.py",
|
||||
"async def f(b, a):\n def inner(x, y):\n return x\n\n return inner(a, b)\n\n\nasync def main():\n await f(2, 1)\n g = lambda p, q: p\n return g(1, 2)\n",
|
||||
)],
|
||||
);
|
||||
check(
|
||||
&[("m.py", "def outer():\n def inner(x, y):\n return x\n\n return inner(1, 2)\n")],
|
||||
change("m.py", "def inner(", "inner(", "inner", vec![("y", "", 1), ("x", "", 0)]),
|
||||
&[("m.py", "def outer():\n def inner(y, x):\n return x\n\n return inner(2, 1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn unchanged_signatures_change_nothing() {
|
||||
check(
|
||||
&[("m.py", "def f(a, b=2, *args, k=1, **kw):\n pass\n\n\nf(1, 2, 3, k=4, z=5)\n")],
|
||||
change(
|
||||
"m.py",
|
||||
"def f(",
|
||||
"f(",
|
||||
"f",
|
||||
vec![("a", "", 0), ("b", "2", 1), ("*args", "", 2), ("k", "1", 3), ("**kw", "", 4)],
|
||||
),
|
||||
&[],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn a_function_defined_in_a_file_with_a_syntax_error_is_refused_with_the_reason() {
|
||||
let e = refused(&[("m.py", "def f(a:\n pass\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0)]));
|
||||
assert!(!e.is_empty());
|
||||
}
|
||||
|
||||
const AB: &str = "def f(a, b):\n return a\n\n\n";
|
||||
|
||||
fn swap() -> Vec<Row> {
|
||||
vec![("b", "", 1), ("a", "", 0)]
|
||||
}
|
||||
|
||||
/// `AB` plus `calls` becomes the new header plus `after`.
|
||||
#[track_caller]
|
||||
fn check_calls(calls: &str, rows: Vec<Row>, header: &str, after: &str) -> Vec<String> {
|
||||
let before = format!("{AB}{calls}\n");
|
||||
let want = format!("def f({header}):\n return a\n\n\n{after}\n");
|
||||
check(&[("m.py", &before)], change("m.py", "def f(", "f(", "f", rows), &[("m.py", &want)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn nested_calls_are_rewritten_inside_out() {
|
||||
check_calls("f(f(1, 2), 3)", swap(), "b, a", "f(3, f(2, 1))");
|
||||
check_calls("f(f(1, 22), 3)", vec![("a", "", 0)], "a", "f(f(1))");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn parentheses_around_arguments_and_defaults_stay_with_them() {
|
||||
check_calls("f((x), (y))", swap(), "b, a", "f((y), (x))");
|
||||
check_calls("f((p + q), c)", swap(), "b, a", "f(c, (p + q))");
|
||||
check(
|
||||
&[("m.py", "def f(a, b=(1+2)):\n pass\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "(1+2)", 1), ("c", "3", -1)]),
|
||||
&[("m.py", "def f(a, b=(1+2), c=3):\n pass\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn removing_every_argument_removes_the_trailing_comma() {
|
||||
check_calls("f(1, 2,)", vec![], "", "f()");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn references_of_something_else_are_not_rewritten() {
|
||||
// the caret on `fn`: a server reports the references of the parameter, not of `apply`
|
||||
let mut c = change("m.py", "def apply(fn", "fn", "apply", vec![("x", "", 1), ("fn", "", 0)]);
|
||||
c.sites = vec![("m.py", "return fn(x)", "fn")];
|
||||
check(
|
||||
&[("m.py", "def apply(fn, x):\n return fn(x)\n\n\napply(print, 1)\n")],
|
||||
c,
|
||||
&[("m.py", "def apply(x, fn):\n return fn(x)\n\n\napply(1, print)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn renaming_the_function_renames_the_calls_only_a_server_finds() {
|
||||
let text = "class B:\n def run(self):\n pass\n\n\nclass C(B):\n def go(self):\n super().run()\n\n\ndef g(o: B):\n o.run()\n";
|
||||
let mut c = change("m.py", "def run", "run", "walk", vec![("self", "", 0)]);
|
||||
c.sites = vec![("m.py", "super().run()", "run"), ("m.py", " o.run()", "run")];
|
||||
check(&[("m.py", text)], c, &[("m.py", &text.replace("run", "walk"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn overrides_keep_their_defaults_and_follow_parameter_renames() {
|
||||
let text = "class B:\n def m(self, a, b=1):\n return a\n\n\nclass C(B):\n def m(self, a, b=2):\n return a\n\n\nC().m(a=0)\n";
|
||||
check(
|
||||
&[("m.py", text)],
|
||||
change("m.py", "def m(self, a, b=1", "m", "m", vec![("self", "", 0), ("y", "", 1), ("b", "1", 2)]),
|
||||
&[("m.py", &text.replace("a, b=", "y, b=").replace("return a", "return y").replace("a=0", "y=0"))],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn star_parameters_are_renamed_by_their_names() {
|
||||
check(
|
||||
&[("m.py", "def f(*args, **kw):\n return args, kw\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("*xs", "", 0), ("**opts", "", 1)]),
|
||||
&[("m.py", "def f(*xs, **opts):\n return xs, opts\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn a_changed_parameter_kind_never_loses_arguments_silently() {
|
||||
let warnings = check(
|
||||
&[("m.py", "def f(*args):\n pass\n\n\nf(1, 2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("args", "", 0)]),
|
||||
&[("m.py", "def f(args):\n pass\n\n\nf(1, 2)\n")],
|
||||
);
|
||||
assert!(warnings[0].contains("after its kind changes"), "{warnings:?}");
|
||||
let warnings = check_calls("f(1, 2)", vec![("a", "", 0), ("*b", "", 1)], "a, *b", "f(1, 2)");
|
||||
assert!(warnings[0].contains("after its kind changes"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn rows_that_would_not_parse_are_refused_or_cleaned() {
|
||||
let files = [("m.py", "def f(a, b=1):\n pass\n")];
|
||||
let at = |rows| change("m.py", "def f(", "f(", "f", rows);
|
||||
for default in ["1, 3", "1 # x", "x=1", "*y"] {
|
||||
let why = refused(&files, at(vec![("a", "", 0), ("b", default, 1)]));
|
||||
assert!(why.contains("not a valid expression"), "{default}: {why}");
|
||||
}
|
||||
let why = refused(&files, at(vec![("a", "", 0), ("*", "", -1), ("/", "", -1), ("b", "1", 1)]));
|
||||
assert!(why.contains("'/' must come before '*'"), "{why}");
|
||||
// the dialog hides the default of a star row, so the old one is dropped
|
||||
check(&files, at(vec![("a", "", 0), ("*b", "1", 1)]), &[("m.py", "def f(a, *b):\n pass\n")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn keyword_only_parameters_without_positional_ones_can_change() {
|
||||
check(
|
||||
&[("m.py", "def f(*, a, b):\n pass\n\n\nf(a=1, b=2)\n")],
|
||||
change("m.py", "def f(", "f(", "f", vec![("*", "", 0), ("b", "", 2), ("a", "", 1)]),
|
||||
&[("m.py", "def f(*, b, a):\n pass\n\n\nf(b=2, a=1)\n")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs rope"]
|
||||
fn calls_through_type_self_and_stored_methods_are_not_misaligned() {
|
||||
let text = "class C:\n def run(self, a, b):\n pass\n\n def go(self):\n type(self).run(self, 1, 2)\n\n\nm = C().run\nm(1, 2)\n";
|
||||
let mut c = change("m.py", "def run", "run", "run", vec![("self", "", 0), ("b", "", 2), ("a", "", 1)]);
|
||||
c.sites = vec![("m.py", "type(self).run(", "run("), ("m.py", "m(1, 2)", "m(")];
|
||||
let warnings = check(
|
||||
&[("m.py", text)],
|
||||
c,
|
||||
&[("m.py", &text.replace("self, a, b", "self, b, a").replace("self, 1, 2", "self, 2, 1"))],
|
||||
);
|
||||
assert!(warnings.iter().any(|w| w.contains("used as a value")), "{warnings:?}");
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Python Change Signature through the commands the app calls: the dialog's signature, the
|
||||
//! edit it computes from the open (unsaved) buffers, applying it and undoing it. `#[ignore]`d:
|
||||
//! it needs `pylsp` with rope on `PATH` (`pip install python-lsp-server pylsp-rope`).
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, IdeEvent, Pos, RequestId, SharedSink, TextChange, error::ErrorKind};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::SignatureParameter;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn row(name: &str, default: &str, index: i32) -> SignatureParameter {
|
||||
SignatureParameter {
|
||||
type_name: String::new(),
|
||||
name: name.into(),
|
||||
default_value: default.into(),
|
||||
original_index: index,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp with rope on PATH"]
|
||||
async fn changes_a_signature_from_unsaved_buffers_then_undoes_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("app");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
|
||||
std::fs::write(root.join("lib.py"), "def f(a, b=2):\n return a\n").unwrap();
|
||||
std::fs::write(root.join("use.py"), "from lib import f\n\nf(1, 2)\n").unwrap();
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
};
|
||||
let host =
|
||||
Host::new(HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&root.join(".app")) });
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let lib = ops::doc::doc_open(&host, "main", root.join("lib.py")).await.unwrap();
|
||||
let usage = ops::doc::doc_open(&host, "main", root.join("use.py")).await.unwrap();
|
||||
// An unsaved call that exists only in the editor.
|
||||
let append = ChangeSet { changes: vec![TextChange { from: 27, to: 27, insert: "f(3, 4)\n".into() }] };
|
||||
ops::doc::doc_edit(&host, "main", usage.id, usage.version, append).await.unwrap();
|
||||
|
||||
let caret = Pos::new(0, 5);
|
||||
let info = ops::lsp::lsp_signature_info(&host, "main", RequestId(1), lib.id, caret).await.unwrap();
|
||||
let names: Vec<_> = info.parameters.iter().map(|p| (p.name.as_str(), p.default_value.as_str())).collect();
|
||||
assert_eq!((info.method_name.as_str(), names), ("f", vec![("a", ""), ("b", "2")]));
|
||||
|
||||
let mut changed = info.clone();
|
||||
changed.parameters = vec![row("b", "2", 1), row("a", "", 0)];
|
||||
let swapped =
|
||||
ops::lsp::lsp_change_signature(&host, "main", RequestId(2), lib.id, caret, changed.clone(), false, None).await;
|
||||
assert!(swapped.is_err(), "a default before a parameter without one is refused");
|
||||
changed.parameters = vec![row("a", "", 0), row("b", "2", 1), row("c", "None", -1)];
|
||||
changed.method_name = "g".into();
|
||||
let answer =
|
||||
ops::lsp::lsp_change_signature(&host, "main", RequestId(3), lib.id, caret, changed, false, None).await.unwrap();
|
||||
let edit = answer.edit.expect("an edit");
|
||||
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
assert_eq!(
|
||||
ops::doc::doc_snapshot(&host, "main", lib.id).await.unwrap().text,
|
||||
"def g(a, b=2, c=None):\n return a\n"
|
||||
);
|
||||
assert_eq!(
|
||||
ops::doc::doc_snapshot(&host, "main", usage.id).await.unwrap().text,
|
||||
"from lib import g\n\ng(1, 2)\ng(3, 4)\n"
|
||||
);
|
||||
|
||||
let id = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap();
|
||||
assert_eq!(ops::doc::doc_snapshot(&host, "main", lib.id).await.unwrap().text, "def f(a, b=2):\n return a\n");
|
||||
assert_eq!(
|
||||
ops::doc::doc_snapshot(&host, "main", usage.id).await.unwrap().text,
|
||||
"from lib import f\n\nf(1, 2)\nf(3, 4)\n"
|
||||
);
|
||||
|
||||
// A refusal comes back as an invalid-input error with rope's reason.
|
||||
let mut bad = info;
|
||||
bad.parameters = vec![row("b", "2", 1), row("a", "", 0), row("a", "", -1)];
|
||||
let error =
|
||||
ops::lsp::lsp_change_signature(&host, "main", RequestId(4), lib.id, caret, bad, false, None).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert!(error.message.contains("Duplicate"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "needs pylsp with rope on PATH"]
|
||||
async fn a_closed_file_with_a_byte_order_mark_keeps_its_first_character() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("app");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("lib.py"), "def f(a, b):\n return a\n").unwrap();
|
||||
std::fs::write(root.join("use.py"), "\u{feff}from lib import f\n\nf(1, 2)\n").unwrap();
|
||||
let host =
|
||||
Host::new(HostConfig { sink_for: Box::new(|_| Arc::new(|_| {})), ..common::host_config(&root.join(".app")) });
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let lib = ops::doc::doc_open(&host, "main", root.join("lib.py")).await.unwrap();
|
||||
let caret = Pos::new(0, 4);
|
||||
let mut changed = ops::lsp::lsp_signature_info(&host, "main", RequestId(1), lib.id, caret).await.unwrap();
|
||||
changed.parameters = vec![row("b", "", 1), row("a", "", 0)];
|
||||
let answer =
|
||||
ops::lsp::lsp_change_signature(&host, "main", RequestId(2), lib.id, caret, changed, false, None).await.unwrap();
|
||||
ops::lsp::apply_workspace_edit(&host, "main", answer.edit.expect("an edit")).await.unwrap();
|
||||
let usage = ops::doc::doc_open(&host, "main", root.join("use.py")).await.unwrap();
|
||||
assert_eq!(usage.text, "from lib import f\n\nf(2, 1)\n");
|
||||
let bytes = std::fs::read(root.join("use.py")).unwrap();
|
||||
assert!(bytes.starts_with("\u{feff}from lib".as_bytes()), "{bytes:?}");
|
||||
}
|
||||
@@ -199,6 +199,54 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_replacement_with_an_unknown_group_changes_no_file() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let names = ["a.txt", "b.txt"];
|
||||
for all_in_scope in [false, true] {
|
||||
for name in names {
|
||||
std::fs::write(root.join(name), "foo.old();\n").unwrap();
|
||||
}
|
||||
let err = ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query(r"(\w+)\.old", true),
|
||||
"$name".into(),
|
||||
false,
|
||||
names.map(|n| ReplaceTarget { path: root.join(n).into(), only: None, skip: None }).into(),
|
||||
all_in_scope,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.message, "Invalid replacement: the pattern has no group name");
|
||||
for name in names {
|
||||
assert_eq!(std::fs::read_to_string(root.join(name)).unwrap(), "foo.old();\n");
|
||||
}
|
||||
}
|
||||
let preview = ops::search::replace_preview(
|
||||
&host,
|
||||
"main",
|
||||
query(r"(\w+)\.old", true),
|
||||
"$2".into(),
|
||||
false,
|
||||
root.join("a.txt"),
|
||||
None,
|
||||
);
|
||||
assert_eq!(preview.await.unwrap_err().message, "Invalid replacement: the pattern has no group 2");
|
||||
assert!(ops::search::search_validate(query("a", true), Some("$1".into())).is_err());
|
||||
assert!(ops::search::search_validate(query("(a)", true), Some("$1_x".into())).is_ok());
|
||||
assert!(ops::search::search_validate(query("a", true), None).is_ok());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// Replace All past the limit replaces what the search lists: only the matches its Search
|
||||
/// Context keeps (comments, string literals or code), as below the limit.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Severity quick fixes writing `.editorconfig` (#7646), against the real `dotnet` and the Roslyn
|
||||
//! language server installed as Settings does. It downloads the server, so it runs only on request:
|
||||
//! `cargo test -p ide-host --test roslyn_editorconfig -- --ignored`; skipped without a .NET SDK.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{DocId, IdeEvent, Pos, Range, RequestId, Severity};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::CodeAction;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
const PROGRAM: &str =
|
||||
"var c = new C();\nc.M();\n\nclass C\n{\n public string Name { get; set; } public void M() { }\n}\n";
|
||||
/// `Name` on line 5, and the whole line, which CA1822 (on `M`) shares.
|
||||
const NAME: Range = Range { start: Pos { line: 5, col: 18 }, end: Pos { line: 5, col: 22 } };
|
||||
const LINE: Range = Range { start: Pos { line: 5, col: 0 }, end: Pos { line: 5, col: 56 } };
|
||||
|
||||
fn has_dotnet() -> bool {
|
||||
Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// Installs the server as Settings does and puts it on `PATH` as the app does at startup. This
|
||||
/// binary has one test, so nothing else reads the environment meanwhile.
|
||||
fn install_roslyn() -> tempfile::TempDir {
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let languages: Vec<_> = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
ide_tools::Tools::new(data.path())
|
||||
.install("roslyn-language-server", &languages, &Default::default(), &|_| {})
|
||||
.unwrap();
|
||||
ide_tools::extend_process_path(data.path());
|
||||
data
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
host: Arc<Host>,
|
||||
events: Arc<Mutex<Vec<IdeEvent>>>,
|
||||
doc: DocId,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// A console project below `app`, with a solution there or on its own.
|
||||
async fn new(solution: bool) -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app");
|
||||
if solution {
|
||||
write(&root.join("App.slnx"), "<Solution><Project Path=\"App/App.csproj\" /></Solution>\n");
|
||||
}
|
||||
write(
|
||||
&root.join("App/App.csproj"),
|
||||
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><OutputType>Exe</OutputType>\
|
||||
<TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable>\
|
||||
<AnalysisMode>All</AnalysisMode></PropertyGroup></Project>\n",
|
||||
);
|
||||
write(&root.join("App/Program.cs"), PROGRAM);
|
||||
let restore = Command::new("dotnet").args(["restore", "App/App.csproj"]).current_dir(&root).output().unwrap();
|
||||
assert!(restore.status.success(), "{}", String::from_utf8_lossy(&restore.stdout));
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let seen = events.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let seen = seen.clone();
|
||||
Arc::new(move |event: IdeEvent| seen.lock().unwrap().push(event))
|
||||
}),
|
||||
..common::host_config(&base.join("host"))
|
||||
}));
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.open_project(WINDOW, &root).unwrap();
|
||||
let doc = ops::doc::doc_open(&host, WINDOW, root.join("App/Program.cs")).await.unwrap().id;
|
||||
Self { _tmp: tmp, root, host, events, doc }
|
||||
}
|
||||
|
||||
/// Waits until the latest diagnostics give `code` the severity `want` (`None`: not reported).
|
||||
async fn severity(&self, code: &str, want: Option<Severity>) {
|
||||
let path = self.root.join("App/Program.cs");
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let mut latest = std::collections::HashMap::new();
|
||||
for event in self.events.lock().unwrap().iter() {
|
||||
if let IdeEvent::Diagnostics { path: p, source, items } = event
|
||||
&& **p == *path
|
||||
{
|
||||
latest.insert(source.clone(), items.clone());
|
||||
}
|
||||
}
|
||||
let found = latest.values().flatten().find(|d| d.code.as_deref() == Some(code)).map(|d| d.severity);
|
||||
if !latest.is_empty() && found == want {
|
||||
return;
|
||||
}
|
||||
assert!(start.elapsed() < Duration::from_secs(180), "{code}: {found:?}, not {want:?}; {latest:?}");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries of "Suppress or configure issues" over `range`, as the UI builds their actions.
|
||||
async fn entries(&self, range: Range) -> Vec<(String, CodeAction)> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let actions = ops::lsp::lsp_code_actions(&self.host, WINDOW, self.doc, range, vec![]).await;
|
||||
let parent = actions.as_ref().ok().and_then(|a| a.iter().find(|a| a.title.starts_with("Suppress or")));
|
||||
if let Some(parent) = parent {
|
||||
let command = parent.command.as_ref().unwrap();
|
||||
assert_eq!(command.command, "roslyn.client.nestedCodeAction");
|
||||
return command.arguments[0]["NestedCodeActions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let path: Vec<&str> = entry["data"]["CodeActionPath"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|p| p.as_str())
|
||||
.collect();
|
||||
let action = CodeAction {
|
||||
title: entry["title"].as_str().unwrap().into(),
|
||||
data: Some(entry["data"].clone()),
|
||||
command: None,
|
||||
..parent.clone()
|
||||
};
|
||||
(path[1..].join(" > "), action)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
assert!(start.elapsed() < Duration::from_secs(180), "no severity actions: {actions:?}");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve(&self, entry: &str) -> ide_core::IdeResult<CodeAction> {
|
||||
let entries = self.entries(NAME).await;
|
||||
let (_, action) = entries.into_iter().find(|(path, _)| path == entry).expect(entry);
|
||||
ops::lsp::lsp_resolve_code_action(&self.host, WINDOW, self.doc, action).await
|
||||
}
|
||||
|
||||
async fn apply(&self, entry: &str) -> ide_core::IdeResult<()> {
|
||||
let action = self.resolve(entry).await?;
|
||||
ops::lsp::lsp_execute_code_action(&self.host, WINDOW, RequestId(1), self.doc, action, vec![]).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies `entry` once the server has read the current `.editorconfig`, whose text becomes
|
||||
/// one holding every line of `expect`.
|
||||
async fn rewrites(&self, file: &str, entry: &str, expect: &[&str]) {
|
||||
let path = self.root.join(file);
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let before = std::fs::read_to_string(&path).unwrap();
|
||||
let edit = self.resolve(entry).await.ok().and_then(|a| a.edit);
|
||||
let after = edit.and_then(|edit| {
|
||||
edit.files.iter().find_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path: p, edits, .. } if **p == *path => {
|
||||
let mut doc = ide_text::Document::new(&before);
|
||||
doc.apply_edits(edits).ok()?;
|
||||
Some(doc.text())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(after) = &after
|
||||
&& expect.iter().all(|line| after.lines().filter(|l| l.trim() == *line).count() == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
assert!(start.elapsed() < Duration::from_secs(60), "{file}: {after:?} from {before:?}");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "installs roslyn-language-server and needs the .NET SDK"]
|
||||
async fn severity_quick_fixes_write_editorconfig() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let _tools = install_roslyn();
|
||||
let f = Fixture::new(true).await;
|
||||
let config = f.root.join(".editorconfig");
|
||||
let read = || std::fs::read_to_string(&config).unwrap();
|
||||
const KEY: &str = "dotnet_diagnostic.CS8618.severity";
|
||||
f.severity("CS8618", Some(Severity::Warning)).await;
|
||||
|
||||
// Two diagnostics on one line each have their own severities.
|
||||
let paths: Vec<String> = f.entries(LINE).await.into_iter().map(|(path, _)| path).collect();
|
||||
for id in ["CS8618", "CA1822"] {
|
||||
assert!(paths.contains(&format!("Configure {id} severity > Silent")), "{paths:?}");
|
||||
}
|
||||
|
||||
// No `.editorconfig`: the server creates one beside the solution, applied without a restart.
|
||||
f.apply("Configure CS8618 severity > Error").await.unwrap();
|
||||
assert!(read().contains("[*.cs]") && read().contains(&format!("{KEY} = error")), "{}", read());
|
||||
f.severity("CS8618", Some(Severity::Error)).await;
|
||||
|
||||
// The edit is undoable.
|
||||
let id = f.events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
});
|
||||
ops::lsp::undo_workspace_edit(&f.host, WINDOW, id.unwrap()).await.unwrap();
|
||||
assert!(!config.exists());
|
||||
f.severity("CS8618", Some(Severity::Warning)).await;
|
||||
ops::lsp::redo_workspace_edit(&f.host, WINDOW, id.unwrap()).await.unwrap();
|
||||
f.severity("CS8618", Some(Severity::Error)).await;
|
||||
|
||||
// An existing key is replaced, not repeated.
|
||||
f.apply("Configure CS8618 severity > None").await.unwrap();
|
||||
assert_eq!(read().matches(KEY).count(), 1, "{}", read());
|
||||
assert!(read().contains(&format!("{KEY} = none")), "{}", read());
|
||||
f.severity("CS8618", None).await;
|
||||
write(&config, &format!("root = true\n[*.cs]\n{KEY} = warning\n"));
|
||||
f.severity("CS8618", Some(Severity::Warning)).await;
|
||||
|
||||
// The server's edits of other existing files.
|
||||
let line = format!("{KEY} = silent");
|
||||
for (text, section) in [
|
||||
("root = true\n", "[*.cs]"),
|
||||
("root = true\n\n[*.md]\nindent_size = 2\n", "[*.cs]"),
|
||||
("root = true\n\n[*.{cs,vb}]\nindent_size = 4\n", "[*.{cs,vb}]"),
|
||||
] {
|
||||
write(&config, text);
|
||||
f.rewrites(".editorconfig", "Configure CS8618 severity > Silent", &[section, &line]).await;
|
||||
}
|
||||
|
||||
// A read-only file is left alone, with an error.
|
||||
let mut permissions = std::fs::metadata(&config).unwrap().permissions();
|
||||
permissions.set_readonly(true);
|
||||
std::fs::set_permissions(&config, permissions.clone()).unwrap();
|
||||
let before = read();
|
||||
let result = f.apply("Configure CS8618 severity > Error").await;
|
||||
assert!(result.is_err(), "{}", read());
|
||||
assert_eq!(read(), before);
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
permissions.set_readonly(false);
|
||||
std::fs::set_permissions(&config, permissions).unwrap();
|
||||
|
||||
// A nearer `.editorconfig` with `root = true` is the one edited.
|
||||
write(&f.root.join("App/.editorconfig"), "root = true\n\n[*.cs]\nindent_size = 4\n");
|
||||
f.rewrites("App/.editorconfig", "Configure CS8618 severity > Silent", &["[*.cs]", &line]).await;
|
||||
f.host.shutdown().await;
|
||||
|
||||
// Without a solution it creates one beside the project.
|
||||
let f = Fixture::new(false).await;
|
||||
f.severity("CS8618", Some(Severity::Warning)).await;
|
||||
f.apply("Configure CS8618 severity > Error").await.unwrap();
|
||||
let created = std::fs::read_to_string(f.root.join("App/.editorconfig")).unwrap();
|
||||
assert!(created.contains(&format!("{KEY} = error")), "{created}");
|
||||
f.severity("CS8618", Some(Severity::Error)).await;
|
||||
f.host.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! C# inlay hints and parameter info (#7678) with the bundled settings, against the real `dotnet`,
|
||||
//! csharp-ls and the Roslyn language server, installed as Settings does (network). Ignored by
|
||||
//! default: `cargo test -p ide-host --test roslyn_hints -- --ignored`; skipped without a .NET SDK.
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{DocId, Pos, Range};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::{InlayHint, InlayKind, SignatureHelp};
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
|
||||
/// Complete code: what the hints are asked for.
|
||||
const HINTS: &str = r#"using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public record Point(int X, int Y);
|
||||
public static class Ext { public static string Repeat(this string s, int count) => s; }
|
||||
public class Grid { public int this[int row, int column] => row; }
|
||||
|
||||
public class Demo
|
||||
{
|
||||
static int Add(int first, int second) => first + second;
|
||||
static void Log(string format, params object[] args) { }
|
||||
static void Opt(int width, int height = 2, bool visible = true) { }
|
||||
static T Echo<T>(T value) => value;
|
||||
static void Take(Point point) { }
|
||||
static void Enable(bool value) { }
|
||||
static void SetColor(string color) { }
|
||||
static void Pair(int item1, int item2) { }
|
||||
static void Name(string name) { }
|
||||
|
||||
public void Run(string name, int total)
|
||||
{
|
||||
var sum = Add(1, 2);
|
||||
var point = new Point(3, 4);
|
||||
Take(new Point(5, 6));
|
||||
Take(new(5, 6));
|
||||
Opt(width: 1, visible: false);
|
||||
Opt(
|
||||
1,
|
||||
height: 3);
|
||||
Log("a {0}", 1, 2);
|
||||
var r = "x".Repeat(3);
|
||||
var g = Echo<int>(7);
|
||||
var cell = new Grid()[1, 2];
|
||||
var xs = new List<int> { 1 }.Select(n => n + 1);
|
||||
Add(Add(1, total), 3);
|
||||
var text = $"v={Add(total, 2)}";
|
||||
var 名前 = "日本語😀"; Add(名前.Length, 2);
|
||||
Point q = new(1, 2);
|
||||
Enable(true);
|
||||
SetColor("red");
|
||||
Pair(1, 2);
|
||||
Name("x");
|
||||
Name(name);
|
||||
Func<int, int, int> f = (a, b) => a + b;
|
||||
List<int> empty = [];
|
||||
foreach (var item in xs) { }
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// `HINTS` from `Run` on, with Roslyn's hints written in: `‹name:›` before an argument, `«type»`
|
||||
/// before a name.
|
||||
const ROSLYN: &str = r#" public void Run(string name, int total)
|
||||
{
|
||||
var «int»sum = Add(‹first:›1, ‹second:›2);
|
||||
var «Point?»point = new Point(‹X:›3, ‹Y:›4);
|
||||
Take(‹point:›new Point(‹X:›5, ‹Y:›6));
|
||||
Take(new(‹X:›5, ‹Y:›6));
|
||||
Opt(width: 1, visible: false);
|
||||
Opt(
|
||||
‹width:›1,
|
||||
height: 3);
|
||||
Log(‹format:›"a {0}", ‹args:›1, 2);
|
||||
var «string?»r = "x".Repeat(‹count:›3);
|
||||
var «int»g = Echo<int>(‹value:›7);
|
||||
var «int»cell = new Grid()[‹row:›1, ‹column:›2];
|
||||
var «IEnumerable<int>?»xs = new List<int> { 1 }.Select(«int»n => n + 1);
|
||||
Add(Add(‹first:›1, total), ‹second:›3);
|
||||
var «string?»text = $"v={Add(total, ‹second:›2)}";
|
||||
var «string?»名前 = "日本語😀"; Add(名前.Length, ‹second:›2);
|
||||
Point q = new(‹X:›1, ‹Y:›2);
|
||||
Enable(‹value:›true);
|
||||
SetColor("red");
|
||||
Pair(1, 2);
|
||||
Name(‹name:›"x");
|
||||
Name(name);
|
||||
Func<int, int, int> f = («int»a, «int»b) => a + b;
|
||||
List<int> empty = [];
|
||||
foreach (var «int»item in xs) { }
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Code being typed: where parameter info is asked for.
|
||||
const CALLS: &str = r#"public record Point(int X, int Y);
|
||||
public static class Ext { public static string Repeat(this string s, int count) => s; }
|
||||
public class Grid { public int this[int row, int column] => row; }
|
||||
|
||||
public class Calls
|
||||
{
|
||||
static int Add(int first, int second) => first + second;
|
||||
static int Add(int first, int second, int third) => first;
|
||||
static void Take(int a, int n) { }
|
||||
static void Log(string format, params object[] args) { }
|
||||
static void Opt(int width, int height = 2, bool visible = true) { }
|
||||
static T Echo<T>(T value) => value;
|
||||
static void Origin(Point point) { }
|
||||
static void Map(System.Func<int, int> map, int e) { }
|
||||
|
||||
public void Run(int total)
|
||||
{
|
||||
Add(1, );
|
||||
Add(1, 2, );
|
||||
Take(1, );
|
||||
Add(Add(1, total), 3);
|
||||
Add($"{Add(1, 2)},)".Length, 4);
|
||||
Add(
|
||||
total,
|
||||
);
|
||||
var 名前 = "日本語😀"; Add(名前.Length, 5);
|
||||
Log("f", 6, 7);
|
||||
Opt(visible: true, width: 8);
|
||||
"x".Repeat(9);
|
||||
Echo<int>(10);
|
||||
new Point(11, 12);
|
||||
Origin(new(13, 14));
|
||||
new Grid()[15, 16].ToString();
|
||||
Map(x => x, 17);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
fn has_dotnet() -> bool {
|
||||
Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
/// Installs a server as Settings does and puts it on `PATH` as the app does at startup. This
|
||||
/// binary has one test, so nothing else reads the environment meanwhile.
|
||||
fn install(data: &Path, server: &str) {
|
||||
let languages = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
ide_tools::Tools::new(data).install(server, &languages, &Default::default(), &|_| {}).unwrap();
|
||||
ide_tools::extend_process_path(data);
|
||||
}
|
||||
|
||||
/// A host with the project in `root` open.
|
||||
async fn open(root: &Path, base: &Path) -> Arc<Host> {
|
||||
let host = Arc::new(Host::new(HostConfig { ..common::host_config(base) }));
|
||||
host.set_project_trust(root, true, false).await.unwrap();
|
||||
host.open_project(WINDOW, root).unwrap();
|
||||
host
|
||||
}
|
||||
|
||||
async fn document(host: &Arc<Host>, root: &Path, file: &str) -> DocId {
|
||||
ops::doc::doc_open(host, WINDOW, root.join(file)).await.unwrap().id
|
||||
}
|
||||
|
||||
/// Asks for the hints of the whole file until `done`, while the server loads the project.
|
||||
async fn hints(host: &Host, doc: DocId, done: impl Fn(&[InlayHint]) -> bool) -> Vec<InlayHint> {
|
||||
let range = Range::new(Pos::new(0, 0), Pos::new(HINTS.lines().count() as u32, 0));
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let found = ops::lsp::lsp_inlay_hints(host, WINDOW, doc, range).await;
|
||||
if let Ok(found) = &found
|
||||
&& done(found)
|
||||
{
|
||||
return found.clone();
|
||||
}
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_secs(180),
|
||||
"{found:#?}\n{}",
|
||||
render(found.as_deref().unwrap_or_default())
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset of UTF-16 column `col`.
|
||||
fn byte(line: &str, col: u32) -> usize {
|
||||
let mut units = 0;
|
||||
line.char_indices()
|
||||
.find(|(_, c)| {
|
||||
let here = units;
|
||||
units += c.len_utf16() as u32;
|
||||
here >= col
|
||||
})
|
||||
.map_or(line.len(), |(i, _)| i)
|
||||
}
|
||||
|
||||
/// `HINTS` from `Run` on, with `hints` written in.
|
||||
fn render(hints: &[InlayHint]) -> String {
|
||||
let first = HINTS.lines().position(|l| l.contains("void Run")).unwrap();
|
||||
let mut out = String::new();
|
||||
for (number, line) in HINTS.lines().enumerate().skip(first) {
|
||||
let mut line_hints: Vec<_> = hints.iter().filter(|h| h.position.line == number as u32).collect();
|
||||
line_hints.sort_by_key(|h| h.position.col);
|
||||
let mut end = 0;
|
||||
for hint in line_hints {
|
||||
let at = byte(line, hint.position.col);
|
||||
out.push_str(&line[end..at]);
|
||||
end = at;
|
||||
let (open, close) = if matches!(hint.kind, InlayKind::Type) { ('«', '»') } else { ('‹', '›') };
|
||||
out.push(open);
|
||||
out.push_str(hint.label.trim());
|
||||
out.push(close);
|
||||
}
|
||||
out.push_str(&line[end..]);
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parameter info with the caret at the `|` of `marked`, a piece of one line of `CALLS`:
|
||||
/// the number of overloads, the marked one's label and the parameter it bolds.
|
||||
async fn parameter_info(host: &Host, doc: DocId, marked: &str) -> Option<(usize, String, u32, String)> {
|
||||
let (before, after) = marked.split_once('|').unwrap();
|
||||
let needle = format!("{before}{after}");
|
||||
let (number, line) = CALLS.lines().enumerate().find(|(_, l)| l.contains(&needle)).expect(marked);
|
||||
let col = line[..line.find(&needle).unwrap() + before.len()].encode_utf16().count();
|
||||
let help: Option<SignatureHelp> =
|
||||
ops::lsp::lsp_signature_help(host, WINDOW, doc, Pos::new(number as u32, col as u32)).await.unwrap();
|
||||
help.map(|help| {
|
||||
let signature = &help.signatures[help.active_signature as usize];
|
||||
let units: Vec<u16> = signature.label.encode_utf16().collect();
|
||||
let bold = signature
|
||||
.parameters
|
||||
.get(help.active_parameter as usize)
|
||||
.map_or_else(String::new, |&(a, b)| String::from_utf16(&units[a as usize..b as usize]).unwrap());
|
||||
(help.signatures.len(), signature.label.clone(), help.active_parameter, bold)
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "installs csharp-ls and roslyn-language-server and needs the .NET SDK"]
|
||||
async fn csharp_inlay_hints_and_parameter_info() {
|
||||
if !has_dotnet() {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(
|
||||
root.join("App.csproj"),
|
||||
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><TargetFramework>net10.0</TargetFramework>\
|
||||
<Nullable>enable</Nullable></PropertyGroup></Project>\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("Hints.cs"), HINTS).unwrap();
|
||||
let restore = Command::new("dotnet").arg("restore").current_dir(&root).output().unwrap();
|
||||
assert!(restore.status.success(), "{}", String::from_utf8_lossy(&restore.stdout));
|
||||
let tools = base.join("tools");
|
||||
let has = |hints: &[InlayHint], line: &str, label: &str| {
|
||||
let number = HINTS.lines().position(|l| l.trim() == line).expect(line) as u32;
|
||||
hints.iter().any(|h| h.position.line == number && h.label.trim() == label)
|
||||
};
|
||||
|
||||
// csharp-ls, the fallback without Roslyn: its own hints, which the C# settings don't touch.
|
||||
install(&tools, "csharp-ls");
|
||||
let host = open(&root, &base.join("fallback")).await;
|
||||
let doc = document(&host, &root, "Hints.cs").await;
|
||||
hints(&host, doc, |h| has(h, "var sum = Add(1, 2);", "first:") && has(h, "var sum = Add(1, 2);", ": int")).await;
|
||||
host.shutdown().await;
|
||||
|
||||
install(&tools, "roslyn-language-server");
|
||||
let host = open(&root, &base.join("roslyn")).await;
|
||||
let doc = document(&host, &root, "Hints.cs").await;
|
||||
let found = hints(&host, doc, |h| render(h) == ROSLYN).await;
|
||||
assert!(found.iter().all(|h| !matches!(h.kind, InlayKind::Other)), "Editor › Inlay Hints switches them by kind");
|
||||
|
||||
// The server's own settings (Settings › Language Servers) win, without a restart.
|
||||
let set = |value: &str| {
|
||||
ops::project::settings_set(
|
||||
&host,
|
||||
WINDOW,
|
||||
SettingsScope::Global,
|
||||
"languageServers.roslyn-language-server.settings".into(),
|
||||
value.into(),
|
||||
)
|
||||
.unwrap();
|
||||
};
|
||||
set(r#"{"csharp|inlay_hints":{"dotnet_enable_inlay_hints_for_parameters":false}}"#);
|
||||
hints(&host, doc, |h| !h.is_empty() && h.iter().all(|h| matches!(h.kind, InlayKind::Type))).await;
|
||||
set(r#"{"csharp|inlay_hints":{"csharp_enable_inlay_hints_for_types":false}}"#);
|
||||
hints(&host, doc, |h| !h.is_empty() && h.iter().all(|h| matches!(h.kind, InlayKind::Parameter))).await;
|
||||
|
||||
// Parameter info, with the bundled settings untouched.
|
||||
std::fs::write(root.join("Calls.cs"), CALLS).unwrap();
|
||||
std::fs::remove_file(root.join("Hints.cs")).unwrap();
|
||||
host.shutdown().await;
|
||||
let host = open(&root, &base.join("calls")).await;
|
||||
let doc = document(&host, &root, "Calls.cs").await;
|
||||
let start = Instant::now();
|
||||
while parameter_info(&host, doc, "Take(1, |)").await.is_none() {
|
||||
assert!(start.elapsed() < Duration::from_secs(180), "no parameter info");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
let two = "int Calls.Add(int first, int second)";
|
||||
let three = "int Calls.Add(int first, int second, int third)";
|
||||
let log = "void Calls.Log(string format, params object[] args)";
|
||||
let opt = "void Calls.Opt(int width, int height = 2, bool visible = true)";
|
||||
// (caret, overloads, marked signature, active parameter, bolded text)
|
||||
let cases = [
|
||||
("Add(|1, );", 2, two, 0, "first"),
|
||||
("Add(1, |);", 2, two, 1, "second"),
|
||||
// A third argument marks the overload that takes it.
|
||||
("Add(1, 2, |);", 2, three, 2, "third"),
|
||||
// `n` is also a letter in front of the parameter list.
|
||||
("Take(1, |);", 1, "void Calls.Take(int a, int n)", 1, "n"),
|
||||
("Add(Add(1, |total), 3);", 2, two, 1, "second"),
|
||||
("Add(Add(1, total), |3);", 2, two, 1, "second"),
|
||||
(r#"Length, |4);"#, 2, two, 1, "second"),
|
||||
(" |);", 2, two, 1, "second"),
|
||||
("Add(名前.Length, |5);", 2, two, 1, "second"),
|
||||
(r#"Log("f", |6, 7);"#, 1, log, 1, "args"),
|
||||
// Past the `params` array the count goes on; the popup keeps `args` bold (signature.ts).
|
||||
(r#"Log("f", 6, |7);"#, 1, log, 2, ""),
|
||||
("visible: |true", 1, opt, 2, "visible"),
|
||||
("width: |8", 1, opt, 0, "width"),
|
||||
(r#""x".Repeat(|9)"#, 1, "(extension) string string.Repeat(int count)", 0, "count"),
|
||||
("Echo<int>(|10)", 1, "int Calls.Echo<int>(int value)", 0, "value"),
|
||||
("new Point(11, |12)", 1, "Point(int X, int Y)", 1, "Y"),
|
||||
("new(13, |14)", 1, "Point(int X, int Y)", 1, "Y"),
|
||||
("[15, |16]", 1, "int Grid[int row, int column]", 1, "column"),
|
||||
("Map(x => x, |17)", 1, "void Calls.Map(System.Func<int, int> map, int e)", 1, "e"),
|
||||
];
|
||||
for (caret, overloads, label, active, bold) in cases {
|
||||
let found = parameter_info(&host, doc, caret).await;
|
||||
assert_eq!(found, Some((overloads, label.to_owned(), active, bold.to_owned())), "{caret}");
|
||||
}
|
||||
// Closed after the `)` of the outermost call.
|
||||
assert_eq!(parameter_info(&host, doc, "Add(Add(1, total), 3);|").await, None);
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -1138,3 +1138,57 @@ async fn unshelve_onto_a_conflicting_edit() {
|
||||
assert_eq!(shelves.len(), 1, "a conflict keeps the shelved changes");
|
||||
assert_eq!(shelves[0].files.len(), 2);
|
||||
}
|
||||
|
||||
/// Subversion › Update File / Update Directory (issue #7433): `svn update` of the selected
|
||||
/// paths only, each in its own working copy; a Git repository refuses it.
|
||||
#[tokio::test]
|
||||
async fn update_selected_paths_of_two_working_copies() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let seed = fx.checkout("seed");
|
||||
std::fs::create_dir(seed.join("dir")).unwrap();
|
||||
for name in ["a.txt", "c.txt", "dir/b.txt"] {
|
||||
std::fs::write(seed.join(name), "one\n").unwrap();
|
||||
}
|
||||
fx.svn(&seed, &["add", "-q", "a.txt", "c.txt", "dir"]);
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "seed"]);
|
||||
let project_root = fx.base.join("project");
|
||||
std::fs::create_dir(&project_root).unwrap();
|
||||
let trunk = format!("{}/trunk", fx.url);
|
||||
for name in ["boot", "antd"] {
|
||||
fx.svn(&fx.base, &["checkout", "-q", &trunk, project_root.join(name).to_str().unwrap()]);
|
||||
}
|
||||
let (boot, antd) = (project_root.join("boot"), project_root.join("antd"));
|
||||
for name in ["a.txt", "c.txt", "dir/b.txt"] {
|
||||
std::fs::write(seed.join(name), "two\n").unwrap();
|
||||
}
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "two"]);
|
||||
|
||||
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
until("both working copies", || project.backends().len() == 2).await;
|
||||
let update = |repo: &Path, paths: Vec<PathBuf>| {
|
||||
let channel = ide_host::ops::Channel::new(|_: String| {});
|
||||
let op = vcs::RemoteOp::UpdateFiles { paths };
|
||||
vcs::vcs_remote(&host, "main", Some(repo.to_path_buf()), ide_core::RequestId::next(), op, channel, None)
|
||||
};
|
||||
let updated_files = |report: Option<vcs::RemoteOpReport>| match report {
|
||||
Some(vcs::RemoteOpReport::Update(report)) => report.updated_files,
|
||||
_ => panic!("no update report"),
|
||||
};
|
||||
// A file and a folder of one working copy, one file of the other.
|
||||
assert_eq!(updated_files(update(&boot, vec![boot.join("a.txt"), boot.join("dir")]).await.unwrap()), 2);
|
||||
assert_eq!(updated_files(update(&antd, vec![antd.join("c.txt")]).await.unwrap()), 1);
|
||||
assert_eq!(updated_files(update(&antd, vec![antd.join("c.txt")]).await.unwrap()), 0, "already up to date");
|
||||
let read = |path: PathBuf| std::fs::read_to_string(path).unwrap();
|
||||
assert_eq!(
|
||||
[read(boot.join("a.txt")), read(boot.join("dir/b.txt")), read(boot.join("c.txt"))],
|
||||
["two\n", "two\n", "one\n"],
|
||||
"only the selected paths of boot"
|
||||
);
|
||||
assert_eq!(
|
||||
[read(antd.join("c.txt")), read(antd.join("a.txt")), read(antd.join("dir/b.txt"))],
|
||||
["two\n", "one\n", "one\n"],
|
||||
"only the selected file of antd"
|
||||
);
|
||||
}
|
||||
@@ -44,10 +44,10 @@ impl Backend for Fake {
|
||||
fn head_label(&self) -> Option<String> {
|
||||
Some(self.head.lock().clone())
|
||||
}
|
||||
fn update(&self, _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
fn update(&self, _: &[PathBuf], _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<usize> {
|
||||
std::fs::write(self.root.join("a.txt"), "updated\n")?;
|
||||
output("Updated to revision 8.".into());
|
||||
Ok(())
|
||||
Ok(1)
|
||||
}
|
||||
fn branches(&self) -> IdeResult<Vec<Branch>> {
|
||||
let head = self.head.lock().clone();
|
||||
@@ -347,7 +347,7 @@ async fn a_working_copy_answers_the_shared_vcs_commands() {
|
||||
let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line));
|
||||
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
|
||||
let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
|
||||
assert!(report.is_none());
|
||||
assert!(matches!(report, Some(vcs::RemoteOpReport::Update(vcs::UpdateReport { updated_files: 1 }))));
|
||||
assert_eq!(*output.lock(), ["Updated to revision 8."]);
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n");
|
||||
let labels: Vec<String> = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect();
|
||||
|
||||
@@ -76,7 +76,7 @@ fn parse_env(text: &str) -> IdeResult<EnvMap> {
|
||||
let s = match raw.as_bytes().first() {
|
||||
Some(b'"') => serde_json::from_str::<String>(raw).map_err(invalid)?,
|
||||
// Keep numeric tokens: Value::Number would round decimals and large integers.
|
||||
Some(b'-' | b'0'..=b'9' | b't' | b'f') => raw.to_owned(),
|
||||
_ if is_variable(raw) => raw.to_owned(),
|
||||
// Objects configure SSL / auth in IDEA; not variables.
|
||||
_ => continue,
|
||||
};
|
||||
@@ -87,6 +87,11 @@ fn parse_env(text: &str) -> IdeResult<EnvMap> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether `value`, JSON text, is a string, a number or a boolean.
|
||||
fn is_variable(value: &str) -> bool {
|
||||
matches!(value.as_bytes().first(), Some(b'"' | b'-' | b'0'..=b'9' | b't' | b'f'))
|
||||
}
|
||||
|
||||
/// The nearest `name` in `dirs`, decoded like the editor opens it (a BOM, UTF-16, or a
|
||||
/// legacy encoding such as GBK from Notepad's ANSI), so a file that shows fine in the editor
|
||||
/// is never skipped as unreadable.
|
||||
@@ -118,63 +123,76 @@ pub fn environment_file(file: &Path, root: Option<&Path>, private: bool) -> IdeR
|
||||
|
||||
/// Where `{{name}}` is defined in the environment files that apply to `file`: the key `name`
|
||||
/// in each environment (and `$shared`) of the nearest private file, then of the nearest public
|
||||
/// file — the lookup order. Positions are 0-based lines and UTF-16 columns of the key, quotes
|
||||
/// included.
|
||||
pub fn variable_definitions(file: &Path, root: Option<&Path>, name: &str) -> Vec<ide_core::Location> {
|
||||
/// file — the lookup order. With `env`, only the key a request run in that environment reads.
|
||||
/// Positions are 0-based lines and UTF-16 columns of the key, quotes included.
|
||||
pub fn variable_definitions(
|
||||
file: &Path,
|
||||
root: Option<&Path>,
|
||||
name: &str,
|
||||
env: Option<&str>,
|
||||
) -> Vec<ide_core::Location> {
|
||||
let dirs = search_dirs(Some(file), root);
|
||||
let mut out = Vec::new();
|
||||
let mut keys = Vec::new();
|
||||
for file_name in [PRIVATE_FILE, PUBLIC_FILE] {
|
||||
let Some(path) = dirs.iter().map(|d| d.join(file_name)).find(|p| p.is_file()) else { continue };
|
||||
let Ok(text) = ide_vfs::load_text(&path) else { continue };
|
||||
for range in environment_keys(&text.text, name) {
|
||||
out.push(ide_core::Location { path: path.clone().into(), range, uri: None });
|
||||
let mut found = environment_keys(&text.text, name);
|
||||
if env.is_some() {
|
||||
// Of a key written twice, a run reads the last one.
|
||||
found.reverse();
|
||||
}
|
||||
for (key_env, range) in found {
|
||||
keys.push((key_env, ide_core::Location { path: path.clone().into(), range, uri: None }));
|
||||
}
|
||||
}
|
||||
out
|
||||
if let Some(env) = env {
|
||||
let used = [env, SHARED].into_iter().find_map(|wanted| keys.iter().position(|(e, _)| e == wanted));
|
||||
keys = used.map(|i| keys.swap_remove(i)).into_iter().collect();
|
||||
}
|
||||
keys.into_iter().map(|(_, location)| location).collect()
|
||||
}
|
||||
|
||||
/// The ranges of keys equal to `name` one level inside the top-level object (an
|
||||
/// environment's variables), found by scanning the JSON text without building a value.
|
||||
fn environment_keys(text: &str, name: &str) -> Vec<ide_core::Range> {
|
||||
/// The environment and range of keys equal to `name` one level inside the top-level object (an
|
||||
/// environment's variables), found by scanning the JSON text without building a value. Keys whose
|
||||
/// value is not a variable (an object, an array or null) are left out.
|
||||
fn environment_keys(text: &str, name: &str) -> Vec<(String, ide_core::Range)> {
|
||||
use ide_core::{Pos, Range};
|
||||
let mut found = Vec::new();
|
||||
let mut env = String::new();
|
||||
let (mut line, mut col) = (0u32, 0u32);
|
||||
let mut depth = 0usize;
|
||||
let mut chars = text.char_indices().peekable();
|
||||
// Whether the last string closed at depth 2 may be a key: set after `{` or `,`.
|
||||
let mut chars = text.char_indices();
|
||||
// Whether a string may be a key: set after `{` or `,`.
|
||||
let mut expect_key = false;
|
||||
while let Some((_, c)) = chars.next() {
|
||||
while let Some((from, c)) = chars.next() {
|
||||
match c {
|
||||
'"' => {
|
||||
let start = Pos::new(line, col);
|
||||
col += 1;
|
||||
let mut value = String::new();
|
||||
let mut closing = None;
|
||||
let mut escaped = false;
|
||||
for (_, c) in chars.by_ref() {
|
||||
for (at, c) in chars.by_ref() {
|
||||
col += c.len_utf16() as u32;
|
||||
if escaped {
|
||||
value.push(match c {
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
other => other,
|
||||
});
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == '"' {
|
||||
closing = Some(at);
|
||||
break;
|
||||
} else {
|
||||
value.push(c);
|
||||
}
|
||||
}
|
||||
let end = Pos::new(line, col);
|
||||
if depth == 2 && expect_key && value == name {
|
||||
let mut rest = chars.clone();
|
||||
while rest.peek().is_some_and(|(_, c)| c.is_whitespace()) {
|
||||
rest.next();
|
||||
}
|
||||
if rest.peek().is_some_and(|(_, c)| *c == ':') {
|
||||
found.push(Range { start, end });
|
||||
if expect_key
|
||||
&& (depth == 1 || depth == 2)
|
||||
&& let Some(to) = closing
|
||||
&& let Some(value) = text[to + 1..].trim_start().strip_prefix(':')
|
||||
&& let Ok(key) = serde_json::from_str::<String>(&text[from..=to])
|
||||
{
|
||||
if depth == 1 {
|
||||
env = key;
|
||||
} else if key == name && is_variable(value.trim_start()) {
|
||||
found.push((env.clone(), Range { start, end }));
|
||||
}
|
||||
}
|
||||
expect_key = false;
|
||||
@@ -409,7 +427,7 @@ mod tests {
|
||||
std::fs::write(root.join("api").join(PRIVATE_FILE), "{ \"dev\": { \"😀\": 1, \"host\": \"secret\" } }")
|
||||
.unwrap();
|
||||
let file = root.join("api").join("requests.http");
|
||||
let found = variable_definitions(&file, Some(root), "host");
|
||||
let found = variable_definitions(&file, Some(root), "host", None);
|
||||
let at: Vec<_> = found
|
||||
.iter()
|
||||
.map(|l| {
|
||||
@@ -431,7 +449,55 @@ mod tests {
|
||||
],
|
||||
"values and nested objects are not definitions"
|
||||
);
|
||||
assert!(variable_definitions(&file, Some(root), "missing").is_empty());
|
||||
assert!(variable_definitions(&file, Some(root), "missing", None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_variable_key_the_selected_environment_reads() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let private = r#"{
|
||||
"$shared": { "host": 1, "key": 1 },
|
||||
"stage": { "token": 1 },
|
||||
"dev": { "token": 1, "ssl": { "x": 1 }, "empty": null }
|
||||
}"#;
|
||||
let public = r#"{
|
||||
"$shared": { "key": 1, "name": 1 },
|
||||
"dev": { "host": 1, "token": 1, "ssl": "x", "empty": true },
|
||||
"stage": { "token": 1 },
|
||||
"prod": { "host": 1, "only": 1 },
|
||||
"\u6d4b\u8bd5": {
|
||||
"na\u006de": 1
|
||||
},
|
||||
"twice": {
|
||||
"host": 1,
|
||||
"host": 2
|
||||
}
|
||||
}"#;
|
||||
std::fs::write(root.join(PRIVATE_FILE), private).unwrap();
|
||||
std::fs::write(root.join(PUBLIC_FILE), public).unwrap();
|
||||
let file = root.join("requests.http");
|
||||
let at = |name: &str, env: &str| {
|
||||
let found = variable_definitions(&file, Some(root), name, Some(env));
|
||||
found
|
||||
.iter()
|
||||
.map(|l| (l.path.0.file_name().unwrap().to_string_lossy().into_owned(), l.range.start.line))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(at("host", "prod"), [(PUBLIC_FILE.to_owned(), 4)]);
|
||||
assert_eq!(at("host", "dev"), [(PUBLIC_FILE.to_owned(), 2)], "the environment comes before private $shared");
|
||||
assert_eq!(at("host", "stage"), [(PRIVATE_FILE.to_owned(), 1)]);
|
||||
assert_eq!(at("token", "dev"), [(PRIVATE_FILE.to_owned(), 3)], "private comes before public");
|
||||
assert_eq!(at("key", "prod"), [(PRIVATE_FILE.to_owned(), 1)]);
|
||||
assert_eq!(at("only", "dev"), []);
|
||||
assert_eq!(at("ssl", "dev"), [(PUBLIC_FILE.to_owned(), 2)], "an object is not a variable");
|
||||
assert_eq!(at("empty", "dev"), [(PUBLIC_FILE.to_owned(), 2)], "null is not a variable");
|
||||
assert_eq!(at("name", "测试"), [(PUBLIC_FILE.to_owned(), 6)], "keys may be escaped");
|
||||
assert_eq!(at("host", "twice"), [(PUBLIC_FILE.to_owned(), 10)], "the last duplicate wins");
|
||||
|
||||
// Half-typed files.
|
||||
std::fs::write(root.join(PUBLIC_FILE), r#"{ "prod": { "host": 1 }, "dev": { "测"#).unwrap();
|
||||
assert_eq!(at("host", "prod"), [(PUBLIC_FILE.to_owned(), 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 830 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача