дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
81
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
975859bdd8 | ||
|
|
42b68388be | ||
|
|
72b0c7c48c | ||
|
|
25d1046af0 | ||
|
|
1cdb998532 | ||
|
|
b1ab5afa67 | ||
|
|
0101d11ac9 | ||
|
|
07d26722b1 | ||
|
|
df48d9271b | ||
|
|
cb6b7ccd3f | ||
|
|
13c0e8aa8d | ||
|
|
9f643af069 | ||
|
|
0c02a9e467 | ||
|
|
8c7bdc9bf2 | ||
|
|
a3f6d82391 | ||
|
|
bfde0ffc34 | ||
|
|
9067abf0cf | ||
|
|
4939b63c88 | ||
|
|
78d34af971 | ||
|
|
d47c9eb347 | ||
|
|
5348e42c59 | ||
|
|
a42eee29f4 | ||
|
|
a3e7142e4c | ||
|
|
d21fd65341 | ||
|
|
422f424b60 | ||
|
|
c10862b1a6 | ||
|
|
d4db49689e | ||
|
|
36ab40797c | ||
|
|
de7d62dce8 | ||
|
|
e3f9049e26 | ||
|
|
3e9f018cf4 | ||
|
|
e44d7fd396 | ||
|
|
dc490f1017 | ||
|
|
5289f44620 | ||
|
|
81aac31cc7 | ||
|
|
026163af9e | ||
|
|
ce03ae7c0f | ||
|
|
1cd8e8def5 | ||
|
|
a0b9fba2f2 | ||
|
|
1f6a3bbf0d | ||
|
|
5265455313 | ||
|
|
64cc72ba2e | ||
|
|
b79dbae83f | ||
|
|
e909c50fe4 | ||
|
|
da7125a944 | ||
|
|
e54e309d61 | ||
|
|
8c3371212c | ||
|
|
e08531c458 | ||
|
|
9c9e0e59cb | ||
|
|
1d5d33cf76 | ||
|
|
2bbba9b945 | ||
|
|
14f143b703 | ||
|
|
f2a372428c | ||
|
|
89524bd583 | ||
|
|
f90d94538d | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace |
No files matched your search
@@ -156,6 +156,44 @@ jobs:
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
timeout-minutes: 5
|
||||
shell: bash
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
|
||||
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
name: Homebrew
|
||||
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published stable release to write the cask for (e.g. v0.1.51)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: homebrew-tap
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
|
||||
- name: Write the cask
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
|
||||
- name: Push to the tap
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
working-directory: tap
|
||||
run: |
|
||||
git add Casks/openidea.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "the cask is already at ${TAG#v}"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "openidea ${TAG#v}"
|
||||
git push
|
||||
@@ -178,3 +178,10 @@ jobs:
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
@@ -4458,13 +4458,18 @@ version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"bytes",
|
||||
"criterion",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"futures",
|
||||
"getrandom 0.3.4",
|
||||
"globset",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"ide-agent",
|
||||
"ide-analysis",
|
||||
"ide-build",
|
||||
@@ -6745,6 +6750,7 @@ dependencies = [
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
On macOS you can also install it with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
|
||||
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
macOS'ta Homebrew ile de kurabilirsiniz:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
|
||||
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
|
||||
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
|
||||
提供 macOS、Windows 和 Linux 版本。
|
||||
|
||||
在 macOS 上也可以用 Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
|
||||
|
||||
@@ -450,6 +450,35 @@ struct TaskFile {
|
||||
/// The user named the task: its agent's own title updates no longer replace it.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`]: the task file is never written, and new sessions ask the
|
||||
/// agent not to save their history.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
ephemeral: bool,
|
||||
/// Start the first session as a fork of a recorded native one (once).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
}
|
||||
|
||||
/// A session to start as a fork of the recorded one: its source, and the id the host
|
||||
/// chooses for the fork (claude); codex assigns its own.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForkStart {
|
||||
source: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
/// A canonical lowercase UUID, the only session id shape either native agent writes.
|
||||
fn canonical_uuid(value: &str) -> bool {
|
||||
value.len() == 36
|
||||
&& value.bytes().enumerate().all(|(index, byte)| {
|
||||
if matches!(index, 8 | 13 | 18 | 23) {
|
||||
byte == b'-'
|
||||
} else {
|
||||
byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -502,6 +531,10 @@ struct TaskState {
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`].
|
||||
ephemeral: bool,
|
||||
/// See `TaskFile::pending_native_fork`: cleared once a session is established.
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
/// Background tasks the agent reported as running (`run_in_background` commands and
|
||||
@@ -1023,6 +1056,94 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
/// Forks a recorded external session into a new task: its first turn continues the
|
||||
/// 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") {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
return Err(IdeError::invalid("the recorded session has no canonical id"));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
if self.imported_session_ids().contains(session_id) {
|
||||
return Err(IdeError::invalid("that session is already a task"));
|
||||
}
|
||||
let found = self
|
||||
.external_sessions()
|
||||
.into_iter()
|
||||
.find(|s| s.provider == provider && s.session_id == session_id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?;
|
||||
let recorded = found
|
||||
.cwd
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute())
|
||||
.ok_or_else(|| IdeError::invalid("the recorded session has no working directory"))?;
|
||||
let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
if canonical(cwd) != canonical(&recorded) {
|
||||
return Err(IdeError::invalid("the session was recorded in another directory"));
|
||||
}
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let config = self.shared.known_config(&spec.id);
|
||||
let now = now_ms();
|
||||
let id = uuid::Uuid::new_v4().simple().to_string();
|
||||
// The host names the fork's session id for claude; codex assigns its own.
|
||||
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(root)),
|
||||
id,
|
||||
title: found.title,
|
||||
provider: spec.id.clone(),
|
||||
model: model_of(&config),
|
||||
status: AgentStatus::Ready,
|
||||
isolation: Isolation::Local,
|
||||
cwd: IpcPath(recorded),
|
||||
branch: None,
|
||||
base: None,
|
||||
base_commit: None,
|
||||
error: None,
|
||||
created_ms: now,
|
||||
updated_ms: now,
|
||||
config,
|
||||
commands: self.shared.known_commands(&spec.id),
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: target.clone(),
|
||||
entries: Vec::new(),
|
||||
wanted: Vec::new(),
|
||||
pending_model: None,
|
||||
pending_switch: None,
|
||||
before: BTreeMap::new(),
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
turns: Vec::new(),
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }),
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
@@ -1151,6 +1272,8 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
ephemeral: req.ephemeral,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
handle.state.lock().busy = !req.idle;
|
||||
@@ -1516,6 +1639,8 @@ impl AgentManager {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: None,
|
||||
}
|
||||
};
|
||||
// Copying may have started the source's agent: it stops again once idle.
|
||||
@@ -2420,6 +2545,8 @@ impl Task {
|
||||
turns,
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
ephemeral: file.ephemeral,
|
||||
pending_native_fork: file.pending_native_fork,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
shell_context: Vec::new(),
|
||||
@@ -2675,7 +2802,9 @@ impl Task {
|
||||
let mut file = self.file.lock();
|
||||
// Read before the copy: whatever was asked for up to now is in it.
|
||||
let asked = self.saves_asked.load(Ordering::Acquire);
|
||||
if file.deleted || file.saved >= asked {
|
||||
// A throwaway task is never written: one its caller couldn't delete (a window closed
|
||||
// while it ran) is gone after a restart.
|
||||
if file.deleted || file.saved >= asked || self.state.lock().ephemeral {
|
||||
return;
|
||||
}
|
||||
let copy = {
|
||||
@@ -2695,6 +2824,8 @@ impl Task {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: s.pending_native_fork.clone(),
|
||||
}
|
||||
};
|
||||
let bytes = serde_json::to_vec(©);
|
||||
@@ -3357,66 +3488,101 @@ impl Task {
|
||||
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
|
||||
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
|
||||
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
|
||||
let pending_native_fork = self.state.lock().pending_native_fork.clone();
|
||||
|
||||
let mut tried_auth = false;
|
||||
let mut session = None;
|
||||
let start_fresh = self.start_fresh.load(Ordering::Acquire);
|
||||
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent does not support resuming this session.".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
if let Some(fork) = pending_native_fork {
|
||||
if !capabilities.fork {
|
||||
return Err(SessionOpenError {
|
||||
message: "the agent can't continue a recorded session".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
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 } }),
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
Err(e) => {
|
||||
tracing::info!("agent task {}: session/load failed: {e}", self.id);
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
let reply = self
|
||||
.request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params)
|
||||
.await
|
||||
.map_err(|e| SessionOpenError { message: self.describe(e), allow_acp_fallback: false })?;
|
||||
let id = reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| SessionOpenError {
|
||||
message: "the agent returned no session".into(),
|
||||
allow_acp_fallback: false,
|
||||
})?
|
||||
.to_owned();
|
||||
session = Some((id, reply));
|
||||
} else {
|
||||
let start_fresh = self.start_fresh.load(Ordering::Acquire);
|
||||
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent does not support resuming this session.".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
Err(e) => {
|
||||
tracing::info!("agent task {}: session/load failed: {e}", self.id);
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
self.start_fresh.store(true, Ordering::Release);
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
|
||||
continue in a new session. The agent won't see the earlier conversation.",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
self.start_fresh.store(true, Ordering::Release);
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
|
||||
continue in a new session. The agent won't see the earlier conversation.",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3424,7 +3590,10 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
if self.state.lock().ephemeral {
|
||||
mark_ephemeral(&mut params);
|
||||
}
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -3604,6 +3773,8 @@ impl Task {
|
||||
s.pending_model = None;
|
||||
s.task.capabilities = capabilities;
|
||||
s.session_id = Some(session_id.clone());
|
||||
// The recorded session is forked (or the fork resumed): the one-shot intent is spent.
|
||||
s.pending_native_fork = None;
|
||||
self.start_fresh.store(false, Ordering::Release);
|
||||
// The (re)started process runs nothing yet: whatever it reports next is all of it.
|
||||
s.background_tasks = Vec::new();
|
||||
@@ -4482,6 +4653,15 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
|
||||
params
|
||||
}
|
||||
|
||||
/// `_meta.openidea.ephemeral` of `session/new`: the native drivers start the session without
|
||||
/// saving it (Claude Code `--no-session-persistence`, Codex `ephemeral` threads).
|
||||
fn mark_ephemeral(params: &mut Value) {
|
||||
if !params["_meta"]["openidea"].is_object() {
|
||||
params["_meta"]["openidea"] = json!({});
|
||||
}
|
||||
params["_meta"]["openidea"]["ephemeral"] = json!(true);
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
@@ -700,6 +700,10 @@ pub struct NewAgentTask {
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
|
||||
/// restart, and the agent keeps no session history of its own for it.
|
||||
#[serde(default)]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
|
||||
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
|
||||
.unwrap_or(direct)
|
||||
}
|
||||
|
||||
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
|
||||
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
|
||||
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
|
||||
/// Copies the transcript and its folder (subagents, tool results) under the same project
|
||||
/// directory name. Returns whether the session is in `config_dir` now.
|
||||
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
|
||||
if transcript(config_dir, cwd, id).exists() {
|
||||
return true;
|
||||
}
|
||||
let file = format!("{id}.jsonl");
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let mut homes: Vec<PathBuf> = config_dir
|
||||
.parent()
|
||||
.into_iter()
|
||||
.chain(home.as_deref())
|
||||
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
|
||||
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
|
||||
.map(|d| d.path())
|
||||
.filter(|p| p != config_dir && p.join("projects").is_dir())
|
||||
.collect();
|
||||
homes.sort();
|
||||
homes.dedup();
|
||||
let found = homes.iter().find_map(|other| {
|
||||
let projects = other.join("projects");
|
||||
let direct = projects.join(escape(cwd));
|
||||
std::iter::once(direct.clone())
|
||||
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
|
||||
.find(|dir| dir.join(&file).is_file())
|
||||
});
|
||||
let Some(source) = found else { return false };
|
||||
let Some(name) = source.file_name() else { return false };
|
||||
let target = config_dir.join("projects").join(name);
|
||||
let copied = std::fs::create_dir_all(&target)
|
||||
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
|
||||
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
|
||||
match copied {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if !from.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let dest = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &dest)?;
|
||||
} else if !dest.exists() {
|
||||
std::fs::copy(entry.path(), dest)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project directory name Claude Code uses for `cwd`.
|
||||
pub(crate) fn escape(cwd: &Path) -> String {
|
||||
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
@@ -207,6 +268,26 @@ mod tests {
|
||||
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_from_another_config_dir_is_copied_in() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
|
||||
let cwd = Path::new("/work/app");
|
||||
let project = old.join("projects").join(escape(cwd));
|
||||
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
|
||||
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
|
||||
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
|
||||
std::fs::create_dir_all(new.join("projects")).unwrap();
|
||||
|
||||
assert!(!adopt(&new, cwd, "missing"));
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
let copied = new.join("projects").join(escape(cwd));
|
||||
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
|
||||
assert!(copied.join("s1/subagents/a.jsonl").is_file());
|
||||
assert!(project.join("s1.jsonl").is_file(), "the original stays");
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_branch_is_the_conversation() {
|
||||
let entries = vec![
|
||||
|
||||
@@ -178,6 +178,8 @@ struct Session {
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -334,6 +336,12 @@ impl Shim {
|
||||
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
|
||||
}
|
||||
|
||||
/// Whether session `id` is in the configuration directory, copied there from another one
|
||||
/// if need be (see [`history::adopt`]).
|
||||
fn adopt(&self, cwd: &Path, id: &str) -> bool {
|
||||
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
@@ -370,6 +378,7 @@ impl Shim {
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -435,10 +444,13 @@ impl Shim {
|
||||
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let cwd = self.cwd_of(¶ms);
|
||||
let (start, pending) = match self.load_pending(id) {
|
||||
Some(s) => (s, true),
|
||||
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
|
||||
(Start::Resume { id: id.to_owned(), at: None }, false)
|
||||
Some(s) => {
|
||||
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
|
||||
self.adopt(&cwd, from);
|
||||
}
|
||||
(s, true)
|
||||
}
|
||||
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
@@ -451,24 +463,43 @@ impl Shim {
|
||||
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
|
||||
}
|
||||
"session/fork" => {
|
||||
let source = self.session(¶ms)?;
|
||||
let id = new_uuid(false);
|
||||
let (start, settings) = {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
let source_id =
|
||||
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let source = self.sessions.lock().get(source_id).cloned();
|
||||
// The host names the fork's session id so the task knows it before the CLI
|
||||
// starts; only a canonical UUID is accepted.
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
if let Some(target) = requested
|
||||
&& !crate::canonical_uuid(target)
|
||||
{
|
||||
return Err(invalid("A fork session id must be a canonical UUID"));
|
||||
}
|
||||
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
|
||||
if self.sessions.lock().contains_key(&id) {
|
||||
return Err(invalid(format!("session {id} is already open")));
|
||||
}
|
||||
let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone());
|
||||
let (start, settings) = match &source {
|
||||
Some(source) => {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
}
|
||||
// A recorded session is not open in this connection: the CLI forks it
|
||||
// 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()),
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
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 }))
|
||||
@@ -703,6 +734,9 @@ impl Session {
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
|
||||
@@ -464,6 +464,7 @@ async fn replay_simple() {
|
||||
let args = r.cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
|
||||
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
|
||||
assert!(!args.contains(&"--no-session-persistence".to_owned()));
|
||||
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
|
||||
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
|
||||
}
|
||||
@@ -652,6 +653,84 @@ async fn replay_resume() {
|
||||
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
/// Registering a fork must not start a process: its first prompt does.
|
||||
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";
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply["sessionId"], target);
|
||||
// The host chose this id for the fork: the next process must fork the recorded
|
||||
// session under exactly it.
|
||||
let saved: Value =
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(saved, 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;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("no process")
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
|
||||
let error = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": "11111111-1111-4111-8111-111111111111",
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": rejected } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect_err("only a canonical id may name the fork");
|
||||
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- recording ----------
|
||||
|
||||
/// Passes the real CLI's stdio through, keeping what went over it.
|
||||
@@ -1350,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_is_not_saved() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({ "cwd": h.cwd, "mcpServers": [], "_meta": { "openidea": { "ephemeral": true } } });
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
@@ -492,6 +492,10 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
|
||||
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
|
||||
request["ephemeral"] = json!(true);
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
if id.is_empty() {
|
||||
|
||||
@@ -1891,3 +1891,40 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
for ephemeral in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled: false,
|
||||
other_project: false,
|
||||
write_error: false,
|
||||
overridden: false,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::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(client.clone(), |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 mut params = json!({"cwd": cwd, "mcpServers": []});
|
||||
if ephemeral {
|
||||
params["_meta"] = json!({"openidea": {"ephemeral": true}});
|
||||
}
|
||||
request(&acp, "session/new", params).await.unwrap();
|
||||
let calls = server.calls.lock();
|
||||
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
|
||||
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
|
||||
drop(calls);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,8 @@ struct FakeAgent {
|
||||
session_steering: bool,
|
||||
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The params of every `session/fork`, in order.
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
}
|
||||
@@ -175,6 +177,9 @@ impl Handler for FakeAgent {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.mcp_calls.lock().push((method.to_owned(), names));
|
||||
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
|
||||
self.calls.lock().push("ephemeral".into());
|
||||
}
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
@@ -203,7 +208,11 @@ impl Handler for FakeAgent {
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": options}))
|
||||
}
|
||||
"session/fork" => Ok(json!({"sessionId": "s2"})),
|
||||
"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") }))
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
Ok(json!({}))
|
||||
@@ -642,6 +651,32 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for ephemeral in [true, false] {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Write a commit message"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
ephemeral,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
mgr.shutdown();
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_commands_share_catalog_discovery_and_persist_results() {
|
||||
@@ -2773,6 +2808,128 @@ async fn forks_rollbacks_and_steering() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111";
|
||||
const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
/// Plants a recorded claude transcript for `session_id` under the project's escaped folder.
|
||||
fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
|
||||
let config = root.join("claude-config");
|
||||
mgr.set_builtin_env(
|
||||
"claude",
|
||||
[("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.reload_providers();
|
||||
let escaped: String =
|
||||
root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
|
||||
let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl"));
|
||||
std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&transcript,
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user",
|
||||
"uuid": "u1",
|
||||
"parentUuid": null,
|
||||
"message": {"role": "user", "content": "fix the login bug"},
|
||||
"cwd": root.to_string_lossy(),
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.provider, "claude");
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
assert_eq!(task.isolation, Isolation::Local);
|
||||
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1, "one fork start");
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap();
|
||||
assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}");
|
||||
assert_ne!(target, NATIVE_SOURCE);
|
||||
assert!(
|
||||
!agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"),
|
||||
"the task forks the recorded session instead of starting or loading another"
|
||||
);
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree.
|
||||
fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(format!("rollout-{session_id}.jsonl")),
|
||||
format!(
|
||||
"{}\n{}\n",
|
||||
json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}),
|
||||
json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_codex_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1);
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_invalid_input_before_starting() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
// Non-native provider, malformed id, unknown session, wrong directory.
|
||||
let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [
|
||||
("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound),
|
||||
("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput),
|
||||
];
|
||||
for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() {
|
||||
let error = mgr.fork_session(provider, id, cwd).unwrap_err();
|
||||
assert_eq!(error.kind, kind, "case {index}: {error}");
|
||||
}
|
||||
// A session already held by a task cannot be forked again.
|
||||
mgr.import_session("claude", NATIVE_SOURCE).unwrap();
|
||||
let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}");
|
||||
assert!(agent.calls.lock().is_empty(), "no process may start");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn usage_limits_and_late_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -5421,6 +5578,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5483,6 +5641,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5626,6 +5785,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5652,6 +5812,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -16,7 +16,8 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
|
||||
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
/// The last resolved dependency classpath for one module and scope. A fingerprint
|
||||
/// permits reuse during a build; NoBuild also uses records without one.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
fingerprint: Option<LaunchFingerprint>,
|
||||
classpath: String,
|
||||
}
|
||||
|
||||
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
if project.packaging == "pom" {
|
||||
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
|
||||
}
|
||||
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);
|
||||
@@ -217,6 +214,30 @@ pub fn module_classpath(
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
|
||||
pub fn module_classpath_without_build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let target = module_target(root, model, module, test)?;
|
||||
if let Some(path) = classpath_cache_path(root, cache, module, test)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
@@ -245,7 +266,7 @@ pub fn module_classpaths(
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& cached.fingerprint.as_ref() == Some(fingerprint)
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
@@ -269,7 +290,7 @@ pub fn module_classpaths(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
if let Some(path) = cache_path {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
@@ -675,6 +696,81 @@ mod tests {
|
||||
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
let script = root.join("mvnw");
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
|
||||
);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
|
||||
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
|
||||
);
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let previous =
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
assert!(previous.contains("repo/runtime.jar"), "{previous}");
|
||||
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
|
||||
let launch =
|
||||
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
assert!(launch.contains("repo/runtime.jar"), "{launch}");
|
||||
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -441,7 +441,7 @@ impl JavaBuild<'_> {
|
||||
let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?;
|
||||
let project = record.model.projects.iter().find(|p| p.dir == module)?;
|
||||
let paths = class_paths(project, test);
|
||||
paths.first().is_some_and(|p| p.is_dir()).then_some(paths)
|
||||
paths.first().is_some_and(|p| p.exists()).then_some(paths)
|
||||
}
|
||||
|
||||
/// Builds `target`. A launch gets the classpath to run with; the others an empty one.
|
||||
@@ -1039,7 +1039,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test:
|
||||
if test {
|
||||
visit(project, false, by_output, by_test_output, seen, out);
|
||||
}
|
||||
for entry in &project.set(test).classpath {
|
||||
for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) {
|
||||
if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
visit(upstream, false, by_output, by_test_output, seen, out);
|
||||
} else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
@@ -1061,10 +1061,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec<PathBuf> {
|
||||
out.push(p.clone());
|
||||
}
|
||||
};
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
if target.packaging != "pom" {
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
for entry in &target.set(test).runtime_classpath {
|
||||
push(entry);
|
||||
}
|
||||
|
||||
@@ -18,15 +18,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
|
||||
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
|
||||
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>lib</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lib</module>
|
||||
<module>app</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let units: Vec<u16> =
|
||||
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -308,6 +308,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +344,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -818,8 +825,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -839,8 +844,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -1291,8 +1312,10 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1310,14 +1333,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1470,26 +1493,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1640,16 +1696,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1661,7 +1740,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1853,7 +1932,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1868,10 +1947,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1885,11 +1969,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1899,8 +1984,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1908,13 +1996,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -2124,14 +2212,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2144,12 +2235,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -126,6 +126,8 @@ struct Script {
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -206,6 +208,7 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -520,6 +523,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -899,7 +916,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -981,7 +998,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1005,7 +1022,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1037,7 +1054,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1889,7 +1906,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1898,7 +1915,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1914,8 +1931,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1958,10 +1978,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -1995,10 +2018,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -2009,6 +2032,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2209,7 +2266,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2236,7 +2293,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2270,7 +2327,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2292,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2299,7 +2371,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2323,7 +2395,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3418,7 +3490,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -297,6 +297,8 @@ pub struct DbManager {
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
|
||||
|
||||
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
|
||||
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
|
||||
@@ -1429,13 +1431,34 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let mut tables: Vec<CompletionTable> = Vec::new();
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return self.jdbc_completion(id, p).await;
|
||||
}
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
|
||||
Pool::Snowflake(p) => {
|
||||
tables = snowflake::meta::completion(p).await?;
|
||||
Vec::new()
|
||||
}
|
||||
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
|
||||
// The default schema is read in full: under a shared row cap, a schema with many
|
||||
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
|
||||
_ if !default_schema.is_empty() => {
|
||||
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
|
||||
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
|
||||
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
|
||||
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
|
||||
rows
|
||||
}
|
||||
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
|
||||
};
|
||||
for r in rows {
|
||||
let mut it = r.into_iter().map(Option::unwrap_or_default);
|
||||
@@ -1471,16 +1494,6 @@ impl DbManager {
|
||||
})
|
||||
};
|
||||
let foreign_keys = group_foreign_keys(fk_rows, &tables);
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(CompletionModel { default_schema, tables, foreign_keys })
|
||||
}
|
||||
|
||||
|
||||
@@ -252,31 +252,47 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which schemas a [`completion_columns`] query reads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompletionScope<'a> {
|
||||
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
All,
|
||||
/// One schema, in full.
|
||||
Only(&'a str),
|
||||
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
Except(&'a str),
|
||||
}
|
||||
|
||||
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
|
||||
pub const COMPLETION_ROW_CAP: usize = 50_000;
|
||||
|
||||
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
|
||||
/// for SQL completion, grouped by table in column order.
|
||||
pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
let (query, schema, order) = match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => {
|
||||
DbDriver::Clickhouse => (
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
|
||||
ORDER BY c.database, c.table, c.position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Sqlite => {
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
"c.database, c.table, c.position",
|
||||
),
|
||||
DbDriver::Sqlite => (
|
||||
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
|
||||
}
|
||||
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
|
||||
DbDriver::Postgres => {
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
"m.name, p.cid",
|
||||
),
|
||||
DbDriver::Postgres => (
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
|
||||
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
|
||||
@@ -287,19 +303,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
|
||||
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
|
||||
"n.nspname",
|
||||
"n.nspname, c.relname, a.attnum",
|
||||
),
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::SqlServer => (
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
@@ -310,19 +328,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
"c.TABLE_SCHEMA",
|
||||
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
|
||||
),
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::Oracle => (
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
@@ -334,10 +354,22 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
|
||||
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
|
||||
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
|
||||
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
|
||||
}
|
||||
}
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
|
||||
"c.owner",
|
||||
"c.owner, c.table_name, c.column_id",
|
||||
),
|
||||
};
|
||||
let filter = match scope {
|
||||
CompletionScope::All => String::new(),
|
||||
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
|
||||
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
|
||||
};
|
||||
let cap = match (scope, driver) {
|
||||
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
|
||||
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
|
||||
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
|
||||
};
|
||||
format!("{query}{filter} ORDER BY {order}{cap}")
|
||||
}
|
||||
|
||||
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
|
||||
@@ -950,7 +982,7 @@ mod tests {
|
||||
let keys = indexes(driver, "default", "events");
|
||||
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
|
||||
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
|
||||
let completion = completion_columns(driver);
|
||||
let completion = completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion.contains("c.is_in_primary_key, 1"));
|
||||
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
|
||||
}
|
||||
@@ -1060,7 +1092,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
@@ -1074,7 +1106,7 @@ mod tests {
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
completion_columns(d, CompletionScope::All),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
@@ -1141,7 +1173,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
|
||||
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
|
||||
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
|
||||
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
|
||||
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
|
||||
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
|
||||
@@ -1256,7 +1288,7 @@ mod tests {
|
||||
let columns = columns(driver, "PUBLIC", "ORDERS");
|
||||
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
|
||||
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
|
||||
assert!(completion_columns(driver).contains("LIMIT 50000"));
|
||||
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
|
||||
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
|
||||
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
|
||||
assert_eq!(
|
||||
@@ -1268,6 +1300,35 @@ mod tests {
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_reads_the_default_schema_without_the_shared_cap() {
|
||||
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
|
||||
// sorting last had no columns.
|
||||
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
|
||||
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
|
||||
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
|
||||
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
|
||||
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
|
||||
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
|
||||
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
|
||||
for (driver, column) in [
|
||||
(DbDriver::Postgres, "n.nspname"),
|
||||
(DbDriver::Mysql, "c.table_schema"),
|
||||
(DbDriver::Clickhouse, "c.database"),
|
||||
(DbDriver::Snowflake, "c.table_schema"),
|
||||
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
|
||||
(DbDriver::Sqlite, "'main'"),
|
||||
] {
|
||||
let only = completion_columns(driver, CompletionScope::Only("app"));
|
||||
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
|
||||
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
|
||||
let rest = completion_columns(driver, CompletionScope::Except("app"));
|
||||
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
|
||||
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
|
||||
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_catalog_queries_run_on_older_servers() {
|
||||
let pg = DbDriver::Postgres;
|
||||
@@ -1279,7 +1340,7 @@ mod tests {
|
||||
tables(pg, "s"),
|
||||
columns(pg, "s", "t"),
|
||||
indexes(pg, "s", "t"),
|
||||
completion_columns(pg).to_owned(),
|
||||
completion_columns(pg, CompletionScope::All),
|
||||
foreign_keys(pg).to_owned(),
|
||||
table_foreign_keys(pg, "s", "t"),
|
||||
triggers(pg, "s", "t"),
|
||||
@@ -1290,7 +1351,7 @@ mod tests {
|
||||
let upper = q.to_uppercase();
|
||||
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
|
||||
}
|
||||
assert_eq!(postgres_legacy(completion_columns(pg)), None);
|
||||
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
|
||||
@@ -779,3 +779,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "wide".into();
|
||||
source.options.startup_script = format!("SET search_path = {schema}");
|
||||
sources.push(source);
|
||||
let password = server().map(|(.., password)| password);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("wide", password, false).await?;
|
||||
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
|
||||
let fill = format!(
|
||||
"DO $$ DECLARE cols text; BEGIN \
|
||||
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
|
||||
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
|
||||
END LOOP; END $$"
|
||||
);
|
||||
let result = async {
|
||||
db.execute("p", &fill, 1, &c).await?;
|
||||
let completion = db.completion("wide").await?;
|
||||
assert_eq!(completion.default_schema, schema);
|
||||
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
|
||||
assert_eq!(wide.len(), 260);
|
||||
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
|
||||
result
|
||||
}
|
||||
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
|
||||
@@ -62,6 +62,8 @@ pub enum Capability {
|
||||
/// Load the plugin's Java agent into the JVMs of Java run configurations. Never
|
||||
/// declared: it comes from `[[contributes.javaAgents]]`.
|
||||
JavaAgent,
|
||||
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
|
||||
Agents,
|
||||
}
|
||||
|
||||
/// How a grant is presented (plan 4.2).
|
||||
@@ -91,7 +93,8 @@ impl Capability {
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
| Self::Clipboard
|
||||
| Self::ClipboardRead => Risk::Medium,
|
||||
| Self::ClipboardRead
|
||||
| Self::Agents => Risk::Medium,
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
@@ -149,6 +152,7 @@ impl Capability {
|
||||
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
|
||||
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
|
||||
Self::JavaAgent => "Run code inside the Java applications you start".into(),
|
||||
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +280,7 @@ impl fmt::Display for Capability {
|
||||
Self::FsRead(p) => write!(f, "fs.read:{p}"),
|
||||
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
|
||||
Self::JavaAgent => f.write_str("java.agent"),
|
||||
Self::Agents => f.write_str("agents"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -355,6 +360,7 @@ impl FromStr for Capability {
|
||||
"clipboard" => Self::Clipboard,
|
||||
"clipboard.read" => Self::ClipboardRead,
|
||||
"java.agent" => Self::JavaAgent,
|
||||
"agents" => Self::Agents,
|
||||
_ => return Err(format!("unknown capability {s:?}")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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.17.0";
|
||||
pub const ENGINE_VERSION: &str = "1.18.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -168,6 +168,8 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"action-performed",
|
||||
"vcs-changed",
|
||||
"problems-changed",
|
||||
"project-closed",
|
||||
"watched-files-changed",
|
||||
];
|
||||
|
||||
impl std::fmt::Display for ActivationEvent {
|
||||
@@ -367,6 +369,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::ClipboardRead) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 11)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::JavaAgent) {
|
||||
return Err(
|
||||
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
|
||||
@@ -403,6 +408,10 @@ impl Manifest {
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") {
|
||||
self.needs_api("`on-event:files-changed`", 3)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "project-closed" || kind == "watched-files-changed")
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if !seen.insert(event) {
|
||||
return Err(format!("duplicate activation event {event}"));
|
||||
}
|
||||
@@ -962,4 +971,21 @@ mod net_ask_api_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_closed_and_watched_files_events_require_api_1_18() {
|
||||
for kind in ["project-closed", "watched-files-changed"] {
|
||||
for engine in ["^1.17", "^1.18"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:{kind}\"]\n"
|
||||
);
|
||||
let parsed = Manifest::parse(&manifest);
|
||||
if engine == "^1.18" {
|
||||
parsed.unwrap();
|
||||
} else {
|
||||
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{kind} {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,12 @@ serde_json = { workspace = true, features = ["raw_value"] }
|
||||
toml.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
tokio = { workspace = true, features = ["io-std"] }
|
||||
bytes = "1"
|
||||
flate2.workspace = true
|
||||
http-body-util = "0.1"
|
||||
hyper = { version = "1", features = ["http1", "server"] }
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["tokio"] }
|
||||
tokio = { workspace = true, features = ["io-std", "net", "signal"] }
|
||||
tracing.workspace = true
|
||||
url = "2"
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! `openidea-server`: the IDE backend for remote development, either serving one
|
||||
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
|
||||
//! per-project daemon (`--attach <project>`).
|
||||
//! `openidea-server`: the headless IDE backend.
|
||||
//!
|
||||
//! * `--stdio`: JSON-RPC over stdin/stdout for SSH / remote development clients.
|
||||
//! * `--attach <project>`: persistent per-project remote development daemon.
|
||||
//! * `--web`: HTTP + WebSocket server exposing the full OpenIDEA web interface on a configurable port.
|
||||
//! * `--mcp-stdio`: MCP stdio bridge.
|
||||
//! * `--connect <host> <port>`: TCP relay over stdin/stdout.
|
||||
|
||||
use ide_host::catalogue::TrustClass;
|
||||
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
|
||||
use ide_host::plugins::remote_host::RemotePlugins;
|
||||
use ide_host::rpc::{self, Dispatcher};
|
||||
use ide_host::web_server::{self, WebServerConfig};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_language::LanguageRegistry;
|
||||
use std::path::PathBuf;
|
||||
@@ -17,6 +22,126 @@ enum Mode {
|
||||
Daemon(PathBuf, ide_host::daemon::BuildId),
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
"\
|
||||
usage:
|
||||
openidea-server --web [options] [<project>]
|
||||
openidea-server --stdio
|
||||
openidea-server --attach <project-path>
|
||||
openidea-server --mcp-stdio [--project <path>]
|
||||
openidea-server --connect <host> <port>
|
||||
openidea-server --version
|
||||
|
||||
web mode options:
|
||||
--host <addr> Bind address (default: $OPENIDEA_HOST or 127.0.0.1)
|
||||
--port <port> Listen port (default: $OPENIDEA_PORT or 8080)
|
||||
--base-path <prefix> Optional reverse-proxy URL prefix (default: $OPENIDEA_BASE_PATH)
|
||||
--web-dir <dir> Built frontend directory (default: $OPENIDEA_WEB_DIR or auto-detected dist/)
|
||||
--project <path> Workspace directory to open on startup (default: $OPENIDEA_WORKSPACE_DIR)
|
||||
--home <dir> Persistent config/data directory (default: $OPENIDEA_SERVER_HOME or ~/.openidea)
|
||||
--token <secret|auto> Access token ($OPENIDEA_WEB_TOKEN; default: auto-generated random token)
|
||||
--no-auth Disable token auth ($OPENIDEA_WEB_NO_AUTH=1; use only behind an authenticating proxy)
|
||||
--no-trust-project Prompt before trusting --project instead of trusting it automatically"
|
||||
);
|
||||
}
|
||||
|
||||
struct ParsedWebArgs {
|
||||
config: WebServerConfig,
|
||||
home_override: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn env_truthy(name: &str) -> bool {
|
||||
std::env::var(name).ok().is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
|
||||
}
|
||||
|
||||
fn parse_web_args(args: &[String]) -> Result<ParsedWebArgs, String> {
|
||||
let mut host = std::env::var("OPENIDEA_HOST").unwrap_or_else(|_| "127.0.0.1".into());
|
||||
let mut port: u16 = match std::env::var("OPENIDEA_PORT") {
|
||||
Ok(raw) if !raw.trim().is_empty() => {
|
||||
raw.trim().parse::<u16>().map_err(|_| format!("invalid OPENIDEA_PORT value: {raw}"))?
|
||||
}
|
||||
_ => 8080,
|
||||
};
|
||||
let mut base_path = std::env::var("OPENIDEA_BASE_PATH").ok().filter(|s| !s.trim().is_empty());
|
||||
let mut web_dir = web_server::default_web_dir();
|
||||
let mut project = std::env::var_os("OPENIDEA_WORKSPACE_DIR")
|
||||
.or_else(|| std::env::var_os("OPENIDEA_PROJECT"))
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(PathBuf::from);
|
||||
let mut trust_project = true;
|
||||
let mut no_auth = env_truthy("OPENIDEA_WEB_NO_AUTH");
|
||||
let mut auth_token = std::env::var("OPENIDEA_WEB_TOKEN").ok().filter(|s| !s.trim().is_empty());
|
||||
let mut home_override: Option<PathBuf> = None;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let arg = args[i].as_str();
|
||||
let next_val = |i: &mut usize, flag: &str| -> Result<String, String> {
|
||||
*i += 1;
|
||||
args.get(*i).cloned().ok_or_else(|| format!("missing value for {flag}"))
|
||||
};
|
||||
if arg == "--web" {
|
||||
i += 1;
|
||||
continue;
|
||||
} else if arg == "--host" {
|
||||
host = next_val(&mut i, "--host")?;
|
||||
} else if let Some(v) = arg.strip_prefix("--host=") {
|
||||
host = v.to_owned();
|
||||
} else if arg == "--port" || arg == "-p" {
|
||||
let v = next_val(&mut i, arg)?;
|
||||
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
|
||||
} else if let Some(v) = arg.strip_prefix("--port=") {
|
||||
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
|
||||
} else if arg == "--base-path" {
|
||||
base_path = Some(next_val(&mut i, "--base-path")?);
|
||||
} else if let Some(v) = arg.strip_prefix("--base-path=") {
|
||||
base_path = Some(v.to_owned());
|
||||
} else if arg == "--web-dir" {
|
||||
web_dir = PathBuf::from(next_val(&mut i, "--web-dir")?);
|
||||
} else if let Some(v) = arg.strip_prefix("--web-dir=") {
|
||||
web_dir = PathBuf::from(v);
|
||||
} else if arg == "--project" || arg == "--workspace" {
|
||||
project = Some(PathBuf::from(next_val(&mut i, arg)?));
|
||||
} else if let Some(v) = arg.strip_prefix("--project=").or_else(|| arg.strip_prefix("--workspace=")) {
|
||||
project = Some(PathBuf::from(v));
|
||||
} else if arg == "--home" {
|
||||
home_override = Some(PathBuf::from(next_val(&mut i, "--home")?));
|
||||
} else if let Some(v) = arg.strip_prefix("--home=") {
|
||||
home_override = Some(PathBuf::from(v));
|
||||
} else if arg == "--token" {
|
||||
auth_token = Some(next_val(&mut i, "--token")?);
|
||||
no_auth = false;
|
||||
} else if let Some(v) = arg.strip_prefix("--token=") {
|
||||
auth_token = Some(v.to_owned());
|
||||
no_auth = false;
|
||||
} else if arg == "--no-auth" {
|
||||
auth_token = None;
|
||||
no_auth = true;
|
||||
} else if arg == "--no-trust-project" {
|
||||
trust_project = false;
|
||||
} else if arg.starts_with('-') {
|
||||
return Err(format!("unknown option: {arg}"));
|
||||
} else if project.is_none() {
|
||||
project = Some(PathBuf::from(arg));
|
||||
} else {
|
||||
return Err(format!("unexpected positional argument: {arg}"));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if no_auth {
|
||||
auth_token = None;
|
||||
} else if auth_token.is_none() || auth_token.as_deref() == Some("auto") {
|
||||
auth_token = Some(web_server::generate_token());
|
||||
}
|
||||
|
||||
Ok(ParsedWebArgs {
|
||||
config: WebServerConfig { host, port, base_path, web_dir, project, trust_project, auth_token },
|
||||
home_override,
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let raw_args: Vec<String> = std::env::args().collect();
|
||||
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
|
||||
@@ -28,6 +153,10 @@ fn main() {
|
||||
println!("openidea-server {} (protocol {})", env!("CARGO_PKG_VERSION"), rpc::PROTOCOL_VERSION);
|
||||
return;
|
||||
}
|
||||
if args.iter().any(|a| a == "--help" || a == "-h") {
|
||||
print_usage();
|
||||
return;
|
||||
}
|
||||
if args.first().is_some_and(|a| a == "--connect") {
|
||||
// One forwarded connection (see `ide_host::relay`): stdout carries its bytes.
|
||||
let code = match ide_host::relay::parse_args(&args[1..]).and_then(|(host, port)| {
|
||||
@@ -42,24 +171,57 @@ fn main() {
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
let base = server_home();
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
|
||||
std::process::exit(2);
|
||||
};
|
||||
// `--replace`: stop another build's backend that still holds the project.
|
||||
let replace = args.get(2).is_some_and(|a| a == "--replace");
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let code = match ide_host::daemon::attach(
|
||||
&base,
|
||||
&home,
|
||||
project_path,
|
||||
replace,
|
||||
std::io::stdin(),
|
||||
std::io::stdout().lock(),
|
||||
) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
if args.iter().any(|a| a == "--web") {
|
||||
let parsed = match parse_web_args(&args) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
init_tracing();
|
||||
let base = parsed.home_override.unwrap_or(base);
|
||||
init_process_env(&base);
|
||||
let worker_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2).clamp(2, 8);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(worker_threads)
|
||||
.max_blocking_threads(32)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio runtime");
|
||||
let code = runtime.block_on(web_server::run(parsed.config, base));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
let mode = match args.as_slice() {
|
||||
#[cfg(unix)]
|
||||
[flag, sock, build] if flag == "--daemon" => {
|
||||
@@ -73,27 +235,33 @@ fn main() {
|
||||
[flag, _] if flag == "--attach" => Mode::Stdio,
|
||||
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
|
||||
_ => {
|
||||
eprintln!(
|
||||
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
|
||||
);
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// stdout carries the protocol: logs go to stderr.
|
||||
init_tracing();
|
||||
init_process_env(&base);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
// stdout carries the protocol in --stdio mode: logs always go to stderr.
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
|
||||
.init();
|
||||
// An SSH exec channel gets a minimal environment: take the login shell's, read
|
||||
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
|
||||
}
|
||||
|
||||
fn init_process_env(base: &std::path::Path) {
|
||||
// An SSH exec channel or container entrypoint gets a minimal environment: inherit login shell
|
||||
// env plus IDE-managed tools before any other thread starts.
|
||||
ide_host::shell_env::inherit_login_shell_env("openidea-server");
|
||||
let data_dir = base.join("data");
|
||||
ide_tools::extend_process_path(&data_dir);
|
||||
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
|
||||
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn server_home() -> PathBuf {
|
||||
|
||||
@@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket.
|
||||
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
|
||||
/// refuses to retire is stopped first.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
@@ -137,11 +139,11 @@ pub fn attach(
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
@@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<Unix
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
match existing_daemon(paths, build) {
|
||||
Ok(Some(stream)) => return Ok(stream),
|
||||
Ok(None) => {}
|
||||
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
@@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
@@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
|
||||
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
|
||||
fn stop_daemon(socket: &Path) -> Result<(), String> {
|
||||
let pids = daemon_pids(socket)?;
|
||||
if pids.is_empty() {
|
||||
return Err(format!("cannot find the backend serving {}", socket.display()));
|
||||
}
|
||||
let signal = |sig| {
|
||||
for pid in &pids {
|
||||
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
|
||||
let _ = rustix::process::kill_process(pid, sig);
|
||||
}
|
||||
}
|
||||
};
|
||||
let alive = || pids.iter().any(|pid| process_exists(*pid));
|
||||
signal(rustix::process::Signal::TERM);
|
||||
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
|
||||
while alive() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if alive() {
|
||||
signal(rustix::process::Signal::KILL);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
|
||||
fn process_exists(pid: i32) -> bool {
|
||||
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
Command::new("ps")
|
||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
||||
.output()
|
||||
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
|
||||
}
|
||||
|
||||
/// Processes started as `openidea-server --daemon <socket> <build>`.
|
||||
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
|
||||
let out = Command::new("ps")
|
||||
.args(["-axww", "-o", "pid=", "-o", "args="])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot list processes: {e}"))?;
|
||||
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
|
||||
ps.lines()
|
||||
.filter_map(|line| {
|
||||
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
|
||||
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
|
||||
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
@@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool {
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::daemon_pids_in;
|
||||
|
||||
#[test]
|
||||
fn finds_the_daemon_of_a_socket_in_the_process_list() {
|
||||
let ps = " 1 /sbin/init\n\
|
||||
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
|
||||
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
|
||||
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
|
||||
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
|
||||
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
|
||||
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ mod formatter;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
pub mod menu;
|
||||
pub mod notebook;
|
||||
pub mod ops;
|
||||
mod phpstan;
|
||||
@@ -26,6 +27,7 @@ mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
pub mod web_server;
|
||||
|
||||
pub use project::{Project, history_retention};
|
||||
|
||||
@@ -378,6 +380,7 @@ impl Host {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
@@ -385,10 +388,12 @@ impl Host {
|
||||
// After the cancels: a capture or open still running then discards what it registers.
|
||||
ops::heap::close_window_snapshots(self, window);
|
||||
let project = self.projects.write().remove(window)?;
|
||||
if self.windows_for_root(&project.root).is_empty()
|
||||
&& let Some(plugins) = self.plugin_host()
|
||||
{
|
||||
plugins.withdraw_project_run_targets(&project.root);
|
||||
if let Some(plugins) = self.plugin_host() {
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
plugins.project_closed(&project.root, window);
|
||||
} else {
|
||||
plugins.forget_client(window);
|
||||
}
|
||||
}
|
||||
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
|
||||
project.plugin_diagnostics.close();
|
||||
|
||||
@@ -446,9 +446,15 @@ pub fn stop_run() -> Tool {
|
||||
"Stops the running command of an agent tab, the way the Run tool window's Stop does: it asks the \
|
||||
process tree to exit and, with `force`, kills it. Waits up to `timeout` milliseconds (default {STOP_TIMEOUT_MS}) \
|
||||
for it to end and returns the tab's status (`stoppedByAgent` once it ended). A process that ignores the request \
|
||||
keeps `stopping`: call again with `force`. The tab stays open with its output."
|
||||
keeps `stopping`: call again with `force`. The tab stays open with its output.
|
||||
|
||||
Pass `runId` instead of `name` to stop a run `execute_run_configuration` started and left running; the result is \
|
||||
its `state` (`stopped` or `stopping`) and `exitCode` when it has one."
|
||||
),
|
||||
|call| async move {
|
||||
if let Some(id) = call.opt_i64("runId")? {
|
||||
return stop_configuration_run(&call, id).await;
|
||||
}
|
||||
let run = find(&call)?;
|
||||
let id = run.live_process().ok_or_else(|| IdeError::invalid(format!("`{}` is not running", run.name)))?;
|
||||
let force = call.flag("force", false)?;
|
||||
@@ -467,11 +473,48 @@ keeps `stopping`: call again with `force`. The tab stays open with its output."
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.param(Param::required("name", ParamType::String, NAME))
|
||||
.param(Param::optional("name", ParamType::String, NAME))
|
||||
.param(Param::optional("runId", ParamType::Integer, "`runId` from `execute_run_configuration`, instead of `name`"))
|
||||
.param(Param::optional("force", ParamType::Boolean, "Kill the process tree instead of asking it to exit"))
|
||||
.param(Param::optional("timeout", ParamType::Integer, "Milliseconds to wait for the command to end"))
|
||||
}
|
||||
|
||||
/// `stop_run` for a run `execute_run_configuration` started (#6127).
|
||||
async fn stop_configuration_run(call: &Call, raw: i64) -> IdeResult<Output> {
|
||||
use super::configs::{forget_started, run_exit, started_by_mcp, wait_exit};
|
||||
if call.opt_str("name")?.is_some() {
|
||||
return Err(IdeError::invalid("pass either `name` or `runId`, not both"));
|
||||
}
|
||||
let id = u32::try_from(raw)
|
||||
.ok()
|
||||
.map(ide_core::RunId)
|
||||
.filter(|id| started_by_mcp(*id))
|
||||
.ok_or_else(|| IdeError::not_found(format!("no run {raw} started by execute_run_configuration")))?;
|
||||
let host = call.host();
|
||||
let deadline = std::time::Instant::now() + timeout(call, STOP_TIMEOUT_MS)?;
|
||||
let exit = match run_exit(&host, id) {
|
||||
Some(exit) => Some(exit),
|
||||
None => {
|
||||
crate::ops::run::run_stop(&host, call.window(), id)?;
|
||||
if call.flag("force", false)? {
|
||||
// A second Stop kills the tree.
|
||||
crate::ops::run::run_stop(&host, call.window(), id)?;
|
||||
}
|
||||
wait_exit(call, id, Some(deadline)).await?
|
||||
}
|
||||
};
|
||||
if exit.is_some() {
|
||||
forget_started(id);
|
||||
}
|
||||
let mut out = Map::new();
|
||||
out.insert("runId".into(), id.0.into());
|
||||
out.insert("state".into(), if exit.is_some() { "stopped" } else { "stopping" }.into());
|
||||
if let Some(Some(code)) = exit {
|
||||
out.insert("exitCode".into(), code.into());
|
||||
}
|
||||
Output::json(Value::Object(out))
|
||||
}
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![run_command(), wait_for_run(), read_run_output(), get_run_status(), send_run_input(), stop_run(), list_runs()]
|
||||
}
|
||||
|
||||
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DEFAULT_TIMEOUT_MS: usize = 10_000;
|
||||
@@ -281,7 +282,19 @@ workingDirectory, envs).",
|
||||
}
|
||||
|
||||
/// Polls how run `id` ended: `None` while running, else its exit code (if known).
|
||||
fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
/// The runs `execute_run_configuration` started: `stop_run` takes their `runId`, and only theirs,
|
||||
/// not the user's own runs.
|
||||
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
|
||||
|
||||
pub(super) fn started_by_mcp(id: RunId) -> bool {
|
||||
STARTED.lock().contains(&id)
|
||||
}
|
||||
|
||||
pub(super) fn forget_started(id: RunId) {
|
||||
STARTED.lock().remove(&id);
|
||||
}
|
||||
|
||||
pub(super) fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
match host.processes.exit_code(id) {
|
||||
Ok(exit) => exit,
|
||||
// Remote (SSH) runs, or a finished run already forgotten: the run list knows whether it runs.
|
||||
@@ -294,7 +307,7 @@ fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
|
||||
/// Waits for run `id` to exit, until `deadline`: `None` when it is still running. Cancelling
|
||||
/// the call stops the run.
|
||||
async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
|
||||
pub(super) async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
|
||||
let host = call.host();
|
||||
loop {
|
||||
if let Some(exit) = run_exit(&host, id) {
|
||||
@@ -741,7 +754,8 @@ Behavior:
|
||||
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
|
||||
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
|
||||
tool window; output files are private and deleted after a day.",
|
||||
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
|
||||
and deleted after a day.",
|
||||
|call| async move {
|
||||
let target = execution_target(
|
||||
call.opt_str("configurationName")?,
|
||||
@@ -807,14 +821,24 @@ one by one",
|
||||
}
|
||||
};
|
||||
|
||||
STARTED.lock().insert(info.id);
|
||||
let exit = match limit {
|
||||
Some(limit) if !limit.is_zero() => wait_exit(&call, info.id, Some(Instant::now() + limit)).await?,
|
||||
_ => None,
|
||||
};
|
||||
if exit.is_some() {
|
||||
STARTED.lock().remove(&info.id);
|
||||
}
|
||||
let c = collector.lock();
|
||||
let mut result = Map::new();
|
||||
if let Some(Some(code)) = exit {
|
||||
result.insert("exitCode".into(), code.into());
|
||||
match exit {
|
||||
Some(Some(code)) => {
|
||||
result.insert("exitCode".into(), code.into());
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
result.insert("runId".into(), info.id.0.into());
|
||||
}
|
||||
}
|
||||
result.insert("output".into(), c.preview().into());
|
||||
// An exited run whose whole output is in `output` needs no file.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -281,6 +281,21 @@ pub async fn agent_import_session(
|
||||
blocking(move || agents.import_session(&provider, &session_id)).await
|
||||
}
|
||||
|
||||
/// Forks a recorded external session into a new task: its first turn continues the recording
|
||||
/// as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_fork_session(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
session_id: String,
|
||||
cwd: String,
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
blocking(move || agents.fork_session(&provider, &session_id, std::path::Path::new(&cwd))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1445,6 +1460,7 @@ ide_command::domain!(
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
|
||||
@@ -32,12 +32,20 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let executor = take_executor(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
let agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for(java_exec.as_deref())
|
||||
let mut agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for_executor(java_exec.as_deref(), executor.as_deref())
|
||||
} else {
|
||||
Default::default()
|
||||
ide_run::java_agent::Agents::default()
|
||||
};
|
||||
match enhanced {
|
||||
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
|
||||
Some(Err(note)) => agents.notes.push(note),
|
||||
None => {}
|
||||
}
|
||||
let config = add_java_agents(config, &agents.options);
|
||||
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
@@ -249,6 +257,34 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
|
||||
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
|
||||
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
|
||||
/// console line saying why the session runs without it.
|
||||
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
(on && is_jvm_launch(config))
|
||||
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
|
||||
}
|
||||
|
||||
/// The plugin executor the session launches through (`executor` in the launch extras, which
|
||||
/// this removes): its plugin's executor-bound Java agent loads only then.
|
||||
fn take_executor(config: &mut LaunchConfig) -> Option<String> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let executor = extra.remove("executor")?;
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
executor.as_str().filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
@@ -380,13 +416,25 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
|
||||
config
|
||||
}
|
||||
|
||||
/// This window's breakpoints of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_breakpoints(path, breakpoints).await
|
||||
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of this window's line breakpoints with `files`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_replace_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.replace_breakpoints(host.owner_window(window), files).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -629,18 +677,20 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_function_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_function_breakpoints(breakpoints).await
|
||||
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
/// Field watchpoints; states aligned with `breakpoints`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_data_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_data_breakpoints(breakpoints).await
|
||||
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -916,6 +966,64 @@ mod tests {
|
||||
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = |name: &str, implementor: &str| {
|
||||
let home = tmp.path().join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
home.join("bin/java").to_string_lossy().into_owned()
|
||||
};
|
||||
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let mut config = launch(
|
||||
"java-debug",
|
||||
"launch",
|
||||
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
|
||||
);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
|
||||
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
|
||||
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
|
||||
|
||||
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
|
||||
for (adapter, request, extra) in [
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
|
||||
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
|
||||
] {
|
||||
let mut config = launch(adapter, request, extra);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), None);
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_executor_is_taken_out_of_the_launch_extras() {
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g", "executor": "acme.reload"}));
|
||||
assert_eq!(take_executor(&mut config).as_deref(), Some("acme.reload"));
|
||||
assert!(extras(&config).get("executor").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
let mut plain = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"}));
|
||||
assert_eq!(take_executor(&mut plain), None);
|
||||
assert_eq!(extras(&plain)["vmArgs"], "-Xmx1g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_server_port_only_for_local_java_debug() {
|
||||
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
|
||||
@@ -962,6 +1070,7 @@ ide_command::domain!(
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
debug_restart_frame,
|
||||
debug_resume,
|
||||
|
||||
@@ -81,8 +81,8 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
/// visibility and type-alias kinds), tree-sitter otherwise.
|
||||
/// Tree-sitter answers come from the per-document tree cache (incremental
|
||||
/// re-parse); large documents get no syntax structure.
|
||||
/// Normal files reuse the per-document tree cache. Large Markdown files use
|
||||
/// the syntax parser's size limit for heading outlines.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<OutlineItem>> {
|
||||
let project = host.project(window)?;
|
||||
@@ -118,7 +118,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large => Vec::new(),
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -69,16 +69,15 @@ pub(crate) async fn resolve_launch(
|
||||
progress("Resolving the module");
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
let scope = std::sync::Arc::new({
|
||||
let (project, module) = (project.clone(), module.clone());
|
||||
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
});
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
@@ -110,6 +109,10 @@ pub(crate) async fn resolve_launch(
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
// A dependency-only POM has no Java project in jdtls, but is a valid launch classpath.
|
||||
if is_maven_aggregator(&scope.root, &model, &module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
@@ -383,6 +386,10 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module && p.packaging == "pom"))
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
@@ -418,31 +425,32 @@ fn gradle_served(settings: &Settings) -> bool {
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
/// Dependency-only Maven POMs also use this path, without querying a Java language server.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
scope: workspace::Scope,
|
||||
scope: std::sync::Arc<workspace::Scope>,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built, by_service) = {
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
if policy == BuildPolicy::NoBuild && !aggregator {
|
||||
return (model, None, false);
|
||||
}
|
||||
if served_by_service(&scope.root, &model, &scope.settings, &module)
|
||||
@@ -455,7 +463,7 @@ async fn resolve_launch_without_jdtls(
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
Some(kind),
|
||||
(policy != BuildPolicy::NoBuild).then_some(kind),
|
||||
&cancel,
|
||||
&on_event,
|
||||
) {
|
||||
@@ -467,6 +475,9 @@ async fn resolve_launch_without_jdtls(
|
||||
Err(e) => return (model, Some(Err(e)), false),
|
||||
}
|
||||
}
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
return (model, None, false);
|
||||
}
|
||||
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
|
||||
(model, Some(built), false)
|
||||
})
|
||||
@@ -486,14 +497,17 @@ async fn resolve_launch_without_jdtls(
|
||||
)));
|
||||
}
|
||||
Some(Ok(built)) => {
|
||||
info.build = Some(match built.failure {
|
||||
let status = match built.failure {
|
||||
None => JavaBuildStatus::Succeeded,
|
||||
Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => {
|
||||
info.hints.push(failure);
|
||||
JavaBuildStatus::Failed
|
||||
}
|
||||
Some(failure) => return Err(IdeError::internal(failure)),
|
||||
});
|
||||
};
|
||||
if policy != BuildPolicy::NoBuild {
|
||||
info.build = Some(status);
|
||||
}
|
||||
class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned()));
|
||||
}
|
||||
}
|
||||
@@ -501,7 +515,8 @@ async fn resolve_launch_without_jdtls(
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
}
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
|
||||
let from_server = if aggregator { None } else { project.lsp.java_server_classpath(&module, test, cancel).await? };
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -527,7 +542,11 @@ async fn resolve_launch_without_jdtls(
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
|
||||
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
|
||||
} else {
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
|
||||
};
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
|
||||
@@ -2292,6 +2292,7 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let generation = project.lsp.injection_generation();
|
||||
let root = project.root.clone();
|
||||
blocking(move || {
|
||||
let d = ProviderDocument {
|
||||
path: snap.path.0,
|
||||
@@ -2311,8 +2312,8 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
|
||||
{
|
||||
out.injections = plugins.provide_injections(&d);
|
||||
out.colors = plugins.language_colors(&d);
|
||||
out.gutter_actions = plugins.language_gutter_actions(&d);
|
||||
out.hover_actions = plugins.language_hover_actions(&d);
|
||||
out.gutter_actions = plugins.language_gutter_actions(&d, Some(&root));
|
||||
out.hover_actions = plugins.language_hover_actions(&d, Some(&root));
|
||||
}
|
||||
project.lsp.set_injections_at(
|
||||
doc,
|
||||
|
||||
@@ -282,6 +282,36 @@ fn refresh_workspace(project: &Project) {
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
}
|
||||
|
||||
/// Records `project` in `recent` (its branch, unless attached to a workspace, and display name).
|
||||
pub fn record_recent(recent: &ide_workspace::RecentProjects, project: &Project) -> IdeResult<()> {
|
||||
let info = info(project);
|
||||
let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root));
|
||||
let branch = if attached {
|
||||
None
|
||||
} else {
|
||||
project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head)
|
||||
};
|
||||
recent.touch(&project.root, branch)?;
|
||||
recent.rename(&project.root, Some(&info.display_name))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// File › Rename Project…: the display name of `window`'s project; an empty `name` restores the
|
||||
/// folder name. A workspace container renames the workspace, else it is stored in project settings.
|
||||
pub fn rename(host: &Host, window: &str, name: &str) -> IdeResult<Arc<Project>> {
|
||||
let project = host.project(window)?;
|
||||
let name = name.trim();
|
||||
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)?
|
||||
&& workspace.is_container(&project.root)
|
||||
{
|
||||
save_workspace(host, window, name, workspace.projects)?;
|
||||
} else {
|
||||
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
|
||||
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
|
||||
}
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
/// Attaches a trusted folder without replacing the current project.
|
||||
pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult<ide_core::IpcPath> {
|
||||
let project = host.project(window)?;
|
||||
|
||||
@@ -559,7 +559,8 @@ async fn start_inner(
|
||||
|
||||
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
|
||||
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
|
||||
/// run target gets none; the console says so, and why an approved agent was left out.
|
||||
/// run target gets none; the console says so, and why an approved agent was left out. A launch
|
||||
/// through a plugin executor (`extras.executor`) also gets that plugin's executor-bound agent.
|
||||
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
|
||||
if !ide_run::java_agent::applies(&config.kind) {
|
||||
return;
|
||||
@@ -575,7 +576,7 @@ fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_di
|
||||
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
|
||||
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
|
||||
});
|
||||
let agents = ide_run::java_agent::current_for(java.as_deref());
|
||||
let agents = ide_run::java_agent::current_for_executor(java.as_deref(), config.extras.executor.as_deref());
|
||||
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
|
||||
if run_dir.is_none() {
|
||||
if !agents.options.is_empty() {
|
||||
|
||||
@@ -30,8 +30,13 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if save {
|
||||
// An open tab's file may have changed on disk before the watcher reported it:
|
||||
// autosave keeps that change and leaves the replacement unsaved. A file opened
|
||||
// just for this was read now.
|
||||
if transient {
|
||||
docs.save(doc)?;
|
||||
} else if save {
|
||||
docs.autosave(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
}
|
||||
@@ -50,7 +55,9 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
/// Edits go through the document layer as one patch per file, so open editors
|
||||
/// update live and undo the whole file's replacements in one step. Unsaved
|
||||
/// editor buffers are replaced in place and left unsaved; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
/// are saved unless the file changed on disk meanwhile (then the replacement stays
|
||||
/// unsaved, as autosave does), and files that were not open are opened
|
||||
/// transiently, saved and closed.
|
||||
///
|
||||
/// With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
/// scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -68,6 +68,17 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn problems(&self, _client: &str, _path: Option<&Path>) -> Result<Vec<ide_plugin::FileProblems>, HostError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
/// Fork a recorded native agent session into a new task in the invoking
|
||||
/// window's project, returning the new task id (API 1.18).
|
||||
fn fork_agent_session(
|
||||
&self,
|
||||
_client: &str,
|
||||
_agent: &str,
|
||||
_session_id: &str,
|
||||
_cwd: &Path,
|
||||
) -> Result<String, HostError> {
|
||||
Err(HostError::Failed("agent fork unavailable".into()))
|
||||
}
|
||||
|
||||
/// Roots of the open projects.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
@@ -695,8 +706,11 @@ pub(super) struct Shared {
|
||||
pub(super) closed_clients: Mutex<BTreeSet<String>>,
|
||||
/// plugin → kinds subscribed at run time (kept across idle reclaim).
|
||||
pub subscriptions: Mutex<super::event_paths::Subscriptions>,
|
||||
/// Paths outside their project that plugins watch (kept across idle reclaim).
|
||||
pub(super) external_watches: super::external_watch::ExternalWatches,
|
||||
/// plugin → files it shows problems for, withdrawn when it stops.
|
||||
diagnostics: Mutex<HashMap<String, BTreeSet<PathBuf>>>,
|
||||
project_generations: Mutex<HashMap<PathBuf, u64>>,
|
||||
pub secrets: RwLock<Arc<dyn SecretStore>>,
|
||||
/// (plugin, `process:` capability) → the approved program.
|
||||
pub pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>,
|
||||
@@ -773,11 +787,35 @@ impl Shared {
|
||||
contexts: Mutex::default(),
|
||||
closed_clients: Mutex::default(),
|
||||
subscriptions: Mutex::default(),
|
||||
external_watches: Default::default(),
|
||||
diagnostics: Mutex::default(),
|
||||
project_generations: Mutex::default(),
|
||||
log_tabs: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
|
||||
let workspace = self.workspace().ok_or(HostError::Cancelled)?;
|
||||
if !workspace.projects().iter().any(|r| r == root) {
|
||||
return Err(HostError::NotFound("project is not open".into()));
|
||||
}
|
||||
let mut gens = self.project_generations.lock();
|
||||
Ok(*gens.entry(root.to_path_buf()).or_insert(1))
|
||||
}
|
||||
|
||||
pub(super) fn bump_project_generation(&self, root: &Path) -> u64 {
|
||||
let mut gens = self.project_generations.lock();
|
||||
let cur = gens.entry(root.to_path_buf()).or_insert(1);
|
||||
*cur = cur.saturating_add(1);
|
||||
*cur
|
||||
}
|
||||
|
||||
/// Moves a closed project's generation on rather than forgetting it, so a handle
|
||||
/// taken before the close stays stale if the project is opened again.
|
||||
pub(super) fn close_project_generation(&self, root: &Path) {
|
||||
self.bump_project_generation(root);
|
||||
}
|
||||
|
||||
pub(super) fn workspace(&self) -> Option<Arc<dyn PluginWorkspace>> {
|
||||
self.workspace.read().clone()
|
||||
}
|
||||
@@ -1023,6 +1061,9 @@ impl Shared {
|
||||
let _ = workspace.publish_diagnostics(plugin, &path, Vec::new());
|
||||
}
|
||||
}
|
||||
if subscriptions {
|
||||
self.external_watches.remove_plugin(plugin);
|
||||
}
|
||||
if subscriptions && self.subscriptions.lock().remove(plugin) {
|
||||
self.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
}
|
||||
@@ -1493,6 +1534,28 @@ fn failed(e: impl std::fmt::Display) -> HostError {
|
||||
HostError::Failed(e.to_string())
|
||||
}
|
||||
|
||||
/// `cwd` of `open-terminal-session-in`: a directory of the project, relative to `root`
|
||||
/// (`""` is the root), that exists and stays inside the project once symlinks are resolved.
|
||||
fn project_subdirectory(root: &Path, cwd: &str) -> Result<PathBuf, HostError> {
|
||||
let invalid = |why: &str| HostError::Invalid(format!("terminal directory {cwd:?}: {why}"));
|
||||
if cwd.len() > 4096 || cwd.contains('\0') {
|
||||
return Err(invalid("not a path"));
|
||||
}
|
||||
let relative = Path::new(cwd);
|
||||
if relative.is_absolute() || relative.has_root() {
|
||||
return Err(invalid("must be relative to the project root"));
|
||||
}
|
||||
let base = dunce::canonicalize(root).map_err(|_| invalid("the project root is gone"))?;
|
||||
let dir = dunce::canonicalize(base.join(relative)).map_err(|_| invalid("no such directory"))?;
|
||||
if !dir.starts_with(&base) {
|
||||
return Err(invalid("outside the project"));
|
||||
}
|
||||
if !dir.is_dir() {
|
||||
return Err(invalid("not a directory"));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
@@ -1561,8 +1624,13 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
fn register_run_target(&self, root: &Path, target: ide_plugin::PluginRunTarget) -> Result<(), HostError> {
|
||||
self.register_target(root, target)
|
||||
fn register_run_target(
|
||||
&self,
|
||||
root: &Path,
|
||||
target: ide_plugin::PluginRunTarget,
|
||||
generation: Option<u64>,
|
||||
) -> Result<(), HostError> {
|
||||
self.register_target(root, target, generation)
|
||||
}
|
||||
fn unregister_run_target(&self, root: &Path, id: &str) {
|
||||
self.unregister_target(root, id);
|
||||
@@ -1573,7 +1641,7 @@ impl HostApi for PluginApi {
|
||||
client: &str,
|
||||
config: &str,
|
||||
args: Vec<String>,
|
||||
debug: bool,
|
||||
options: ide_plugin::PluginRunStartOptions,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError> {
|
||||
@@ -1584,15 +1652,40 @@ impl HostApi for PluginApi {
|
||||
let mut run =
|
||||
self.shared.workspace().ok_or(HostError::Cancelled)?.run_configuration(client, self.id(), config)?;
|
||||
let binary = self.approved_program_in_project(&run.command, self.shared.project_of(client).as_deref())?;
|
||||
let user_override = !run.detected;
|
||||
let debug = options.debug;
|
||||
if debug && run.debug_adapter.is_none() {
|
||||
return Err(HostError::Invalid("this configuration has no debugger".into()));
|
||||
}
|
||||
let program = run.command.clone();
|
||||
if debug && run.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
let has_target = run.extras.target.as_ref().is_some_and(|t| !t.is_empty());
|
||||
if debug && has_target {
|
||||
return Err(HostError::Invalid("debugging this target is not supported".into()));
|
||||
}
|
||||
if debug && options.output_mode == Some(ide_plugin::PluginOutputMode::Pty) {
|
||||
return Err(HostError::Invalid("terminal emulation cannot be used when debugging".into()));
|
||||
}
|
||||
if debug {
|
||||
run.extras.emulate_terminal = false;
|
||||
run.command = binary.to_string_lossy().into_owned();
|
||||
} else {
|
||||
// Precedence: user-saved override > per-invocation override > plugin default.
|
||||
if !user_override && let Some(mode) = options.output_mode {
|
||||
run.extras.emulate_terminal = mode == ide_plugin::PluginOutputMode::Pty;
|
||||
}
|
||||
if run.extras.emulate_terminal {
|
||||
if run.is_test {
|
||||
return Err(HostError::Invalid("terminal emulation cannot be used for test configurations".into()));
|
||||
}
|
||||
if run.extras.stdin_file.is_some() {
|
||||
return Err(HostError::Invalid(
|
||||
"input cannot be redirected from a file when emulating a terminal".into(),
|
||||
));
|
||||
}
|
||||
if has_target {
|
||||
return Err(HostError::Invalid("terminal emulation on this target is not supported".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
run.args.extend(args);
|
||||
let id = self.new_operation(
|
||||
@@ -1613,6 +1706,7 @@ impl HostApi for PluginApi {
|
||||
key: String,
|
||||
title: String,
|
||||
cmd: ProcessCommand,
|
||||
cwd: Option<String>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError> {
|
||||
@@ -1623,6 +1717,11 @@ impl HostApi for PluginApi {
|
||||
if !self.shared.workspace().is_some_and(|w| w.trusted(&root)) {
|
||||
return Err(HostError::Denied("project is not trusted".into()));
|
||||
}
|
||||
// Trust and the program pin stay the project's; the directory only moves the shell.
|
||||
let dir = match &cwd {
|
||||
Some(cwd) => project_subdirectory(&root, cwd)?,
|
||||
None => root.clone(),
|
||||
};
|
||||
let binary = self.approved_program_in_project(&cmd.program, Some(&root))?;
|
||||
let mut command = StdCommand::new(&binary);
|
||||
append_process_env(&mut command, &cmd.env)?;
|
||||
@@ -1654,7 +1753,7 @@ impl HostApi for PluginApi {
|
||||
program: binary.into(),
|
||||
args: cmd.args,
|
||||
env: cmd.env.into_iter().collect(),
|
||||
cwd: root.into(),
|
||||
cwd: dir.into(),
|
||||
};
|
||||
if let Err(error) = self.window_request(client, request, cancel, timeout) {
|
||||
self.shared.operations.lock().remove(&id);
|
||||
@@ -1830,6 +1929,12 @@ impl HostApi for PluginApi {
|
||||
fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> {
|
||||
self.set_file_icon_decorations(set, items)
|
||||
}
|
||||
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
|
||||
self.shared
|
||||
.workspace()
|
||||
.ok_or_else(|| HostError::NotFound("window project".into()))?
|
||||
.fork_agent_session(client, agent, session_id, cwd)
|
||||
}
|
||||
fn console_rules(&self, rules: Vec<ide_plugin::ConsoleRule>) -> Result<(), HostError> {
|
||||
let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?;
|
||||
let mut all = self.shared.console_rules.lock();
|
||||
@@ -2196,7 +2301,10 @@ impl HostApi for PluginApi {
|
||||
|
||||
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
|
||||
let client = from_window(client, "reveal a view")?;
|
||||
let declared = self.shared.ui.items(super::ui_points::VIEWS, Some(self.id())).iter().any(|i| i.key == view);
|
||||
// A tool window comes to the front; a dialog (API 1.18) opens.
|
||||
let declared = [super::ui_points::VIEWS, super::ui_points::DIALOGS]
|
||||
.into_iter()
|
||||
.any(|point| self.shared.ui.items(point, Some(self.id())).iter().any(|i| i.key == view));
|
||||
if !declared {
|
||||
return Err(HostError::NotFound(format!("the plugin declares no view {view:?}")));
|
||||
}
|
||||
@@ -2932,14 +3040,36 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
|
||||
let filter = super::event_paths::PathFilter::new(kind, globs)?;
|
||||
fn subscribe_paths_with_options(
|
||||
&self,
|
||||
kind: &str,
|
||||
globs: Vec<String>,
|
||||
debounce_ms: Option<u32>,
|
||||
) -> Result<(), HostError> {
|
||||
let debounce = match debounce_ms {
|
||||
Some(ms) if ms > 60_000 => return Err(HostError::Invalid("debounce must not exceed 60000 ms".into())),
|
||||
Some(ms) => Some(Duration::from_millis(ms as u64)),
|
||||
None => None,
|
||||
};
|
||||
let filter = super::event_paths::PathFilter::with_debounce(kind, globs, debounce)?;
|
||||
if self.shared.subscriptions.lock().set_paths(self.id(), kind, filter) {
|
||||
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
|
||||
self.subscribe_paths_with_options(kind, globs, None)
|
||||
}
|
||||
|
||||
fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
|
||||
self.shared.project_generation(root)
|
||||
}
|
||||
|
||||
fn watch_paths(&self, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
|
||||
self.shared.external_watches.set(self.id(), client, project, paths)
|
||||
}
|
||||
|
||||
fn unsubscribe(&self, kind: &str) {
|
||||
if self.shared.subscriptions.lock().unsubscribe(self.id(), kind) {
|
||||
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
@@ -3489,6 +3619,14 @@ impl PluginWorkspace for HostWorkspace {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
|
||||
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
|
||||
let project = host.project(client).map_err(failed)?;
|
||||
project.require_trust().map_err(failed)?;
|
||||
// Scans the recorded transcripts on disk; plugin calls already run off the UI thread.
|
||||
Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id)
|
||||
}
|
||||
|
||||
fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option<String> {
|
||||
client
|
||||
.and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path))
|
||||
@@ -3850,6 +3988,29 @@ impl PluginWorkspace for HostWorkspace {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn terminal_directories_stay_inside_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(root.join("sub/deeper")).unwrap();
|
||||
std::fs::write(root.join("file.txt"), "").unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
assert_eq!(project_subdirectory(&root, "").unwrap(), root);
|
||||
assert_eq!(project_subdirectory(&root, "sub/deeper").unwrap(), root.join("sub/deeper"));
|
||||
assert_eq!(project_subdirectory(&root, "sub/../sub").unwrap(), root.join("sub"));
|
||||
for bad in ["/tmp", "../outside", "sub/../../outside", "missing", "file.txt", "a\0b"] {
|
||||
assert!(matches!(project_subdirectory(&root, bad), Err(HostError::Invalid(_))), "{bad:?}");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
|
||||
assert!(project_subdirectory(&root, "escape").is_err(), "a link out of the project");
|
||||
std::os::unix::fs::symlink(root.join("sub"), root.join("inside")).unwrap();
|
||||
assert_eq!(project_subdirectory(&root, "inside").unwrap(), root.join("sub"));
|
||||
}
|
||||
}
|
||||
|
||||
fn api(dir: &Path, pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>) -> PluginApi {
|
||||
let manifest = ide_extension::Manifest::parse(
|
||||
"id = \"acme.lint\"\nname = \"Lint\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n",
|
||||
|
||||
@@ -51,6 +51,53 @@ pub async fn plugin_run_command(
|
||||
result
|
||||
}
|
||||
|
||||
/// Run Anything entries of the plugin declaring `prefix` for the field's `text` (API 1.18).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_anything_suggest(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
prefix: String,
|
||||
text: String,
|
||||
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
host.blocking(move || plugins.run_anything_suggest(&plugin_id, &window_id, root, &prefix, &text)).await
|
||||
}
|
||||
|
||||
/// Runs a Run Anything line starting with the plugin's `prefix` (API 1.18): whether
|
||||
/// the plugin claimed it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_anything_run(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
prefix: String,
|
||||
line: String,
|
||||
) -> IdeResult<bool> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
host.blocking(move || plugins.run_anything_run(&plugin_id, &window_id, root, &prefix, &line)).await
|
||||
}
|
||||
|
||||
/// Completions for a field of a plugin's own run configuration (API 1.18).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_configuration_complete(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
config_id: String,
|
||||
field: String,
|
||||
text: String,
|
||||
caret: u32,
|
||||
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || plugins.run_configuration_complete(&window_id, &root, &config_id, &field, &text, caret)).await
|
||||
}
|
||||
|
||||
/// The UI language (BCP 47) that plugin code reads with `ui.locale()`.
|
||||
#[command(trust = always)]
|
||||
pub async fn plugin_set_ui_locale(plugins: &Arc<PluginHost>, tag: String) -> IdeResult<()> {
|
||||
@@ -316,7 +363,10 @@ ide_command::domain!(
|
||||
plugin_post_events,
|
||||
plugin_prepare_debug_run,
|
||||
plugin_program,
|
||||
plugin_run_anything_run,
|
||||
plugin_run_anything_suggest,
|
||||
plugin_run_command,
|
||||
plugin_run_configuration_complete,
|
||||
plugin_select_tests,
|
||||
plugin_set_active_file,
|
||||
plugin_set_ui_locale,
|
||||
|
||||
@@ -17,11 +17,21 @@ pub(super) struct Subscriptions {
|
||||
#[derive(Clone)]
|
||||
pub(super) struct PathFilter {
|
||||
pub globs: Vec<String>,
|
||||
pub debounce: Option<std::time::Duration>,
|
||||
matchers: Vec<GlobMatcher>,
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(kind: &str, globs: Vec<String>) -> Result<Self, HostError> {
|
||||
Self::with_debounce(kind, globs, None)
|
||||
}
|
||||
|
||||
pub fn with_debounce(
|
||||
kind: &str,
|
||||
globs: Vec<String>,
|
||||
debounce: Option<std::time::Duration>,
|
||||
) -> Result<Self, HostError> {
|
||||
if !matches!(kind, "file-opened" | "file-saved" | "files-changed" | "document-changed") {
|
||||
return Err(HostError::Invalid(
|
||||
"subscribe-paths supports file-opened, file-saved, files-changed and document-changed".into(),
|
||||
@@ -53,7 +63,7 @@ impl PathFilter {
|
||||
.compile_matcher(),
|
||||
);
|
||||
}
|
||||
Ok(Self { globs, matchers })
|
||||
Ok(Self { globs, debounce, matchers })
|
||||
}
|
||||
|
||||
pub fn matches(&self, root: &Path, path: &Path) -> bool {
|
||||
@@ -78,7 +88,7 @@ impl Subscriptions {
|
||||
changed = self.kinds.entry(plugin.to_owned()).or_default().insert(kind);
|
||||
}
|
||||
let previous = self.paths.entry(plugin.to_owned()).or_default().insert(kind.to_owned(), filter.clone());
|
||||
previous.is_none_or(|old| old.globs != filter.globs) | changed
|
||||
previous.is_none_or(|old| old.globs != filter.globs || old.debounce != filter.debounce) | changed
|
||||
}
|
||||
pub fn unsubscribe(&mut self, plugin: &str, kind: &str) -> bool {
|
||||
let removed = self.paths.get_mut(plugin).is_some_and(|filters| filters.remove(kind).is_some());
|
||||
@@ -120,6 +130,8 @@ impl PluginHost {
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let batch = ide_plugin::FilesChanged {
|
||||
project: batch.project.clone(),
|
||||
generation: batch.generation,
|
||||
created: paths(&batch.created),
|
||||
modified: paths(&batch.modified),
|
||||
removed: paths(&batch.removed),
|
||||
|
||||
@@ -244,12 +244,16 @@ impl PluginHost {
|
||||
if self.shared.client_closed(client) {
|
||||
return;
|
||||
}
|
||||
self.queues
|
||||
.lock()
|
||||
.entry((plugin.into(), Some(client.into())))
|
||||
.or_insert_with(|| EventQueue { since: Instant::now(), events: Vec::new(), files_source: None })
|
||||
.events
|
||||
.push(event);
|
||||
let now = Instant::now();
|
||||
let mut queues = self.queues.lock();
|
||||
let queue = queues.entry((plugin.into(), Some(client.into()))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
queue.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,6 +438,9 @@ fn validate_configurations(
|
||||
if let Some(cwd) = &c.cwd {
|
||||
ide_plugin::resolve_new_in_root(root, cwd).map_err(HostError::Invalid)?;
|
||||
}
|
||||
if c.test && c.output_mode == ide_plugin::PluginOutputMode::Pty {
|
||||
return Err(HostError::Invalid("test configurations cannot emulate a terminal".into()));
|
||||
}
|
||||
validate_env(&c.env)?;
|
||||
validate_debugger(c.debugger.as_ref())?;
|
||||
}
|
||||
@@ -607,6 +614,7 @@ impl PluginHost {
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
config.debug_adapter = owned.debug_adapter;
|
||||
config.extras.emulate_terminal = false;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
@@ -801,4 +809,16 @@ mod tests {
|
||||
assert!(ok(AttachChild { kind: "dotnet".into(), command_contains: Some("Worker.dll".into()) }));
|
||||
assert!(!ok(AttachChild { kind: "dotnet".into(), command_contains: Some(String::new()) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configurations_reject_pty_on_test_configurations() {
|
||||
let root = std::env::temp_dir();
|
||||
let mut c = launch(vec![], None);
|
||||
c.output_mode = ide_plugin::PluginOutputMode::Pty;
|
||||
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_ok());
|
||||
c.test = true;
|
||||
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_err());
|
||||
c.output_mode = ide_plugin::PluginOutputMode::Pipes;
|
||||
assert!(validate_configurations(&root, &[c]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Paths outside a project that a plugin watches (`events.watch-paths`, API 1.18).
|
||||
//!
|
||||
//! A watch set belongs to (plugin, project) and the window that asked for it. Every
|
||||
//! directory is watched flat (its own entries): a watched file through its parent, a
|
||||
//! watched directory through itself plus its parent (so its own removal is seen).
|
||||
//! Watcher threads only queue changes here; [`super::PluginHost::flush_events_at`]
|
||||
//! delivers them while the set, its window and its project are still current.
|
||||
use ide_core::{NullSink, ipc_path::to_ipc};
|
||||
use ide_plugin::{FilesChanged, HostError};
|
||||
use ide_vfs::{FsBatch, WatchMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ExternalWatches {
|
||||
sets: Mutex<HashMap<(String, PathBuf), WatchSet>>,
|
||||
pending: Arc<Mutex<Vec<Change>>>,
|
||||
next: AtomicU64,
|
||||
}
|
||||
|
||||
struct WatchSet {
|
||||
id: u64,
|
||||
client: String,
|
||||
_watchers: Vec<Watcher>,
|
||||
}
|
||||
|
||||
/// Changes seen by one watch set, waiting for delivery.
|
||||
pub(super) struct Change {
|
||||
pub plugin: String,
|
||||
pub client: String,
|
||||
pub project: PathBuf,
|
||||
set: u64,
|
||||
pub batch: FilesChanged,
|
||||
}
|
||||
|
||||
/// What one flat directory watch reports: entries named exactly, or all of them.
|
||||
#[derive(Default)]
|
||||
struct Wanted {
|
||||
exact: BTreeSet<PathBuf>,
|
||||
entries: bool,
|
||||
}
|
||||
|
||||
impl ExternalWatches {
|
||||
/// Replaces what `plugin` watches for `project` from window `client`.
|
||||
pub fn set(&self, plugin: &str, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
|
||||
let key = (plugin.to_owned(), project.to_path_buf());
|
||||
if paths.is_empty() {
|
||||
self.sets.lock().remove(&key);
|
||||
return Ok(());
|
||||
}
|
||||
let id = self.next.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let mut dirs: BTreeMap<PathBuf, Wanted> = BTreeMap::new();
|
||||
for path in &paths {
|
||||
if let Some(parent) = path.parent() {
|
||||
dirs.entry(parent.to_path_buf()).or_default().exact.insert(path.clone());
|
||||
}
|
||||
if path.is_dir() {
|
||||
dirs.entry(path.clone()).or_default().entries = true;
|
||||
}
|
||||
}
|
||||
let mut watchers = Vec::with_capacity(dirs.len());
|
||||
for (dir, wanted) in dirs {
|
||||
let pending = Arc::downgrade(&self.pending);
|
||||
let (plugin, client, project) = (plugin.to_owned(), client.to_owned(), project.to_path_buf());
|
||||
let watched = dir.clone();
|
||||
let on_change = Box::new(move |batch: &FsBatch| {
|
||||
let Some(pending) = pending.upgrade() else { return };
|
||||
let Some(batch) = select(&watched, &wanted, batch) else { return };
|
||||
// Drained on every event flush; bounded by the flat directories' entries.
|
||||
pending.lock().push(Change {
|
||||
plugin: plugin.clone(),
|
||||
client: client.clone(),
|
||||
project: project.clone(),
|
||||
set: id,
|
||||
batch,
|
||||
});
|
||||
});
|
||||
let watcher = Watcher::start_with(&dir, Vec::new(), Arc::new(NullSink), on_change, WatchMode::Flat)
|
||||
.map_err(|e| HostError::Failed(format!("cannot watch {}: {}", dir.display(), e.message)))?;
|
||||
watchers.push(watcher);
|
||||
}
|
||||
let set = WatchSet { id, client: client.to_owned(), _watchers: watchers };
|
||||
self.sets.lock().insert(key, set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Changes of sets still in place, oldest first; others are dropped.
|
||||
pub fn take(&self) -> Vec<Change> {
|
||||
let changes = std::mem::take(&mut *self.pending.lock());
|
||||
if changes.is_empty() {
|
||||
return changes;
|
||||
}
|
||||
let sets = self.sets.lock();
|
||||
changes
|
||||
.into_iter()
|
||||
.filter(|c| {
|
||||
sets.get(&(c.plugin.clone(), c.project.clone())).is_some_and(|s| s.id == c.set && s.client == c.client)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn remove_plugin(&self, plugin: &str) {
|
||||
self.sets.lock().retain(|(p, _), _| p != plugin);
|
||||
}
|
||||
|
||||
pub fn remove_project(&self, root: &Path) {
|
||||
self.sets.lock().retain(|(_, project), _| project != root);
|
||||
}
|
||||
|
||||
pub fn remove_client(&self, client: &str) {
|
||||
self.sets.lock().retain(|_, set| set.client != client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `batch` (from the flat watch on `dir`) the set asked for. Ignored
|
||||
/// files are reported too: as modified while they exist, removed once they don't.
|
||||
fn select(dir: &Path, wanted: &Wanted, batch: &FsBatch) -> Option<FilesChanged> {
|
||||
let keep = |path: &&PathBuf| wanted.exact.contains(*path) || (wanted.entries && path.parent() == Some(dir));
|
||||
let ipc = |paths: Vec<&PathBuf>| paths.into_iter().map(|p| to_ipc(p)).collect::<Vec<_>>();
|
||||
let mut modified: Vec<&PathBuf> = batch.modified.iter().filter(keep).collect();
|
||||
let mut removed: Vec<&PathBuf> = batch.removed.iter().filter(keep).collect();
|
||||
for path in batch.ignored.iter().filter(keep) {
|
||||
if path.symlink_metadata().is_ok() { modified.push(path) } else { removed.push(path) }
|
||||
}
|
||||
let changes = FilesChanged {
|
||||
project: None,
|
||||
generation: None,
|
||||
created: ipc(batch.created.iter().filter(keep).collect()),
|
||||
modified: ipc(modified),
|
||||
removed: ipc(removed),
|
||||
};
|
||||
(!changes.created.is_empty() || !changes.modified.is_empty() || !changes.removed.is_empty()).then_some(changes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn batch(created: &[&Path], modified: &[&Path], removed: &[&Path], ignored: &[&Path]) -> FsBatch {
|
||||
let v = |p: &[&Path]| p.iter().map(|p| p.to_path_buf()).collect();
|
||||
FsBatch {
|
||||
created: v(created),
|
||||
modified: v(modified),
|
||||
removed: v(removed),
|
||||
ignored: v(ignored),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_watch_reports_only_what_the_set_names() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let (file, other, kept) = (dir.join("Taskfile.yml"), dir.join("other.yml"), dir.join("kept.yml"));
|
||||
std::fs::write(&kept, "").unwrap();
|
||||
let exact = Wanted { exact: [file.clone()].into(), entries: false };
|
||||
let got = select(dir, &exact, &batch(&[&file], &[&other], &[], &[&kept])).unwrap();
|
||||
assert_eq!(got.created, vec![to_ipc(&file)]);
|
||||
assert!(got.modified.is_empty() && got.removed.is_empty());
|
||||
assert!(select(dir, &exact, &batch(&[], &[&other], &[], &[])).is_none());
|
||||
|
||||
let nested = dir.join("sub").join("deep.yml");
|
||||
let entries = Wanted { exact: BTreeSet::new(), entries: true };
|
||||
let gone = dir.join("gone.yml");
|
||||
let got = select(dir, &entries, &batch(&[&nested], &[&other], &[], &[&kept, &gone])).unwrap();
|
||||
assert!(got.created.is_empty(), "entries below the directory are not watched");
|
||||
assert_eq!(got.modified, vec![to_ipc(&other), to_ipc(&kept)]);
|
||||
assert_eq!(got.removed, vec![to_ipc(&gone)]);
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,21 @@ pub(super) fn retain_live(events: &mut Vec<WorkbenchEvent>, source: Option<&Sour
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues `incoming`, folding a filesystem batch into the queued one it continues:
|
||||
/// the project batch, or the watched-paths batch of the same project.
|
||||
pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEvent>) {
|
||||
for event in incoming {
|
||||
if let WorkbenchEvent::FilesChanged(batch) = &event
|
||||
&& let Some(WorkbenchEvent::FilesChanged(previous)) =
|
||||
events.iter_mut().find(|e| matches!(e, WorkbenchEvent::FilesChanged(_)))
|
||||
let previous = events.iter_mut().find_map(|queued| match (queued, &event) {
|
||||
(WorkbenchEvent::FilesChanged(previous), WorkbenchEvent::FilesChanged(_)) => Some(previous),
|
||||
(WorkbenchEvent::WatchedFilesChanged(previous), WorkbenchEvent::WatchedFilesChanged(batch))
|
||||
if previous.project == batch.project =>
|
||||
{
|
||||
Some(previous)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
if let (WorkbenchEvent::FilesChanged(batch) | WorkbenchEvent::WatchedFilesChanged(batch), Some(previous)) =
|
||||
(&event, previous)
|
||||
{
|
||||
use std::collections::BTreeMap;
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -61,7 +71,9 @@ pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEv
|
||||
paths.insert(path.clone(), kind);
|
||||
}
|
||||
}
|
||||
*previous = FilesChanged::default();
|
||||
let project = batch.project.clone().or_else(|| previous.project.clone());
|
||||
let generation = batch.generation.or(previous.generation);
|
||||
*previous = FilesChanged { project, generation, ..Default::default() };
|
||||
for (path, kind) in paths {
|
||||
match kind {
|
||||
Created => previous.created.push(path),
|
||||
@@ -88,14 +100,15 @@ impl PluginHost {
|
||||
}
|
||||
let paths =
|
||||
|paths: &[PathBuf]| paths.iter().filter(|p| p.starts_with(root)).map(|p| to_ipc(p)).collect::<Vec<_>>();
|
||||
let batch = FilesChanged {
|
||||
created: paths(&batch.created),
|
||||
modified: paths(&batch.modified),
|
||||
removed: paths(&batch.removed),
|
||||
};
|
||||
if batch.created.is_empty() && batch.modified.is_empty() && batch.removed.is_empty() {
|
||||
let created = paths(&batch.created);
|
||||
let modified = paths(&batch.modified);
|
||||
let removed = paths(&batch.removed);
|
||||
if created.is_empty() && modified.is_empty() && removed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let generation = self.shared.bump_project_generation(root);
|
||||
let batch =
|
||||
FilesChanged { project: Some(to_ipc(root)), generation: Some(generation), created, modified, removed };
|
||||
self.post_events_from(
|
||||
Some(client),
|
||||
vec![WorkbenchEvent::FilesChanged(batch)],
|
||||
@@ -189,7 +202,15 @@ mod tests {
|
||||
let queues = host.queues.lock();
|
||||
let queue = queues.values().next().expect("new session queue");
|
||||
assert!(queue.files_source.as_ref().unwrap().same(&Source { active: Arc::downgrade(&new) }));
|
||||
assert_eq!(queue.events, [delta(0, &to_ipc(&root.join("new.rs")))]);
|
||||
assert_eq!(
|
||||
queue.events,
|
||||
[WorkbenchEvent::FilesChanged(FilesChanged {
|
||||
project: Some(to_ipc(&root)),
|
||||
generation: Some(2),
|
||||
created: vec![to_ipc(&root.join("new.rs"))],
|
||||
..Default::default()
|
||||
})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -291,6 +312,7 @@ mod tests {
|
||||
created: vec![to_ipc(&root.join("config/a.yaml")), to_ipc(&root.join("src/a.rs"))],
|
||||
modified: vec![to_ipc(&root.join("config/b.yaml"))],
|
||||
removed: vec![to_ipc(&root.join("config/c.yaml"))],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
host.flush_events();
|
||||
@@ -306,6 +328,7 @@ mod tests {
|
||||
created: vec![to_ipc(&root.join("config/a.yaml"))],
|
||||
modified: vec![to_ipc(&root.join("config/b.yaml"))],
|
||||
removed: vec![to_ipc(&root.join("config/c.yaml"))],
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
} else {
|
||||
@@ -437,6 +460,7 @@ mod tests {
|
||||
PendingFiles {
|
||||
queue: super::super::EventQueue {
|
||||
since: std::time::Instant::now(),
|
||||
last_event: std::time::Instant::now(),
|
||||
events: vec![delta(0, "/project/new")],
|
||||
files_source: None,
|
||||
},
|
||||
@@ -475,6 +499,7 @@ mod tests {
|
||||
created: vec![format!("/project/{i}")],
|
||||
modified: vec!["/project/shared".into()],
|
||||
removed: vec!["/project/gone".into()],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
}
|
||||
@@ -616,7 +641,15 @@ mod tests {
|
||||
};
|
||||
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
|
||||
let received: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
|
||||
assert_eq!(received, [FilesChanged { created: vec![to_ipc(&root.join("new.rs"))], ..Default::default() }]);
|
||||
assert_eq!(
|
||||
received,
|
||||
[FilesChanged {
|
||||
project: Some(to_ipc(&root)),
|
||||
generation: Some(3),
|
||||
created: vec![to_ipc(&root.join("new.rs"))],
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn queued_filter_replacement_and_pause_do_not_activate() {
|
||||
@@ -656,4 +689,226 @@ mod tests {
|
||||
host.post_files_changed("main", &root, &active, &batch);
|
||||
assert!(host.queues.lock().is_empty(), "paused paths never queue work");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_changed_debounce_coalesces_bursts_of_edits_without_repeated_delivery() {
|
||||
use super::super::event_paths::PathFilter;
|
||||
use std::time::Duration;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let host = files_changed_host(&root);
|
||||
host.shared.subscriptions.lock().set_paths(
|
||||
"files-events",
|
||||
"files-changed",
|
||||
PathFilter::with_debounce("files-changed", vec!["**/*".into()], Some(Duration::from_millis(80))).unwrap(),
|
||||
);
|
||||
|
||||
let active = Arc::new(AtomicBool::new(true));
|
||||
// Post 3 bursts of file changes quickly within debounce window
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { created: vec![root.join("file1.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "first change must be debounced, not delivered immediately");
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { modified: vec![root.join("file2.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "second change within debounce window resets debounce");
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { removed: vec![root.join("file3.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "third change still debouncing");
|
||||
|
||||
// Wait until debounce expires (> 80 ms since last event)
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
host.flush_events();
|
||||
assert!(host.wait_events(Duration::from_secs(5)));
|
||||
|
||||
let inv = ide_plugin::Invocation {
|
||||
client: Some("main".into()),
|
||||
workspace_root: Some(root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
|
||||
let batches: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
|
||||
assert_eq!(batches.len(), 1, "rapid edit bursts must coalesce into exactly 1 batch");
|
||||
assert_eq!(batches[0].created, [to_ipc(&root.join("file1.rs"))]);
|
||||
assert_eq!(batches[0].modified, [to_ipc(&root.join("file2.rs"))]);
|
||||
assert_eq!(batches[0].removed, [to_ipc(&root.join("file3.rs"))]);
|
||||
assert_eq!(host.shared.project_generation(&root).unwrap(), 4);
|
||||
}
|
||||
|
||||
struct MultiWorkspace(std::sync::Mutex<Vec<PathBuf>>);
|
||||
impl super::super::PluginWorkspace for MultiWorkspace {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(
|
||||
&self,
|
||||
_: &Path,
|
||||
_: u64,
|
||||
_: &[ide_core::TextEdit],
|
||||
_: bool,
|
||||
) -> Result<u64, ide_plugin::HostError> {
|
||||
unreachable!()
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf> {
|
||||
let projects = self.0.lock().unwrap();
|
||||
match window {
|
||||
"main" => projects.first().cloned(),
|
||||
"other" => projects.get(1).cloned(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn publish_diagnostics(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &Path,
|
||||
_: Vec<ide_core::Diagnostic>,
|
||||
) -> Result<(), ide_plugin::HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_run_target_registration_rejected_after_generation_bump() {
|
||||
use ide_plugin::HostError;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let host = files_changed_host(&root);
|
||||
let dummy = root.join("dummy");
|
||||
std::fs::write(&dummy, b"dummy").unwrap();
|
||||
host.shared.pins.write().insert(
|
||||
("files-events".into(), "process:dummy".into()),
|
||||
ide_language::ProgramPin::approve(&dummy).unwrap(),
|
||||
);
|
||||
let plugin = host.get("files-events").unwrap();
|
||||
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
|
||||
|
||||
let target = ide_plugin::PluginRunTarget {
|
||||
id: "target-1".into(),
|
||||
name: "Target 1".into(),
|
||||
program: "dummy".into(),
|
||||
args: vec!["test".into()],
|
||||
workdir_args: vec![],
|
||||
container_root: None,
|
||||
commands: vec![],
|
||||
};
|
||||
|
||||
// Generation starts at 1
|
||||
let gen1 = host.shared.project_generation(&root).unwrap();
|
||||
assert_eq!(gen1, 1);
|
||||
|
||||
// Registering with matching generation succeeds
|
||||
assert!(api.register_target(&root, target.clone(), Some(gen1)).is_ok());
|
||||
|
||||
// Bump generation (simulating filesystem change or manual bump)
|
||||
let gen2 = host.shared.bump_project_generation(&root);
|
||||
assert_eq!(gen2, 2);
|
||||
|
||||
// Registering with old generation is rejected with Stale
|
||||
let err = api.register_target(&root, target.clone(), Some(gen1)).unwrap_err();
|
||||
assert!(matches!(err, HostError::Stale));
|
||||
|
||||
// Registering with new generation succeeds
|
||||
assert!(api.register_target(&root, target, Some(gen2)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_isolation_and_project_closed_lifecycle() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root_a = dunce::canonicalize(tmp.path()).unwrap().join("project_a");
|
||||
let root_b = dunce::canonicalize(tmp.path()).unwrap().join("project_b");
|
||||
std::fs::create_dir_all(&root_a).unwrap();
|
||||
std::fs::create_dir_all(&root_b).unwrap();
|
||||
let host = files_changed_host(&root_a);
|
||||
let ws = Arc::new(MultiWorkspace(std::sync::Mutex::new(vec![root_a.clone(), root_b.clone()])));
|
||||
host.set_workspace(Some(ws.clone()));
|
||||
|
||||
let dummy = tmp.path().join("dummy");
|
||||
std::fs::write(&dummy, b"dummy").unwrap();
|
||||
host.shared.pins.write().insert(
|
||||
("files-events".into(), "process:dummy".into()),
|
||||
ide_language::ProgramPin::approve(&dummy).unwrap(),
|
||||
);
|
||||
let plugin = host.get("files-events").unwrap();
|
||||
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
|
||||
|
||||
let active_a = Arc::new(AtomicBool::new(true));
|
||||
let active_b = Arc::new(AtomicBool::new(true));
|
||||
|
||||
// Post changes to Project A and B
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root_a,
|
||||
&active_a,
|
||||
&ide_vfs::FsBatch { created: vec![root_a.join("a.rs")], ..Default::default() },
|
||||
);
|
||||
host.post_files_changed(
|
||||
"other",
|
||||
&root_b,
|
||||
&active_b,
|
||||
&ide_vfs::FsBatch { created: vec![root_b.join("b.rs")], ..Default::default() },
|
||||
);
|
||||
|
||||
assert_eq!(host.shared.project_generation(&root_a).unwrap(), 2);
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
|
||||
// Bumping project A does not bump project B
|
||||
let bump_a = host.shared.bump_project_generation(&root_a);
|
||||
assert_eq!(bump_a, 3);
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
|
||||
// Register target for project A and B
|
||||
let target = ide_plugin::PluginRunTarget {
|
||||
id: "run".into(),
|
||||
name: "Run".into(),
|
||||
program: "dummy".into(),
|
||||
args: vec![],
|
||||
workdir_args: vec![],
|
||||
container_root: None,
|
||||
commands: vec![],
|
||||
};
|
||||
assert!(api.register_target(&root_a, target.clone(), None).is_ok());
|
||||
assert!(api.register_target(&root_b, target.clone(), None).is_ok());
|
||||
|
||||
assert_eq!(host.run_targets(&root_a).len(), 1);
|
||||
assert_eq!(host.run_targets(&root_b).len(), 1);
|
||||
|
||||
// Close project A
|
||||
ws.0.lock().unwrap().retain(|p| p != &root_a);
|
||||
host.project_closed(&root_a, "main");
|
||||
|
||||
// Project A targets withdrawn, Project B untouched
|
||||
assert!(host.run_targets(&root_a).is_empty());
|
||||
assert_eq!(host.run_targets(&root_b).len(), 1);
|
||||
|
||||
// Project A generation closed (NotFound on lookup), Project B intact
|
||||
assert!(host.shared.project_generation(&root_a).is_err());
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,13 @@
|
||||
//! args = "optional-arguments" # optional
|
||||
//! vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] # optional, API 1.14
|
||||
//! jdk = "jetbrains" # optional: only those VM options on JBR
|
||||
//! executor = "Hot Reload" # optional, API 1.18: see below
|
||||
//! ```
|
||||
//!
|
||||
//! With `executor`, the agent is not added to every launch: the plugin contributes an
|
||||
//! executor beside Run and Debug ("Run with Hot Reload", "Debug with Hot Reload"), and only
|
||||
//! launches through it get the agent and its `vmOptions`.
|
||||
//!
|
||||
//! One agent per plugin. The declaration derives the optional high-risk `java.agent`
|
||||
//! capability; granting it records the jar's hash, and a launch adds the agent only
|
||||
//! while the jar still has it ([`ide_run::java_agent`]).
|
||||
@@ -28,6 +33,7 @@ pub const POINT_ID: &str = "javaAgents";
|
||||
const MAX_ARGS: usize = 4096;
|
||||
const MAX_VM_OPTION: usize = 512;
|
||||
const MAX_VM_OPTIONS: usize = 32;
|
||||
const MAX_EXECUTOR: usize = 40;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -39,6 +45,8 @@ struct Decl {
|
||||
vm_options: Vec<String>,
|
||||
#[serde(default)]
|
||||
jdk: Option<String>,
|
||||
#[serde(default)]
|
||||
executor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -48,6 +56,8 @@ pub(super) struct Agent {
|
||||
pub(super) args: Option<String>,
|
||||
pub(super) vm_options: Vec<String>,
|
||||
pub(super) jdk: Option<String>,
|
||||
/// The executor title: only launches through it get the agent.
|
||||
pub(super) executor: Option<String>,
|
||||
}
|
||||
|
||||
/// Agents of enabled plugins.
|
||||
@@ -111,9 +121,16 @@ impl ExtensionPoint for JavaAgentsPoint {
|
||||
if !vm_options.is_empty() || jdk.is_some() {
|
||||
pkg.manifest.needs_api("contributes.javaAgents.vmOptions", 14)?;
|
||||
}
|
||||
let label = label(&d.path, args.as_deref(), &vm_options);
|
||||
let executor = validate_executor(d.executor)?;
|
||||
if executor.is_some() {
|
||||
pkg.manifest.needs_api("contributes.javaAgents.executor", 18)?;
|
||||
}
|
||||
let mut label = label(&d.path, args.as_deref(), &vm_options);
|
||||
if let Some(title) = &executor {
|
||||
label = format!("{label} (Run with {title})");
|
||||
}
|
||||
let (store, plugin) = (self.store.clone(), pkg.id().to_owned());
|
||||
let agent = Agent { jar, args, vm_options, jdk };
|
||||
let agent = Agent { jar, args, vm_options, jdk, executor };
|
||||
Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent))
|
||||
}
|
||||
}
|
||||
@@ -153,6 +170,17 @@ fn validate_jdk(jdk: Option<String>) -> Result<Option<String>, String> {
|
||||
Ok(Some(raw))
|
||||
}
|
||||
|
||||
/// The executor's title: one line, short enough for "Debug '<configuration>' with <title>".
|
||||
fn validate_executor(executor: Option<String>) -> Result<Option<String>, String> {
|
||||
let Some(title) = executor.map(|s| s.trim().to_owned()) else { return Ok(None) };
|
||||
if title.is_empty() || title.chars().count() > MAX_EXECUTOR || title.contains(|c: char| c.is_control()) {
|
||||
return Err(format!(
|
||||
"contributes.javaAgents: `executor` must be a title of 1–{MAX_EXECUTOR} characters on one line"
|
||||
));
|
||||
}
|
||||
Ok(Some(title))
|
||||
}
|
||||
|
||||
/// What Settings › Plugins shows: jar name, args, and any JVM options.
|
||||
fn label(path: &Path, args: Option<&str>, vm_options: &[String]) -> String {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
@@ -224,6 +252,7 @@ impl JavaAgentSource for PluginJavaAgents {
|
||||
vm_options: agent.vm_options.clone(),
|
||||
jdk: agent.jdk.clone(),
|
||||
approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()),
|
||||
executor: agent.executor.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -306,6 +335,33 @@ mod tests {
|
||||
assert_eq!(agent.jdk.as_deref(), Some("jetbrains"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_executor_from_api_18() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manifest = MANIFEST.replace("^1.10", "^1.18");
|
||||
let decl = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" Hot Reload \"\n";
|
||||
let pkg = package(&tmp.path().join("ok"), &format!("{manifest}{decl}"));
|
||||
assert_eq!(prepare(&pkg).unwrap().label, "spring agent.jar (Run with Hot Reload)");
|
||||
let store: Arc<JavaAgents> = Arc::default();
|
||||
let point = JavaAgentsPoint::new(store.clone());
|
||||
let _keep = (point.prepare(&pkg, pkg.manifest.declarations(POINT_ID).remove(0)).unwrap().commit)().unwrap();
|
||||
assert_eq!(store.for_plugin("acme.spring").unwrap().executor.as_deref(), Some("Hot Reload"));
|
||||
let source = PluginJavaAgents { store, pins: Arc::default() };
|
||||
assert_eq!(source.agents()[0].executor.as_deref(), Some("Hot Reload"));
|
||||
|
||||
let old = package(&tmp.path().join("old"), &format!("{MANIFEST_14}{decl}"));
|
||||
assert!(prepare(&old).map(|_| ()).unwrap_err().contains("new in plugin API 1.18"));
|
||||
let long = format!(
|
||||
"[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \"{}\"\n",
|
||||
"x".repeat(41)
|
||||
);
|
||||
let long = package(&tmp.path().join("long"), &format!("{manifest}{long}"));
|
||||
assert!(prepare(&long).map(|_| ()).unwrap_err().contains("`executor`"));
|
||||
let empty = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" \"\n";
|
||||
let empty = package(&tmp.path().join("empty"), &format!("{manifest}{empty}"));
|
||||
assert!(prepare(&empty).map(|_| ()).unwrap_err().contains("`executor`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_would_fail_at_launch() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use super::{PluginHost, ProviderKind};
|
||||
use ide_core::{IdeResult, Pos, Range};
|
||||
use ide_plugin::{ProviderDocument, language_features::*};
|
||||
use std::sync::Arc;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
pub(crate) fn valid_range(doc: &ProviderDocument, range: Range) -> bool {
|
||||
valid_range_in(&ide_text::Document::new(&doc.text), range)
|
||||
@@ -279,14 +279,18 @@ impl PluginHost {
|
||||
/// Optional API 1.14 hover actions. Only plugins declaring the
|
||||
/// `hover-actions` provider kind are asked; the released language-features
|
||||
/// export remains unchanged.
|
||||
pub fn language_hover_actions(&self, doc: &ProviderDocument) -> Vec<(String, HoverAction)> {
|
||||
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
|
||||
pub fn language_hover_actions(&self, doc: &ProviderDocument, project: Option<&Path>) -> Vec<(String, HoverAction)> {
|
||||
let project = project.map(Path::to_path_buf);
|
||||
let mut out = Vec::new();
|
||||
for (d, _bounds) in self.feature_documents(doc, None) {
|
||||
let snapshot = d.clone();
|
||||
let text = ide_text::Document::new(&snapshot.text);
|
||||
let d = Arc::new(d);
|
||||
let results = self
|
||||
.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| rt.language_hover_actions(&d, t));
|
||||
let project = project.clone();
|
||||
let results = self.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| {
|
||||
rt.language_hover_actions(&d, project.as_deref(), t)
|
||||
});
|
||||
for (p, items) in results {
|
||||
let commands: std::collections::HashSet<_> =
|
||||
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
|
||||
@@ -304,14 +308,22 @@ impl PluginHost {
|
||||
out
|
||||
}
|
||||
|
||||
pub fn language_gutter_actions(&self, doc: &ProviderDocument) -> Vec<(String, GutterAction)> {
|
||||
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
|
||||
pub fn language_gutter_actions(
|
||||
&self,
|
||||
doc: &ProviderDocument,
|
||||
project: Option<&Path>,
|
||||
) -> Vec<(String, GutterAction)> {
|
||||
let project = project.map(Path::to_path_buf);
|
||||
let mut out = Vec::new();
|
||||
for (d, bounds) in self.feature_documents(doc, None) {
|
||||
let lines = d.text.split('\n').count() as u32;
|
||||
let snapshot = d.clone();
|
||||
let d = Arc::new(d);
|
||||
let results = self
|
||||
.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| rt.language_gutter_actions(&d, t));
|
||||
let project = project.clone();
|
||||
let results = self.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| {
|
||||
rt.language_gutter_actions(&d, project.as_deref(), t)
|
||||
});
|
||||
for (p, items) in results {
|
||||
let commands: std::collections::HashSet<_> =
|
||||
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
|
||||
|
||||
@@ -27,6 +27,7 @@ pub(crate) mod diagnostics;
|
||||
pub mod endpoints;
|
||||
mod event_paths;
|
||||
mod execution;
|
||||
mod external_watch;
|
||||
mod files_changed;
|
||||
mod hover;
|
||||
mod icon_extensions;
|
||||
@@ -211,6 +212,7 @@ const LATENCY_WINDOW: usize = 128;
|
||||
/// Events waiting for one plugin (from one window).
|
||||
struct EventQueue {
|
||||
since: Instant,
|
||||
last_event: Instant,
|
||||
events: Vec<WorkbenchEvent>,
|
||||
files_source: Option<files_changed::Source>,
|
||||
}
|
||||
@@ -220,6 +222,8 @@ const MAX_QUEUED_EVENTS: usize = 500;
|
||||
/// How long events for a plugin that is not running are collected before it
|
||||
/// is activated to receive them.
|
||||
const IDLE_BATCH: Duration = Duration::from_secs(2);
|
||||
/// Maximum delay for debounced events before forcing delivery.
|
||||
const MAX_DEBOUNCE_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
struct LoadedPlugin {
|
||||
pkg: Package,
|
||||
@@ -1433,6 +1437,110 @@ impl PluginHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// Run Anything entries (API 1.18) of the plugin that declares `prefix`, for the
|
||||
/// field's `text` in `window`'s project: from what it already knows, within 300 ms.
|
||||
pub fn run_anything_suggest(
|
||||
&self,
|
||||
id: &str,
|
||||
window: &str,
|
||||
root: Option<PathBuf>,
|
||||
prefix: &str,
|
||||
text: &str,
|
||||
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
|
||||
self.declared_run_anything(id, prefix)?;
|
||||
if text.len() > 4096 || !(prefix.starts_with(text) || text.starts_with(prefix)) {
|
||||
return Err(IdeError::invalid("the text doesn't start with the plugin's prefix"));
|
||||
}
|
||||
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
|
||||
let (prefix, text) = (prefix.to_owned(), text.to_owned());
|
||||
let budget = Duration::from_millis(300);
|
||||
self.code_call_with_budget(
|
||||
id,
|
||||
invocation,
|
||||
"suggesting Run Anything entries",
|
||||
None,
|
||||
Some(budget),
|
||||
move |rt, inv| rt.run_anything_suggest(&prefix, &text, inv, budget),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs a Run Anything line whose first word is `prefix` (API 1.18): whether the
|
||||
/// plugin claimed it. A failed call is an error, which the caller treats as claimed.
|
||||
pub fn run_anything_run(
|
||||
&self,
|
||||
id: &str,
|
||||
window: &str,
|
||||
root: Option<PathBuf>,
|
||||
prefix: &str,
|
||||
line: &str,
|
||||
) -> IdeResult<bool> {
|
||||
self.declared_run_anything(id, prefix)?;
|
||||
if line.len() > 4096 || line.split_whitespace().next() != Some(prefix) {
|
||||
return Err(IdeError::invalid("the line doesn't start with the plugin's prefix"));
|
||||
}
|
||||
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
|
||||
let (prefix, line) = (prefix.to_owned(), line.to_owned());
|
||||
let timeout = self.limits.timeout;
|
||||
self.code_call(id, invocation, "running a Run Anything line", move |rt, inv| {
|
||||
rt.run_anything_run(&prefix, &line, inv, timeout)
|
||||
})
|
||||
}
|
||||
|
||||
/// Completions (API 1.18) for `field` of the plugin run configuration `config_id`
|
||||
/// (`plugin:<plugin>:<id>`, also a user's override of one), as `window`'s project
|
||||
/// currently has it, for the field's `text` and UTF-16 `caret`: from what the owning
|
||||
/// plugin already knows, within 300 ms.
|
||||
pub fn run_configuration_complete(
|
||||
&self,
|
||||
window: &str,
|
||||
root: &Path,
|
||||
config_id: &str,
|
||||
field: &str,
|
||||
text: &str,
|
||||
caret: u32,
|
||||
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
|
||||
if text.len() > 16 * 1024 || caret as usize > text.encode_utf16().count() || field.len() > 64 {
|
||||
return Err(IdeError::invalid("the field text or caret is out of range"));
|
||||
}
|
||||
if !self.run_detection().detect(root).iter().any(|c| c.id == config_id && c.kind == "plugin") {
|
||||
return Err(IdeError::not_found("this plugin configuration is no longer provided"));
|
||||
}
|
||||
let owner = self
|
||||
.plugins
|
||||
.read()
|
||||
.keys()
|
||||
.filter(|id| {
|
||||
config_id.strip_prefix(ide_run::EXTERNAL_PREFIX).is_some_and(|rest| rest.starts_with(&format!("{id}:")))
|
||||
})
|
||||
.max_by_key(|id| id.len())
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found("the plugin owning this configuration is not loaded"))?;
|
||||
let own = config_id[ide_run::EXTERNAL_PREFIX.len() + owner.len() + 1..].to_owned();
|
||||
let invocation = Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: Some(root.to_path_buf()),
|
||||
..Default::default()
|
||||
};
|
||||
let (field, text) = (field.to_owned(), text.to_owned());
|
||||
let budget = Duration::from_millis(300);
|
||||
self.code_call_with_budget(
|
||||
&owner,
|
||||
invocation,
|
||||
"completing a run configuration field",
|
||||
None,
|
||||
Some(budget),
|
||||
move |rt, inv| rt.run_configuration_complete(&own, &field, &text, caret, inv, budget),
|
||||
)
|
||||
}
|
||||
|
||||
fn declared_run_anything(&self, id: &str, prefix: &str) -> IdeResult<()> {
|
||||
if self.ui.items(ui_points::RUN_ANYTHING, Some(id)).iter().any(|d| d.key == prefix) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::invalid(format!("plugin {id:?} declares no Run Anything prefix {prefix:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Content of a declared view, or of a custom editor (`invocation.editor`
|
||||
/// is its document). Activates the plugin (`on-view`).
|
||||
pub fn render_view(
|
||||
@@ -1805,10 +1913,57 @@ impl PluginHost {
|
||||
/// events, and ignores context writes of commands still running for it.
|
||||
pub fn forget_client(&self, label: &str) {
|
||||
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
|
||||
self.shared.external_watches.remove_client(label);
|
||||
self.shared.forget_client(label);
|
||||
self.forget_web_ptys(label);
|
||||
}
|
||||
|
||||
/// A project closed (or the last window for it detached). Closes the project
|
||||
/// generation, drops queued events for that window and project, withdraws run
|
||||
/// targets and run configurations, and delivers
|
||||
/// `project-closed` to subscribed plugins.
|
||||
pub fn project_closed(&self, root: &Path, window: &str) {
|
||||
self.shared.close_project_generation(root);
|
||||
self.shared.external_watches.remove_project(root);
|
||||
self.withdraw_project_run_targets(root);
|
||||
self.shared.run_configurations.write().retain(|(_, r), _| r != root);
|
||||
|
||||
let root_ipc = ide_core::ipc_path::to_ipc(root);
|
||||
{
|
||||
let mut queues = self.queues.lock();
|
||||
queues.retain(|(_, client), q| {
|
||||
if client.as_deref() == Some(window) {
|
||||
return false;
|
||||
}
|
||||
q.events.retain(|e| {
|
||||
if let WorkbenchEvent::FilesChanged(f) | WorkbenchEvent::WatchedFilesChanged(f) = e
|
||||
&& f.project.as_deref() == Some(&root_ipc)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
!q.events.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
let plugins = self.plugins.read();
|
||||
for p in plugins.values() {
|
||||
{
|
||||
let mut batches = p.batches.lock();
|
||||
batches.files_pending.retain(|(client, ws_root), _| {
|
||||
client.as_deref() != Some(window) && ws_root.as_deref() != Some(root)
|
||||
});
|
||||
}
|
||||
}
|
||||
drop(plugins);
|
||||
// In-flight work is not cancelled: an instance serves every project, and its
|
||||
// results for this one are refused now that the project's generation moved on.
|
||||
|
||||
self.post_events(None, vec![WorkbenchEvent::ProjectClosed(root_ipc)]);
|
||||
self.flush_events();
|
||||
}
|
||||
|
||||
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
|
||||
pub fn cancel_task(&self, task_id: &str) -> bool {
|
||||
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
|
||||
@@ -1945,6 +2100,36 @@ impl PluginHost {
|
||||
);
|
||||
}
|
||||
|
||||
/// Queues what `events.watch-paths` watchers saw for their plugin and window,
|
||||
/// while that window still shows the project the watch belongs to.
|
||||
fn queue_watched_changes(&self, now: Instant) {
|
||||
let changes = self.shared.external_watches.take();
|
||||
if changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let subs = self.shared.subscriptions.lock().clone();
|
||||
let plugins = self.plugins.read();
|
||||
let mut queues = self.queues.lock();
|
||||
for change in changes {
|
||||
let Some(p) = plugins.get(&change.plugin) else { continue };
|
||||
if self.shared.project_of(&change.client).as_deref() != Some(change.project.as_path())
|
||||
|| !Self::wants(p, EventKind::WatchedFilesChanged, subs.kinds.get(p.id()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let batch =
|
||||
ide_plugin::FilesChanged { project: Some(ide_core::ipc_path::to_ipc(&change.project)), ..change.batch };
|
||||
let queue = queues.entry((change.plugin, Some(change.client))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
files_changed::append(&mut queue.events, vec![WorkbenchEvent::WatchedFilesChanged(batch)]);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post_events(&self, client: Option<&str>, events: Vec<WorkbenchEvent>) {
|
||||
self.post_events_from(client, events, None);
|
||||
}
|
||||
@@ -1998,9 +2183,11 @@ impl PluginHost {
|
||||
}
|
||||
let queue = queues.entry((p.id().to_owned(), client.map(str::to_owned))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
if let Some(source) = &source {
|
||||
if !queue.files_source.as_ref().is_some_and(|old| old.same(source)) {
|
||||
queue.events.retain(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
@@ -2015,6 +2202,7 @@ impl PluginHost {
|
||||
&& !matches!(
|
||||
event,
|
||||
WorkbenchEvent::FilesChanged(_)
|
||||
| WorkbenchEvent::WatchedFilesChanged(_)
|
||||
| WorkbenchEvent::RunExited(_)
|
||||
| WorkbenchEvent::TerminalExited(_)
|
||||
| WorkbenchEvent::ContentTabAction(_)
|
||||
@@ -2039,24 +2227,82 @@ impl PluginHost {
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn flush_events_at(&self, now: Instant) {
|
||||
self.queue_watched_changes(now);
|
||||
let due: Vec<(QueueKey, EventQueue)> = {
|
||||
let mut queues = self.queues.lock();
|
||||
let plugins = self.plugins.read();
|
||||
let keys: Vec<_> = queues
|
||||
.iter()
|
||||
.filter(|((id, _), q)| {
|
||||
let running =
|
||||
plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
|
||||
running
|
||||
let subs = self.shared.subscriptions.lock();
|
||||
let mut due = Vec::new();
|
||||
let mut keys_to_remove = Vec::new();
|
||||
|
||||
for (key, q) in queues.iter_mut() {
|
||||
let (id, _client) = key;
|
||||
let running = plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
|
||||
let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled));
|
||||
// Already debounced by the watcher, like project file changes.
|
||||
let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_)));
|
||||
let debounce = subs.paths.get(id).and_then(|p| p.get("files-changed")).and_then(|f| f.debounce);
|
||||
|
||||
let (files_due, files_debouncing) = if has_files {
|
||||
if let Some(debounce) = debounce {
|
||||
let elapsed = now.saturating_duration_since(q.last_event) >= debounce
|
||||
|| now.saturating_duration_since(q.since) >= MAX_DEBOUNCE_WAIT;
|
||||
(elapsed, !elapsed)
|
||||
} else {
|
||||
(true, false)
|
||||
}
|
||||
} else {
|
||||
(false, false)
|
||||
};
|
||||
|
||||
let other_events_due = (running
|
||||
|| has_watched
|
||||
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|
||||
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|
||||
|| has_scheduled)
|
||||
&& q.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
|
||||
if files_debouncing {
|
||||
if other_events_due {
|
||||
let mut other_events = Vec::new();
|
||||
q.events.retain(|e| {
|
||||
if matches!(e, WorkbenchEvent::FilesChanged(_)) {
|
||||
true
|
||||
} else {
|
||||
other_events.push(e.clone());
|
||||
false
|
||||
}
|
||||
});
|
||||
due.push((
|
||||
key.clone(),
|
||||
EventQueue {
|
||||
since: q.since,
|
||||
last_event: q.last_event,
|
||||
events: other_events,
|
||||
files_source: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let is_due = files_due
|
||||
|| has_watched
|
||||
|| running
|
||||
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|
||||
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|
||||
|| q.events
|
||||
.iter()
|
||||
.any(|e| matches!(e, WorkbenchEvent::FilesChanged(_) | WorkbenchEvent::Scheduled))
|
||||
})
|
||||
.map(|(k, _)| k.clone())
|
||||
.collect();
|
||||
keys.into_iter().filter_map(|k| queues.remove(&k).map(|q| (k, q))).collect()
|
||||
|| has_scheduled;
|
||||
if is_due {
|
||||
keys_to_remove.push(key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for k in keys_to_remove {
|
||||
if let Some(q) = queues.remove(&k) {
|
||||
due.push((k, q));
|
||||
}
|
||||
}
|
||||
due
|
||||
};
|
||||
let mut changed = false;
|
||||
for ((id, client), queue) in due {
|
||||
@@ -2081,9 +2327,10 @@ impl PluginHost {
|
||||
pub fn wait_events(&self, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
let busy = self.plugins.read().values().any(|p| p.batches.lock().pending > 0);
|
||||
self.flush_events_at(Instant::now());
|
||||
let busy =
|
||||
self.plugins.read().values().any(|p| p.batches.lock().pending > 0) || !self.queues.lock().is_empty();
|
||||
if !busy {
|
||||
self.flush_events_at(Instant::now());
|
||||
return true;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
@@ -2125,12 +2372,20 @@ impl PluginHost {
|
||||
&& queue.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)))
|
||||
{
|
||||
let (files, other) = queue.events.into_iter().partition(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
let changed =
|
||||
self.deliver(id, client.clone(), EventQueue { since: queue.since, events: other, files_source: None });
|
||||
let changed = self.deliver(
|
||||
id,
|
||||
client.clone(),
|
||||
EventQueue { since: queue.since, last_event: queue.last_event, events: other, files_source: None },
|
||||
);
|
||||
return self.deliver(
|
||||
id,
|
||||
client,
|
||||
EventQueue { since: queue.since, events: files, files_source: queue.files_source },
|
||||
EventQueue {
|
||||
since: queue.since,
|
||||
last_event: queue.last_event,
|
||||
events: files,
|
||||
files_source: queue.files_source,
|
||||
},
|
||||
) | changed;
|
||||
}
|
||||
let Ok(plugin) = self.get(id) else { return false };
|
||||
@@ -2451,12 +2706,15 @@ impl PluginHost {
|
||||
let restricted = p.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root));
|
||||
if due && !restricted && self.startup_finished.load(Ordering::Acquire) {
|
||||
// Activates it if needed and calls `handle([scheduled])`.
|
||||
self.queues
|
||||
.lock()
|
||||
.entry((p.id().to_owned(), None))
|
||||
.or_insert_with(|| EventQueue { since: now, events: Vec::new(), files_source: None })
|
||||
.events
|
||||
.push(WorkbenchEvent::Scheduled);
|
||||
let mut q = self.queues.lock();
|
||||
let queue = q.entry((p.id().to_owned(), None)).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
queue.events.push(WorkbenchEvent::Scheduled);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
@@ -3145,6 +3403,7 @@ impl PluginHost {
|
||||
vm_options: agent.vm_options,
|
||||
jdk: agent.jdk,
|
||||
approved,
|
||||
executor: agent.executor,
|
||||
}
|
||||
}),
|
||||
source: p.source,
|
||||
|
||||
@@ -95,6 +95,9 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
|
||||
|
||||
@@ -45,6 +45,9 @@ pub struct Detector {
|
||||
/// Optional output parser, including the API 1.4 plugin export.
|
||||
#[serde(default)]
|
||||
pub framework: Option<String>,
|
||||
/// Output stream transport (API 1.18): `"pipes"` (default) or `"pty"`.
|
||||
#[serde(default, alias = "outputMode")]
|
||||
pub output_mode: Option<ide_plugin::PluginOutputMode>,
|
||||
}
|
||||
|
||||
/// Detectors of enabled plugins.
|
||||
@@ -94,6 +97,12 @@ impl ExtensionPoint for RunDetectorsPoint {
|
||||
if d.framework.as_ref().is_some_and(|v| v.is_empty() || v.len() > 64) {
|
||||
return Err("invalid test framework".into());
|
||||
}
|
||||
if d.output_mode.is_some() {
|
||||
pkg.manifest.needs_api("runDetectors.outputMode", 18)?;
|
||||
}
|
||||
if d.test && d.output_mode == Some(ide_plugin::PluginOutputMode::Pty) {
|
||||
return Err(format!("run detector {:?}: test configurations cannot emulate a terminal", d.id));
|
||||
}
|
||||
validate_item_id(&d.id, "run detector id")?;
|
||||
if d.name.trim().is_empty() || d.name.len() > 128 {
|
||||
return Err(format!("run detector {:?}: `name` must be 1–128 bytes", d.id));
|
||||
@@ -169,6 +178,7 @@ impl ExternalDetection for PluginRunDetection {
|
||||
allow_parallel: false,
|
||||
extras: ide_run::RunExtras {
|
||||
params: d.framework.clone().map(|f| [("framework".into(), f)].into()).unwrap_or_default(),
|
||||
emulate_terminal: d.output_mode == Some(ide_plugin::PluginOutputMode::Pty),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
@@ -193,7 +203,10 @@ impl ExternalDetection for PluginRunDetection {
|
||||
is_test: c.test,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
extras: ide_run::RunExtras {
|
||||
emulate_terminal: c.output_mode == ide_plugin::PluginOutputMode::Pty,
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
config.id = config_id(plugin, &c.id);
|
||||
config.cwd = Some(c.cwd.as_ref().map(|p| root.join(p)).unwrap_or_else(|| root.to_path_buf()).into());
|
||||
@@ -250,3 +263,34 @@ impl ExternalDetection for PluginRunDetection {
|
||||
pin.verify().map(Path::to_path_buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_extension::ExtensionPoint;
|
||||
|
||||
#[test]
|
||||
fn detector_output_mode_requires_api_18_and_rejects_tests() {
|
||||
let point = RunDetectorsPoint::new(Arc::default());
|
||||
let base_toml = |extra: &str| {
|
||||
let src = format!("id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\n{extra}\n");
|
||||
let manifest = ide_extension::Manifest::parse(&src).unwrap();
|
||||
ide_extension::Package::new(manifest, std::env::temp_dir())
|
||||
};
|
||||
let decl = |test: bool, mode: &str| -> toml::Value {
|
||||
toml::from_str(&format!(
|
||||
"id = \"run\"\nname = \"Run\"\nfiles = [\"m\"]\ncommand = \"tool\"\ntest = {test}\noutputMode = \"{mode}\"\n"
|
||||
))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let old = base_toml("engines.openidea = \"^1.17\"");
|
||||
assert!(point.prepare(&old, decl(false, "pty")).unwrap_err().contains("1.18"));
|
||||
|
||||
let current = base_toml("engines.openidea = \"^1.18\"");
|
||||
assert!(point.prepare(¤t, decl(false, "pty")).is_ok());
|
||||
assert!(point.prepare(¤t, decl(false, "pipes")).is_ok());
|
||||
assert!(point.prepare(¤t, decl(true, "pipes")).is_ok());
|
||||
assert!(point.prepare(¤t, decl(true, "pty")).unwrap_err().contains("test"));
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,12 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
impl PluginApi {
|
||||
pub(super) fn register_target(&self, root: &Path, target: PluginRunTarget) -> Result<(), HostError> {
|
||||
pub(super) fn register_target(
|
||||
&self,
|
||||
root: &Path,
|
||||
target: PluginRunTarget,
|
||||
generation: Option<u64>,
|
||||
) -> Result<(), HostError> {
|
||||
ide_remote::plugin_target::validate(&target).map_err(|e| HostError::Invalid(e.to_string()))?;
|
||||
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
|
||||
if !workspace.projects().iter().any(|r| r == root) {
|
||||
@@ -48,6 +53,12 @@ impl PluginApi {
|
||||
if !workspace.trusted(root) {
|
||||
return Err(HostError::Denied("project is not trusted".into()));
|
||||
}
|
||||
if let Some(expected) = generation {
|
||||
let current = self.shared.project_generation(root)?;
|
||||
if expected < current {
|
||||
return Err(HostError::Stale);
|
||||
}
|
||||
}
|
||||
self.approved_program_in_project(&target.program, Some(root))?;
|
||||
let blocked = self.shared.prompts_blocked.lock();
|
||||
if blocked.contains(self.pkg.id()) {
|
||||
|
||||
@@ -70,6 +70,10 @@ pub struct PluginJavaAgent {
|
||||
pub jdk: Option<String>,
|
||||
/// The jar still has the hash recorded when `java.agent` was granted.
|
||||
pub approved: bool,
|
||||
/// The title of the executor the agent is bound to (API 1.18): "Run with <title>" and
|
||||
/// "Debug with <title>" launch with it; other launches leave it out.
|
||||
#[serde(default)]
|
||||
pub executor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//!
|
||||
//! ```toml
|
||||
//! [[contributes.menus]]
|
||||
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message
|
||||
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message,
|
||||
//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes)
|
||||
//! command = "check"
|
||||
//! when = "editorLang == java"
|
||||
//! # view = "<view id>" # required for (only allowed on) viewItem.context
|
||||
@@ -44,6 +45,22 @@
|
||||
//! width = 110 # pixels, 40–400
|
||||
//! when = "plugin.<id>.enabled" # optional
|
||||
//!
|
||||
//! [[contributes.overlays]]
|
||||
//! id = "stage"
|
||||
//! web = "web/stage.html" # floats over the workbench, never takes the focus (API 1.18)
|
||||
//! width = 320 # pixels, 40–800; the page can resize it within those bounds
|
||||
//! height = 240
|
||||
//! anchor = "bottom-right" # top-left … bottom-right (nine); the page can move it
|
||||
//! when = "plugin.<id>.showing" # optional
|
||||
//! interactive = true # optional; false lets every click through to the IDE
|
||||
//!
|
||||
//! [[contributes.dialogs]]
|
||||
//! id = "preview"
|
||||
//! title = "SQL Preview" # the dialog's title bar
|
||||
//! web = "web/preview.html" # modal, resizable; opened by `views.reveal("preview")` (API 1.18)
|
||||
//! width = 900 # pixels, 320–1600
|
||||
//! height = 600 # pixels, 200–1200
|
||||
//!
|
||||
//! [[contributes.fileIcons]]
|
||||
//! id = "drawing"
|
||||
//! patterns = ["*.excalidraw"]
|
||||
@@ -82,8 +99,11 @@ pub const SETTINGS: &str = "settings";
|
||||
pub const VIEWS: &str = "views";
|
||||
pub const CUSTOM_EDITORS: &str = "customEditors";
|
||||
pub const EDITOR_PANELS: &str = "editorPanels";
|
||||
pub const OVERLAYS: &str = "overlays";
|
||||
pub const DIALOGS: &str = "dialogs";
|
||||
pub const RUN_ANYTHING: &str = "runAnything";
|
||||
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
|
||||
pub const WEB_POINTS: [&str; 3] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS];
|
||||
pub const WEB_POINTS: [&str; 5] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS];
|
||||
pub const FILE_ICONS: &str = "fileIcons";
|
||||
pub const MARKER_ICONS: &str = "markerIcons";
|
||||
pub const FILE_TEMPLATES: &str = "fileTemplates";
|
||||
@@ -93,7 +113,10 @@ pub const SERVER_COMMANDS: &str = "serverCommands";
|
||||
const VIEW_ITEM_MENU: &str = "viewItem.context";
|
||||
/// The toolbar above the commit message (Commit tool window and dialog).
|
||||
const COMMIT_MESSAGE_MENU: &str = "commit.message";
|
||||
const MENU_IDS: [&str; 10] = [
|
||||
/// The Services tool window's context menu and toolbar for the IDE's own nodes (run
|
||||
/// configurations, Docker containers…): the command gets the selected services.
|
||||
const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
|
||||
const MENU_IDS: [&str; 12] = [
|
||||
"editor.context",
|
||||
"projectView.context",
|
||||
"editorTab.context",
|
||||
@@ -104,6 +127,8 @@ const MENU_IDS: [&str; 10] = [
|
||||
"mainToolbar",
|
||||
"problems.context",
|
||||
"searchResults.context",
|
||||
SERVICES_MENUS[0],
|
||||
SERVICES_MENUS[1],
|
||||
];
|
||||
const MAX_TITLE: usize = 256;
|
||||
const MAX_SETTINGS: usize = 200;
|
||||
@@ -168,6 +193,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
if d.menu == COMMIT_MESSAGE_MENU {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?;
|
||||
}
|
||||
if SERVICES_MENUS.contains(&d.menu.as_str()) {
|
||||
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?;
|
||||
}
|
||||
if let Some(w) = &d.when {
|
||||
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
|
||||
}
|
||||
@@ -887,6 +915,109 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OverlayDecl {
|
||||
id: String,
|
||||
web: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
#[serde(default = "default_overlay_anchor")]
|
||||
anchor: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
when: Option<String>,
|
||||
#[serde(default = "default_true")]
|
||||
interactive: bool,
|
||||
}
|
||||
|
||||
fn default_overlay_anchor() -> String {
|
||||
"bottom-right".into()
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Where an overlay can sit in the window (the page may move it to another).
|
||||
pub const OVERLAY_ANCHORS: [&str; 9] = [
|
||||
"top-left",
|
||||
"top-center",
|
||||
"top-right",
|
||||
"middle-left",
|
||||
"center",
|
||||
"middle-right",
|
||||
"bottom-left",
|
||||
"bottom-center",
|
||||
"bottom-right",
|
||||
];
|
||||
const OVERLAY_SIZE: std::ops::RangeInclusive<u32> = 40..=800;
|
||||
|
||||
/// `[[contributes.overlays]]` (API 1.18): a web page floating over the workbench at
|
||||
/// one of nine anchors, shown while `when` holds. It never takes the keyboard focus,
|
||||
/// sits under dialogs and popups, and sees nothing of the IDE, so it needs no
|
||||
/// capability.
|
||||
pub(super) fn overlay(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: OverlayDecl = decode(OVERLAYS, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{OVERLAYS}"), 18)?;
|
||||
validate_item_id(&d.id, "overlay id")?;
|
||||
let what = format!("overlay {:?}", d.id);
|
||||
for (name, value) in [("width", d.width), ("height", d.height)] {
|
||||
if !OVERLAY_SIZE.contains(&value) {
|
||||
return Err(format!("{what}: `{name}` is {}–{} pixels", OVERLAY_SIZE.start(), OVERLAY_SIZE.end()));
|
||||
}
|
||||
}
|
||||
if !OVERLAY_ANCHORS.contains(&d.anchor.as_str()) {
|
||||
return Err(format!("{what}: `anchor` is one of {}", OVERLAY_ANCHORS.join(", ")));
|
||||
}
|
||||
if let Some(when) = &d.when {
|
||||
validate_when(when).map_err(|e| format!("{what}: {e}"))?;
|
||||
}
|
||||
let files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DialogDecl {
|
||||
id: String,
|
||||
title: String,
|
||||
web: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
const DIALOG_WIDTH: std::ops::RangeInclusive<u32> = 320..=1600;
|
||||
const DIALOG_HEIGHT: std::ops::RangeInclusive<u32> = 200..=1200;
|
||||
|
||||
/// `[[contributes.dialogs]]` (API 1.18): a package web page in a modal, resizable IDE
|
||||
/// dialog with a title bar, opened by the plugin's code with `views.reveal(id)` in the
|
||||
/// invoking window. Like a web view it sees nothing of the IDE beyond its messages, so
|
||||
/// it needs no capability.
|
||||
pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: DialogDecl = decode(DIALOGS, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{DIALOGS}"), 18)?;
|
||||
validate_item_id(&d.id, "dialog id")?;
|
||||
let what = format!("dialog {:?}", d.id);
|
||||
// `views.reveal(id)` opens it, so it can't share an id with a tool window.
|
||||
if pkg.manifest.declarations(VIEWS).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) {
|
||||
return Err(format!("{what}: a view has the same id"));
|
||||
}
|
||||
if d.title.trim().is_empty() || d.title.len() > 256 {
|
||||
return Err(format!("{what}: `title` is 1–256 bytes"));
|
||||
}
|
||||
for (name, value, range) in [("width", d.width, DIALOG_WIDTH), ("height", d.height, DIALOG_HEIGHT)] {
|
||||
if !range.contains(&value) {
|
||||
return Err(format!("{what}: `{name}` is {}–{} pixels", range.start(), range.end()));
|
||||
}
|
||||
}
|
||||
let files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct FileIconDecl {
|
||||
@@ -1112,6 +1243,44 @@ pub(super) fn commit_check(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
|
||||
Ok(UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RunAnythingDecl {
|
||||
/// The first word of the Run Anything lines the plugin answers (`task`).
|
||||
prefix: String,
|
||||
/// The heading of its entries (default: the plugin's name).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
title: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether `prefix` can start a Run Anything line: a lowercase word of letters, digits,
|
||||
/// `.`, `_` or `-` that commands begin with (`task`, `just`, `make`).
|
||||
pub(super) fn valid_run_anything_prefix(prefix: &str) -> bool {
|
||||
(1..=32).contains(&prefix.len())
|
||||
&& prefix.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
|
||||
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
|
||||
}
|
||||
|
||||
/// `[[contributes.runAnything]]` (API 1.18): Run Anything lines starting with `prefix`
|
||||
/// are suggested and run by the plugin's `run-anything-provider` export.
|
||||
pub(super) fn run_anything(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: RunAnythingDecl = decode(RUN_ANYTHING, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{RUN_ANYTHING}"), 18)?;
|
||||
if !valid_run_anything_prefix(&d.prefix) {
|
||||
return Err(format!(
|
||||
"contributes.{RUN_ANYTHING}: `prefix` {:?} is one lowercase word (letters, digits, `.`, `_`, `-`; at most 32)",
|
||||
d.prefix
|
||||
));
|
||||
}
|
||||
if let Some(t) = &d.title {
|
||||
title(RUN_ANYTHING, t)?;
|
||||
}
|
||||
if pkg.manifest.wasm.is_none() {
|
||||
return Err(format!("contributes.{RUN_ANYTHING}: needs `wasm` (its lines run in the plugin's code)"));
|
||||
}
|
||||
Ok(UiDecl::new(d.prefix.clone(), d.title.clone().unwrap_or_default(), json(&d)?))
|
||||
}
|
||||
|
||||
/// A command a language server's code lens, code action or inlay hint carries and
|
||||
/// leaves to the client, and the plugin command that runs it.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -1212,6 +1381,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn services_menus_require_api_1_18() {
|
||||
for location in SERVICES_MENUS {
|
||||
for (api, valid) in [("^1.17", false), ("^1.18", true)] {
|
||||
let manifest = ide_extension::Manifest::parse(&format!("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'")).unwrap();
|
||||
let pkg = Package::new(manifest, std::path::PathBuf::from("/unused"));
|
||||
let decl = toml::from_str(&format!(
|
||||
"menu='{location}'\ncommand='reload'\nwhen=\"serviceKind == 'spring-boot' && serviceRunning\""
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(menu(&pkg, decl).is_ok(), valid, "{api}:{location}");
|
||||
}
|
||||
}
|
||||
let manifest = ide_extension::Manifest::parse("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='^1.18'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'").unwrap();
|
||||
let pkg = Package::new(manifest, std::path::PathBuf::from("/unused"));
|
||||
let grouped = toml::from_str("menu='services.context'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap();
|
||||
assert!(menu(&pkg, grouped).is_ok());
|
||||
let toolbar = toml::from_str("menu='services.toolbar'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap();
|
||||
assert!(menu(&pkg, toolbar).unwrap_err().contains("only for context menus"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_bindings_need_api_1_10_and_a_when_clause() {
|
||||
let pkg = |api: &str| {
|
||||
@@ -1518,6 +1708,133 @@ web = "web/view.html"
|
||||
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlays_validate_api_size_anchor_when_and_page() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/overlay");
|
||||
// A Windows checkout may have CRLF line ends; the edits below match on `\n`.
|
||||
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap().replace("\r\n", "\n");
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(OVERLAYS).into_iter().next().unwrap();
|
||||
overlay(&Package::new(manifest, root.clone()), decl)
|
||||
};
|
||||
let valid = check(&source).unwrap();
|
||||
assert_eq!(valid.key, "probe");
|
||||
assert_eq!(
|
||||
valid.json,
|
||||
serde_json::json!({
|
||||
"id": "probe", "web": "web/index.html", "width": 260, "height": 140,
|
||||
"anchor": "bottom-right", "interactive": true,
|
||||
})
|
||||
);
|
||||
assert_eq!(valid.files, [PathBuf::from("web/index.html")]);
|
||||
let placed =
|
||||
check(&source.replace("height = 140", "height = 140\nanchor = \"top-center\"\ninteractive = false"));
|
||||
let placed = placed.unwrap();
|
||||
assert_eq!(placed.json["anchor"], "top-center");
|
||||
assert_eq!(placed.json["interactive"], false);
|
||||
let when = source.replace("height = 140", "height = 140\nwhen = \"plugin.overlay.showing\"");
|
||||
assert_eq!(check(&when).unwrap().json["when"], "plugin.overlay.showing");
|
||||
for size in ["40", "800"] {
|
||||
assert!(check(&source.replace("width = 260", &format!("width = {size}"))).is_ok(), "{size}");
|
||||
}
|
||||
for (bad, error) in [
|
||||
(source.replace("^1.18", "^1.17"), "1.18"),
|
||||
(source.replace("width = 260", "width = 39"), "40–800"),
|
||||
(source.replace("height = 140", "height = 801"), "`height`"),
|
||||
(source.replace("height = 140\n", ""), "height"),
|
||||
(source.replace("height = 140", "height = 140\nanchor = \"left\""), "anchor"),
|
||||
(source.replace("height = 140", "height = 140\nwhen = \"a &&\""), "when"),
|
||||
(source.replace("height = 140", "height = 140\nfocus = true"), "focus"),
|
||||
(source.replace("web/index.html", "index.html"), "directory of its own"),
|
||||
(source.replace("web/index.html", "web/missing.html"), "no such file"),
|
||||
(source.replace(r#"id = "probe""#, r#"id = "Pro Be""#), "id"),
|
||||
] {
|
||||
let err = check(&bad).unwrap_err();
|
||||
assert!(err.contains(error), "{bad}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialogs_validate_api_title_size_id_and_page() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("web")).unwrap();
|
||||
std::fs::write(dir.path().join("web/preview.html"), "<p>SQL</p>").unwrap();
|
||||
let source = r#"id = "sql"
|
||||
name = "SQL"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.18"
|
||||
|
||||
[[contributes.dialogs]]
|
||||
id = "preview"
|
||||
title = "SQL Preview"
|
||||
web = "web/preview.html"
|
||||
width = 900
|
||||
height = 600
|
||||
"#;
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(DIALOGS).into_iter().next().unwrap();
|
||||
dialog(&Package::new(manifest, dir.path().to_path_buf()), decl)
|
||||
};
|
||||
let valid = check(source).unwrap();
|
||||
assert_eq!((valid.key.as_str(), valid.label.as_str()), ("preview", "SQL Preview"));
|
||||
assert_eq!(
|
||||
valid.json,
|
||||
serde_json::json!({"id": "preview", "title": "SQL Preview", "web": "web/preview.html", "width": 900, "height": 600})
|
||||
);
|
||||
assert_eq!(valid.files, [PathBuf::from("web/preview.html")]);
|
||||
for (bad, error) in [
|
||||
(source.replace("^1.18", "^1.17"), "1.18"),
|
||||
(source.replace("width = 900", "width = 319"), "320–1600"),
|
||||
(source.replace("height = 600", "height = 1201"), "`height`"),
|
||||
(source.replace(r#"title = "SQL Preview""#, r#"title = " ""#), "title"),
|
||||
(
|
||||
source.replace(
|
||||
"height = 600",
|
||||
"height = 600
|
||||
modal = false",
|
||||
),
|
||||
"modal",
|
||||
),
|
||||
(source.replace("web/preview.html", "web/missing.html"), "no such file"),
|
||||
(source.replace(r#"id = "preview""#, r#"id = "Pre View""#), "id"),
|
||||
(format!("{source}\n[[contributes.views]]\nid = \"preview\"\ntitle = \"P\"\n"), "same id"),
|
||||
] {
|
||||
let err = check(&bad).unwrap_err();
|
||||
assert!(err.contains(error), "{bad}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_anything_validates_api_prefix_title_and_code() {
|
||||
let source = "id = \"go\"\nname = \"Go\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.18\"\nwasm = \"p.wasm\"\n\n[[contributes.runAnything]]\nprefix = \"task\"\n";
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(RUN_ANYTHING).into_iter().next().unwrap();
|
||||
run_anything(&Package::new(manifest, std::env::temp_dir()), decl)
|
||||
};
|
||||
let valid = check(source).unwrap();
|
||||
assert_eq!((valid.key.as_str(), valid.json.clone()), ("task", serde_json::json!({"prefix": "task"})));
|
||||
assert_eq!(check(&format!("{source}title = \"Go Task\"\n")).unwrap().json["title"], "Go Task");
|
||||
for prefix in ["go-task", "mvn.w", "x2"] {
|
||||
assert!(check(&source.replace("\"task\"", &format!("{prefix:?}"))).is_ok(), "{prefix}");
|
||||
}
|
||||
for (bad, error) in [
|
||||
(source.replace("^1.18", "^1.17"), "1.18".to_owned()),
|
||||
(source.replace("wasm = \"p.wasm\"\n", ""), "wasm".to_owned()),
|
||||
(format!("{source}command = \"x\"\n"), "command".to_owned()),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(
|
||||
["Task", "task build", "", "-x", "t/x", &"t".repeat(33)]
|
||||
.map(|p| (source.replace("\"task\"", &format!("{p:?}")), "prefix".to_owned())),
|
||||
) {
|
||||
let err = check(&bad).unwrap_err();
|
||||
assert!(err.contains(&error), "{bad}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
|
||||
|
||||
@@ -222,6 +222,9 @@ impl Host {
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
|
||||
}
|
||||
if cfg.name == "jdtls" {
|
||||
// Before anything reads the install the command resolves to.
|
||||
let managed = ide_tools::tools_dir(&data_dir).join("jdtls").join("bin").join("jdtls");
|
||||
ide_sdk::jdtls::skip_plain_launcher_wrappers(cfg, &managed);
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
let cache = match &member {
|
||||
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
|
||||
@@ -315,7 +318,13 @@ impl Host {
|
||||
ide_sdk::php::configure_intelephense_storage(cfg, &data_dir);
|
||||
if cfg.name == "jdtls" {
|
||||
let (excluded_poms, build_files) = jdtls_maven_import(root, &effective);
|
||||
ide_sdk::apply::configure_maven_import(cfg, root, &excluded_poms, build_files.as_deref());
|
||||
ide_sdk::apply::configure_maven_import(
|
||||
cfg,
|
||||
root,
|
||||
&excluded_poms,
|
||||
&effective.project_structure.excluded,
|
||||
build_files.as_deref(),
|
||||
);
|
||||
ide_sdk::apply::configure_gradle_import(
|
||||
cfg,
|
||||
effective.languages.java.gradle.linked_projects.as_deref(),
|
||||
@@ -2363,7 +2372,7 @@ mod maven_linkage_tests {
|
||||
serde_json::json!({"name": "jdtls", "command": "jdtls"}),
|
||||
)
|
||||
.unwrap();
|
||||
ide_sdk::apply::configure_maven_import(&mut server, tmp.path(), &excluded_poms, None);
|
||||
ide_sdk::apply::configure_maven_import(&mut server, tmp.path(), &excluded_poms, &[], None);
|
||||
let options = serde_json::to_value(server.initialization_options).unwrap();
|
||||
let exclusions = options.pointer("/settings/java/import/exclusions").unwrap().as_array().unwrap();
|
||||
assert!(exclusions.contains(&serde_json::json!(tmp.path().join("a").to_string_lossy().replace('\\', "/"))));
|
||||
|
||||
@@ -32,6 +32,10 @@ use std::sync::{Arc, OnceLock};
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
/// What `openidea-server --attach` reports when another build's backend keeps the project
|
||||
/// (clients match it to offer stopping that backend).
|
||||
pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \
|
||||
unsaved changes. Reconnect with that build, or stop its backend and open the project again.";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
/// Advertised only by a persistent backend with an editable idle timeout.
|
||||
@@ -73,6 +77,31 @@ pub struct ChannelMessage {
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
/// Streaming lifecycle signal delivered through a [`ChannelSink`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ChannelSignal {
|
||||
/// Emitted when a command claims a `{ "$channel": id }` argument.
|
||||
Opened(u64),
|
||||
/// One serialized streaming payload.
|
||||
Data(ChannelMessage),
|
||||
/// Emitted automatically when the last clone of the command's channel emitter is dropped.
|
||||
End(u64),
|
||||
}
|
||||
|
||||
/// Delivers streaming values and lifecycle signals from a command back to its caller.
|
||||
pub type ChannelSink = Arc<dyn Fn(ChannelSignal) + Send + Sync>;
|
||||
|
||||
struct ChannelDropGuard {
|
||||
id: u64,
|
||||
sink: ChannelSink,
|
||||
}
|
||||
|
||||
impl Drop for ChannelDropGuard {
|
||||
fn drop(&mut self) {
|
||||
(self.sink)(ChannelSignal::End(self.id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds the active client [`Peer`]: once for `--stdio` ([`OnceLock<Peer>`]) or
|
||||
/// rebound across client reconnects for a persistent daemon ([`PeerSlot`]).
|
||||
pub trait PeerHandle: Send + Sync + 'static {
|
||||
@@ -137,7 +166,7 @@ pub struct Call {
|
||||
pub host: Arc<Host>,
|
||||
pub window: String,
|
||||
pub args: Value,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
channel_sink: ChannelSink,
|
||||
}
|
||||
|
||||
impl Call {
|
||||
@@ -161,19 +190,26 @@ impl Call {
|
||||
.and_then(|v| v.get("$channel"))
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| IdeError::invalid(format!("argument {name}: expected a channel")))?;
|
||||
let peer = self.peer.clone();
|
||||
Ok(Arc::new(move |data: T| {
|
||||
let Some(peer) = peer.current() else { return };
|
||||
match serde_json::to_value(&data) {
|
||||
Ok(data) => {
|
||||
let _ = peer.notify("channel", ChannelMessage { id, data });
|
||||
}
|
||||
Err(e) => tracing::warn!("channel {id}: {e}"),
|
||||
}
|
||||
let sink = self.channel_sink.clone();
|
||||
sink(ChannelSignal::Opened(id));
|
||||
let guard = ChannelDropGuard { id, sink };
|
||||
Ok(Arc::new(move |data: T| match serde_json::to_value(&data) {
|
||||
Ok(data) => (guard.sink)(ChannelSignal::Data(ChannelMessage { id: guard.id, data })),
|
||||
Err(e) => tracing::warn!("channel {}: {e}", guard.id),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_channel_sink(peer: Arc<dyn PeerHandle>) -> ChannelSink {
|
||||
Arc::new(move |signal: ChannelSignal| {
|
||||
if let ChannelSignal::Data(msg) = signal
|
||||
&& let Some(peer) = peer.current()
|
||||
{
|
||||
let _ = peer.notify("channel", msg);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
|
||||
type HandlerFn = Arc<dyn Fn(Call) -> BoxFuture<IdeResult<Value>> + Send + Sync>;
|
||||
|
||||
@@ -184,24 +220,45 @@ pub struct Dispatcher {
|
||||
}
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn add<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
|
||||
fn wrap_handler<F, Fut, T>(f: F) -> HandlerFn
|
||||
where
|
||||
F: Fn(Call) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = IdeResult<T>> + Send + 'static,
|
||||
T: Serialize,
|
||||
{
|
||||
let f = Arc::new(f);
|
||||
let handler: HandlerFn = Arc::new(move |call| {
|
||||
Arc::new(move |call| {
|
||||
let fut = f(call);
|
||||
Box::pin(async move {
|
||||
let value = fut.await?;
|
||||
serde_json::to_value(value).map_err(|e| IdeError::internal(e.to_string()))
|
||||
})
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
|
||||
where
|
||||
F: Fn(Call) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = IdeResult<T>> + Send + 'static,
|
||||
T: Serialize,
|
||||
{
|
||||
let handler = Self::wrap_handler(f);
|
||||
assert!(self.handlers.insert(name, (trust, handler)).is_none(), "command {name} is registered twice");
|
||||
self
|
||||
}
|
||||
|
||||
/// Registers or replaces `name` (used by the web server to add shell-level hooks such as recent-project tracking).
|
||||
pub fn replace<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
|
||||
where
|
||||
F: Fn(Call) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = IdeResult<T>> + Send + 'static,
|
||||
T: Serialize,
|
||||
{
|
||||
let handler = Self::wrap_handler(f);
|
||||
self.handlers.insert(name, (trust, handler));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn commands(&self) -> Vec<&'static str> {
|
||||
let mut out: Vec<_> = self.handlers.keys().copied().collect();
|
||||
out.sort_unstable();
|
||||
@@ -219,6 +276,23 @@ impl Dispatcher {
|
||||
ops::register_domains(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
/// Invokes a command asynchronously with trust enforcement and a caller-supplied channel sink.
|
||||
pub async fn invoke(
|
||||
&self,
|
||||
host: Arc<Host>,
|
||||
window: String,
|
||||
cmd: &str,
|
||||
args: Value,
|
||||
channel_sink: ChannelSink,
|
||||
) -> IdeResult<Value> {
|
||||
let Some((trust, handler)) = self.handlers.get(cmd).cloned() else {
|
||||
return Err(IdeError::unavailable(format!("command {cmd} is not available")));
|
||||
};
|
||||
host.authorize(&window, trust)?;
|
||||
let call = Call { host, window, args, channel_sink };
|
||||
handler(call).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Serves `host` over `reader` / `writer` until the client disconnects.
|
||||
@@ -342,7 +416,7 @@ struct ServerHandler {
|
||||
daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>,
|
||||
}
|
||||
|
||||
fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
|
||||
pub(crate) fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
|
||||
ServerInfo {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
protocol: PROTOCOL_VERSION,
|
||||
@@ -374,7 +448,12 @@ impl Handler for ServerHandler {
|
||||
return Err((codes::METHOD_NOT_FOUND, format!("command {} is not available remotely", call.cmd)));
|
||||
};
|
||||
self.host.authorize(&call.window, trust).map_err(error_reply)?;
|
||||
let c = Call { host: self.host.clone(), window: call.window, args: call.args, peer: self.peer.clone() };
|
||||
let c = Call {
|
||||
host: self.host.clone(),
|
||||
window: call.window,
|
||||
args: call.args,
|
||||
channel_sink: peer_channel_sink(self.peer.clone()),
|
||||
};
|
||||
// Requests run on blocking-capable threads: wait for the command here.
|
||||
self.host.runtime.block_on(handler(c)).map_err(error_reply)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Shell-level commands registered in web server mode alongside `Dispatcher::standard()`.
|
||||
//!
|
||||
//! Project-host commands (`#[command]`) already live in `ide-host::ops` and are served directly.
|
||||
//! This module supplies the web equivalents of desktop shell commands (`app_info`, `languages`,
|
||||
//! `recent_projects`, `window_take_launch`, `menu_model`, `light_edit_open`, workspace helpers,
|
||||
//! HTTP client helpers, and benign no-ops for native-window-only commands).
|
||||
|
||||
use crate::Host;
|
||||
use crate::catalogue::TrustClass::{self, Always, Trusted};
|
||||
use crate::menu;
|
||||
use crate::ops::project::ProjectInfo;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{IdeError, IpcPath, RequestId};
|
||||
use ide_language::LanguageInfo;
|
||||
use ide_workspace::{RecentProject, RecentProjectGroup, RecentProjects};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Shared state for shell-level commands in a web server process.
|
||||
pub struct WebShellState {
|
||||
pub recent: RecentProjects,
|
||||
/// Per-window pending launch (taken once by `window_take_launch`).
|
||||
launches: Mutex<HashMap<String, PathBuf>>,
|
||||
/// Default workspace directory configured via `--project` / `OPENIDEA_WORKSPACE_DIR`.
|
||||
default_project: Option<PathBuf>,
|
||||
/// Whether the default project should be auto-trusted on startup.
|
||||
trust_default_project: bool,
|
||||
}
|
||||
|
||||
impl WebShellState {
|
||||
pub fn new(config_dir: &std::path::Path, default_project: Option<PathBuf>, trust_default_project: bool) -> Self {
|
||||
Self {
|
||||
recent: RecentProjects::load(config_dir),
|
||||
launches: Mutex::new(HashMap::new()),
|
||||
default_project,
|
||||
trust_default_project,
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeds a pending project launch for `window` (from URL `?project=...` or `--project`),
|
||||
/// or the project the window already has open when its page reloads.
|
||||
pub fn seed_launch(&self, host: &Host, window: &str, requested_project: Option<PathBuf>) {
|
||||
if let Ok(project) = host.project(window) {
|
||||
// A reloaded page gets the project the window still has: reopening it keeps its
|
||||
// index, language servers and runs.
|
||||
if !project.light {
|
||||
self.launches.lock().insert(window.to_owned(), project.root.clone());
|
||||
}
|
||||
return;
|
||||
}
|
||||
let target = requested_project.or_else(|| self.default_project.clone());
|
||||
if let Some(path) = target {
|
||||
if self.trust_default_project
|
||||
&& self.default_project.as_ref().is_some_and(|p| p == &path)
|
||||
&& let Err(e) = host.trust.inherit(&path)
|
||||
{
|
||||
tracing::warn!("cannot trust {}: {e}", path.display());
|
||||
}
|
||||
self.launches.lock().insert(window.to_owned(), path);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_launch(&self, window: &str) -> Option<PathBuf> {
|
||||
self.launches.lock().remove(window)
|
||||
}
|
||||
|
||||
pub fn record_project(&self, project: &crate::Project) {
|
||||
if !project.light
|
||||
&& let Err(e) = crate::ops::project::record_recent(&self.recent, project)
|
||||
{
|
||||
tracing::warn!("cannot record {} in recent projects: {e}", project.root.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct AppInfo {
|
||||
version: String,
|
||||
platform: String,
|
||||
windows_build_number: Option<u32>,
|
||||
config_dir: IpcPath,
|
||||
data_dir: IpcPath,
|
||||
wayland: bool,
|
||||
window_buttons: ide_core::platform::WindowButtonLayout,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct BuildInfo {
|
||||
version: String,
|
||||
build: String,
|
||||
profile: String,
|
||||
os: String,
|
||||
arch: String,
|
||||
tauri: String,
|
||||
updates: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct CloseContext {
|
||||
quitting: bool,
|
||||
windows: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct OpenProject {
|
||||
name: String,
|
||||
root: PathBuf,
|
||||
current: bool,
|
||||
remote: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct LocalDataInfo {
|
||||
current: String,
|
||||
default_dir: String,
|
||||
custom_root: Option<String>,
|
||||
env_override: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct LogLocation {
|
||||
dir: IpcPath,
|
||||
file: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// The menu bar the browser draws: the desktop spec as on Windows and Linux, without the
|
||||
/// update check (updates are managed with the server).
|
||||
fn web_menu_model(recent: &[RecentProject]) -> Vec<menu::MenuNode> {
|
||||
let spec = menu::without_action(menu::spec(menu::Os::Linux), "app.checkForUpdates");
|
||||
menu::model(&spec, &menu::recent_items(recent, &[], dirs::home_dir().as_deref()), &menu::MenuConfig::default())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum LogLevel {
|
||||
Error,
|
||||
Warn,
|
||||
Info,
|
||||
Debug,
|
||||
}
|
||||
|
||||
/// Registers all web-mode shell commands onto `dispatcher` (which should already contain
|
||||
/// `Dispatcher::standard()`).
|
||||
pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
// Wrap `open_project` so opened projects are recorded in RecentProjects.
|
||||
let s = shell.clone();
|
||||
dispatcher.replace("open_project", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
let project = crate::ops::project::open(&c.host, &c.window, &path).await?;
|
||||
s.record_project(&project);
|
||||
Ok(crate::ops::project::info(&project))
|
||||
}
|
||||
});
|
||||
|
||||
// App info & metadata.
|
||||
dispatcher.add("app_info", TrustClass::Always, |c| async move {
|
||||
Ok(AppInfo {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
windows_build_number: None,
|
||||
config_dir: c.host.config_dir.clone().into(),
|
||||
data_dir: c.host.data_dir.clone().into(),
|
||||
wayland: false,
|
||||
window_buttons: ide_core::platform::WindowButtonLayout { left: vec![], right: vec![] },
|
||||
})
|
||||
});
|
||||
|
||||
dispatcher.add("app_build_info", TrustClass::Always, |_| async move {
|
||||
Ok(BuildInfo {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
build: option_env!("OPENIDEA_BUILD").unwrap_or("web").into(),
|
||||
profile: if cfg!(debug_assertions) { "debug" } else { "release" }.into(),
|
||||
os: std::env::consts::OS.into(),
|
||||
arch: std::env::consts::ARCH.into(),
|
||||
tauri: "web".into(),
|
||||
updates: false,
|
||||
})
|
||||
});
|
||||
|
||||
dispatcher.add("app_log_location", TrustClass::Always, |c| async move {
|
||||
Ok(LogLocation { dir: c.host.local_data_dir.join("logs").into(), file: None })
|
||||
});
|
||||
|
||||
dispatcher.add("app_update_status", TrustClass::Always, |_| async move {
|
||||
Ok(json!({ "lastChecked": null, "checking": false }))
|
||||
});
|
||||
dispatcher.add("app_update_announcement", TrustClass::Always, |_| async move { Ok(false) });
|
||||
dispatcher.add("app_update_window_ready", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
dispatcher.add("app_check_update", TrustClass::Always, |_| async move {
|
||||
Err::<Value, _>(IdeError::unavailable("Software updates are managed externally in web server mode"))
|
||||
});
|
||||
dispatcher.add("app_release_notes", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
dispatcher.add("app_quit", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
dispatcher.add("app_cancel_quit", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
dispatcher.add("app_restart", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
|
||||
dispatcher.add("languages", TrustClass::Always, |c| async move {
|
||||
Ok(c.host.languages.all().iter().map(LanguageInfo::from).collect::<Vec<_>>())
|
||||
});
|
||||
|
||||
dispatcher.add("log_frontend", TrustClass::Always, |c| async move {
|
||||
let level: LogLevel = c.arg("level")?;
|
||||
let message: String = c.arg("message")?;
|
||||
match level {
|
||||
LogLevel::Error => tracing::error!(target: "frontend", "{message}"),
|
||||
LogLevel::Warn => tracing::warn!(target: "frontend", "{message}"),
|
||||
LogLevel::Info => tracing::info!(target: "frontend", "{message}"),
|
||||
LogLevel::Debug => tracing::debug!(target: "frontend", "{message}"),
|
||||
}
|
||||
Ok(Value::Null)
|
||||
});
|
||||
|
||||
// Recent projects & groups.
|
||||
let s = shell.clone();
|
||||
dispatcher.add("recent_projects", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let items = s.recent.list();
|
||||
c.host
|
||||
.blocking(move || Ok(ide_workspace::recent::with_live_branches(items)))
|
||||
.await
|
||||
.or_else(|_| Ok(s.recent.list()))
|
||||
}
|
||||
});
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("remove_recent_project", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
s.recent.remove(&path)?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
});
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("recent_project_groups", TrustClass::Always, move |_| {
|
||||
let s = s.clone();
|
||||
async move { Ok(s.recent.groups()) }
|
||||
});
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("set_recent_project_groups", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let groups: Vec<RecentProjectGroup> = c.arg("groups")?;
|
||||
s.recent.set_groups(groups)
|
||||
}
|
||||
});
|
||||
|
||||
// LightEdit.
|
||||
dispatcher.add("light_edit_open", TrustClass::Always, |c| async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
let (host, window) = (c.host.clone(), c.window.clone());
|
||||
let project = c.host.blocking(move || host.open_light(&window, &path)).await?;
|
||||
Ok::<Settings, IdeError>(project.settings.effective())
|
||||
});
|
||||
|
||||
dispatcher.add("light_edit_open_untitled", TrustClass::Always, |c| async move {
|
||||
let (host, window) = (c.host.clone(), c.window.clone());
|
||||
let project = c.host.blocking(move || host.open_light_empty(&window)).await?;
|
||||
Ok::<Settings, IdeError>(project.settings.effective())
|
||||
});
|
||||
|
||||
// Project rename & trust locations.
|
||||
let s = shell.clone();
|
||||
dispatcher.add("project_rename", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let name: String = c.arg("name")?;
|
||||
let project = crate::ops::project::rename(&c.host, &c.window, &name)?;
|
||||
s.record_project(&project);
|
||||
Ok::<ProjectInfo, IdeError>(crate::ops::project::info(&project))
|
||||
}
|
||||
});
|
||||
|
||||
dispatcher.add("project_trust_add_location", TrustClass::Always, |c| async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
c.host.trust.add_location(&path)?;
|
||||
Ok(Value::Null)
|
||||
});
|
||||
|
||||
// Launch & window lifecycle.
|
||||
let s = shell.clone();
|
||||
dispatcher.add("window_take_launch", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let Some(project) = s.take_launch(&c.window) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
Ok(json!({
|
||||
"project": IpcPath::from(project),
|
||||
"files": [],
|
||||
"remote": null,
|
||||
"settingsPage": null,
|
||||
"newProjects": false,
|
||||
"positions": [],
|
||||
"comparison": null,
|
||||
"diffWindow": null,
|
||||
"diff": null,
|
||||
"diffBeforeFiles": false,
|
||||
"deployment": null,
|
||||
"editor": null
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
dispatcher.add("window_complete_launch", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
|
||||
dispatcher.add("window_open_projects", TrustClass::Always, |c| async move {
|
||||
let current_root = c.host.project(&c.window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let list: Vec<OpenProject> = c
|
||||
.host
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|p| !p.light)
|
||||
.map(|p| OpenProject {
|
||||
name: p.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
current: current_root.as_ref() == Some(&p.root),
|
||||
root: p.root.clone(),
|
||||
remote: None,
|
||||
})
|
||||
.collect();
|
||||
Ok(list)
|
||||
});
|
||||
|
||||
dispatcher.add("window_open_project", TrustClass::Always, |_| async move { Ok(json!({ "kind": "current" })) });
|
||||
|
||||
dispatcher.add("window_open_files", TrustClass::Always, |c| async move {
|
||||
let files: Vec<IpcPath> = c.arg("files")?;
|
||||
Ok(files)
|
||||
});
|
||||
|
||||
dispatcher.add("window_is_fullscreen", TrustClass::Always, |_| async move { Ok(false) });
|
||||
dispatcher.add("window_close_context", TrustClass::Always, |_| async move {
|
||||
Ok(CloseContext { quitting: false, windows: 1 })
|
||||
});
|
||||
for (noop, trust) in [
|
||||
("window_set_titlebar_height", Always),
|
||||
("window_set_smooth_scrolling", Always),
|
||||
("window_flash_taskbar", Always),
|
||||
("window_cycle", Always),
|
||||
("menu_configure", Always),
|
||||
("menu_refresh", Always),
|
||||
("menu_set_disabled", Always),
|
||||
("show_system_notification", Trusted),
|
||||
("window_group_cancel_close", Always),
|
||||
("window_group_restore", Always),
|
||||
("plugin_subscribe", Always),
|
||||
("plugin_activation_event", Trusted),
|
||||
("plugin_set_theme_frame", Always),
|
||||
] {
|
||||
dispatcher.add(noop, trust, |_| async move { Ok(Value::Null) });
|
||||
}
|
||||
for (noop_false, trust) in [
|
||||
("window_toggle_fullscreen", Always),
|
||||
("window_toggle_zoom", Always),
|
||||
("window_start_drag", Always),
|
||||
("window_drag_files", Always),
|
||||
("file_dialog_needs_gtk", Trusted),
|
||||
("clipboard_has_files", Always),
|
||||
("clipboard_has_image", Always),
|
||||
] {
|
||||
dispatcher.add(noop_false, trust, |_| async move { Ok(false) });
|
||||
}
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("menu_model", TrustClass::Always, move |_| {
|
||||
let s = s.clone();
|
||||
async move { Ok(web_menu_model(&s.recent.list())) }
|
||||
});
|
||||
|
||||
// Empty desktop-only collections so UI components render cleanly without errors.
|
||||
for (empty_list, trust) in [
|
||||
("window_group_current", Always),
|
||||
("system_font_families", Always),
|
||||
("system_probe_hotkeys", Trusted),
|
||||
("wsl_distros", Always),
|
||||
("web_browsers", Always),
|
||||
("plugin_catalog", Always),
|
||||
("plugin_installed_intellij_themes", Always),
|
||||
("git_credentials", Always),
|
||||
("android_devices", Trusted),
|
||||
("clipboard_file_list", Always),
|
||||
] {
|
||||
dispatcher.add(empty_list, trust, |_| async move { Ok(Vec::<Value>::new()) });
|
||||
}
|
||||
|
||||
for (null_opt, trust) in [
|
||||
("wsl_resolve", Always),
|
||||
("remote_current", Always),
|
||||
("plugin_market_url", Always),
|
||||
("clipboard_text", Trusted),
|
||||
("clipboard_image", Always),
|
||||
] {
|
||||
dispatcher.add(null_opt, trust, |_| async move { Ok(Value::Null) });
|
||||
}
|
||||
|
||||
dispatcher.add("plugin_list", TrustClass::Always, |_| async move {
|
||||
Ok(json!({ "plugins": [], "activeTheme": null, "ui": [] }))
|
||||
});
|
||||
|
||||
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
|
||||
let current = c.host.local_data_dir.to_string_lossy().into_owned();
|
||||
Ok(LocalDataInfo {
|
||||
default_dir: current.clone(),
|
||||
current,
|
||||
custom_root: None,
|
||||
env_override: std::env::var_os("OPENIDEA_SERVER_HOME").is_some(),
|
||||
})
|
||||
});
|
||||
|
||||
dispatcher.add("caches_schedule_invalidation", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
|
||||
dispatcher.add("lsp_restart_named", TrustClass::Trusted, |c| async move {
|
||||
let name: String = c.arg("name")?;
|
||||
crate::ops::lsp::lsp_restart_named(&c.host, &name).await?;
|
||||
Ok(Value::Null)
|
||||
});
|
||||
|
||||
dispatcher.add("web_serves_page", TrustClass::Trusted, |c| async move {
|
||||
let url: String = c.arg("url")?;
|
||||
Ok(crate::ops::web::serves_page(&url).await)
|
||||
});
|
||||
|
||||
dispatcher.add("workspace_discover_projects", TrustClass::Always, |c| async move {
|
||||
let request: RequestId = c.arg("request")?;
|
||||
let folders: Vec<PathBuf> = c.arg("folders")?;
|
||||
let cancel = c.host.begin_request(request);
|
||||
let result = c.host.blocking(move || ide_workspace::project_discovery::discover(folders, &cancel)).await;
|
||||
c.host.end_request(request);
|
||||
result
|
||||
});
|
||||
|
||||
dispatcher.add("workspace_create", TrustClass::Always, |c| async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
let name: String = c.arg("name")?;
|
||||
let projects: Vec<PathBuf> = c.arg("projects")?;
|
||||
c.host
|
||||
.blocking(move || {
|
||||
ide_workspace::workspace::Workspace::save(&path, &name, projects, true)?;
|
||||
Ok(IpcPath::from(dunce::canonicalize(path)?))
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("workspace_update", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let name: String = c.arg("name")?;
|
||||
let projects: Vec<PathBuf> = c.arg("projects")?;
|
||||
let (host, window) = (c.host.clone(), c.window.clone());
|
||||
let info =
|
||||
c.host.blocking(move || crate::ops::project::save_workspace(&host, &window, &name, projects)).await?;
|
||||
if let Ok(project) = c.host.project(&c.window) {
|
||||
s.record_project(&project);
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
});
|
||||
|
||||
let s = shell.clone();
|
||||
dispatcher.add("workspace_attach", TrustClass::Always, move |c| {
|
||||
let s = s.clone();
|
||||
async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
let (host, window) = (c.host.clone(), c.window.clone());
|
||||
let root = c.host.blocking(move || crate::ops::project::attach_workspace(&host, &window, &path)).await?;
|
||||
if let Ok(project) = c.host.project(&c.window) {
|
||||
s.record_project(&project);
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
});
|
||||
|
||||
dispatcher.add("http_requests", TrustClass::Trusted, |c| async move {
|
||||
let text: String = c.arg("text")?;
|
||||
Ok(ide_http::parse::requests(&text))
|
||||
});
|
||||
|
||||
dispatcher.add("http_from_curl", TrustClass::Trusted, |c| async move {
|
||||
let command: String = c.arg("command")?;
|
||||
Ok(ide_http::curl::from_curl(&command))
|
||||
});
|
||||
|
||||
dispatcher.add("ssh_askpass_answer", TrustClass::Always, |_| async move { Ok(Value::Null) });
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,109 @@ fn write(root: &Path, rel: &str, text: &str) {
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn pom_launch_uses_dependency_classpath_without_a_java_project() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
|
||||
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return;
|
||||
}
|
||||
for (jdtls, delegate) in [(false, false), (true, false), (true, true)] {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let pom = include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml")
|
||||
.replace("</modules>", "<module>assembly</module></modules>");
|
||||
write(&root, "pom.xml", &pom);
|
||||
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(
|
||||
&root,
|
||||
"assembly/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion>
|
||||
<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>
|
||||
<artifactId>assembly</artifactId><packaging>pom</packaging>
|
||||
<dependencies>
|
||||
<dependency><groupId>t</groupId><artifactId>app</artifactId><version>1</version><scope>runtime</scope></dependency>
|
||||
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.36</version></dependency>
|
||||
</dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
);
|
||||
let main = "package a;\npublic class A { public static void main(String[] args) throws Exception { Class.forName(\"org.slf4j.Logger\"); System.out.println(l.L.name()); } }\n";
|
||||
write(&root, "app/src/main/java/a/A.java", main);
|
||||
let global = SettingsStore::load(&base.join("config"), None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(
|
||||
SettingsScope::Global,
|
||||
&format!("languageServers.{server}.enabled"),
|
||||
serde_json::json!(server == "jdtls" && jdtls),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
global.set(SettingsScope::Global, "languages.java.maven.delegateBuild", serde_json::json!(delegate)).unwrap();
|
||||
global
|
||||
.set(
|
||||
SettingsScope::Global,
|
||||
"languageServers.jdtls.command",
|
||||
serde_json::json!(root.join("must-not-start-jdtls")),
|
||||
)
|
||||
.unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let module = root.join("assembly");
|
||||
assert_eq!(host.project("main").unwrap().lsp.java_served_by_jdtls(&module), jdtls);
|
||||
|
||||
for (policy, debug) in [
|
||||
(BuildPolicy::Make, false),
|
||||
(BuildPolicy::NoBuild, false),
|
||||
(BuildPolicy::NoBuild, true),
|
||||
(BuildPolicy::Rebuild, true),
|
||||
] {
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
write(&root, "app/src/main/java/a/A.java", "this must not be compiled");
|
||||
} else {
|
||||
write(&root, "app/src/main/java/a/A.java", main);
|
||||
}
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
module.clone(),
|
||||
false,
|
||||
debug,
|
||||
policy,
|
||||
RequestId::next(),
|
||||
ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event)),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("jdtls={jdtls}, delegate={delegate}, policy={policy:?}: {e:?}"));
|
||||
assert_eq!(info.build.is_some(), policy != BuildPolicy::NoBuild);
|
||||
assert!(info.class_paths.iter().any(|p| p.ends_with("slf4j-api-1.7.36.jar")), "{:?}", info.class_paths);
|
||||
assert!(!info.class_paths.iter().any(|p| p.contains("t.assembly/classes")), "{:?}", info.class_paths);
|
||||
let cp = std::env::join_paths(&info.class_paths).unwrap();
|
||||
let out = std::process::Command::new(info.java_exec.as_ref().expect("resolved Java executable"))
|
||||
.arg("-cp")
|
||||
.arg(cp)
|
||||
.arg("a.A")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "lib");
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
assert!(!events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Step { .. })));
|
||||
}
|
||||
}
|
||||
host.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
|
||||
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -27,24 +130,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
|
||||
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! A Maven build in an excluded folder (a `.worktrees` checkout of the same repository)
|
||||
//! repeats the coordinates of the project's own build. jdtls keeps one Eclipse project per
|
||||
//! name, so it must not import the excluded copy: Go to Definition and implementations would
|
||||
//! otherwise land in it instead of the project's sources.
|
||||
//!
|
||||
//! `#[ignore]`d because it needs jdtls on `PATH` and a JDK 21+:
|
||||
//! `cargo test -p ide-host --test jdtls_excluded_checkout -- --ignored`.
|
||||
|
||||
use ide_core::{IdeEvent, Pos};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_lsp::types::GotoKind;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
|
||||
fn pom(artifact: &str, deps: &str) -> String {
|
||||
format!(
|
||||
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\"><modelVersion>4.0.0</modelVersion>\
|
||||
<groupId>com.x</groupId><artifactId>{artifact}</artifactId><version>1.0</version>\
|
||||
<properties><maven.compiler.release>17</maven.compiler.release></properties>\
|
||||
<dependencies>{deps}</dependencies></project>"
|
||||
)
|
||||
}
|
||||
|
||||
fn write_lib(dir: &Path) -> std::path::PathBuf {
|
||||
let source = dir.join("src/main/java/lib/Foo.java");
|
||||
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
|
||||
std::fs::write(dir.join("pom.xml"), pom("lib", "")).unwrap();
|
||||
std::fs::write(&source, "package lib;\npublic class Foo {\n public static int answer() { return 42; }\n}\n")
|
||||
.unwrap();
|
||||
source
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "needs jdtls on PATH and a JDK 21+"]
|
||||
async fn excluded_checkout_does_not_shadow_the_projects_own_build() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
// The opened folder has no build of its own; its builds sit side by side.
|
||||
let root = base.join("workspace");
|
||||
let own = write_lib(&root.join("lib"));
|
||||
write_lib(&root.join(".worktrees/topic/lib"));
|
||||
// Only in the checkout: imported at all, it shows the folder was scanned.
|
||||
let extra = root.join(".worktrees/topic/extra");
|
||||
std::fs::create_dir_all(&extra).unwrap();
|
||||
std::fs::write(extra.join("pom.xml"), pom("extra", "")).unwrap();
|
||||
let dep = "<dependency><groupId>com.x</groupId><artifactId>lib</artifactId><version>1.0</version></dependency>";
|
||||
let app = root.join("app/src/main/java/app/App.java");
|
||||
std::fs::create_dir_all(app.parent().unwrap()).unwrap();
|
||||
std::fs::write(root.join("app/pom.xml"), pom("app", dep)).unwrap();
|
||||
std::fs::write(
|
||||
&app,
|
||||
"package app;\nimport lib.Foo;\npublic class App {\n int run() { return Foo.answer(); }\n}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("app/config"),
|
||||
data_dir: base.join("app/data"),
|
||||
local_data_dir: base.join("app/data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new({
|
||||
let events = events.clone();
|
||||
move |_| {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().unwrap().push(e))
|
||||
}
|
||||
}),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project(WINDOW, &root).unwrap();
|
||||
let set =
|
||||
|key: &str, value: &str| ops::project::set_settings(&host, WINDOW, SettingsScope::Project, key, value).unwrap();
|
||||
set("projectStructure.excluded", r#"[".worktrees"]"#);
|
||||
set("languages.java.jdtlsShared", "true");
|
||||
let repo = base.join("m2").to_string_lossy().replace('\\', "/");
|
||||
set("languages.java.maven.localRepository", &serde_json::to_string(&repo).unwrap());
|
||||
|
||||
let doc = ops::doc::doc_open(&host, WINDOW, app.clone()).await.unwrap().id;
|
||||
// `Foo` in `return Foo.answer();`
|
||||
let at = Pos::new(3, 24);
|
||||
let deadline = Instant::now() + Duration::from_secs(420);
|
||||
let found = loop {
|
||||
let found = ops::lsp::lsp_goto(&host, WINDOW, doc, at, GotoKind::Definition).await;
|
||||
if let Ok(locs) = &found
|
||||
&& let Some(first) = locs.first()
|
||||
{
|
||||
break first.path.0.clone();
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no definition for Foo: {found:?}");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
};
|
||||
assert_eq!(found, own, "Foo resolved to the excluded checkout");
|
||||
let imported = imported_projects(&base.join("app/data"));
|
||||
assert!(imported.iter().any(|p| p.ends_with("/workspace/lib")), "lib not imported: {imported:?}");
|
||||
assert!(!imported.iter().any(|p| p.contains("/.worktrees/")), "imported the excluded checkout: {imported:?}");
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
/// The folders of the Eclipse projects jdtls has imported, from its workspaces under `data`.
|
||||
fn imported_projects(data: &Path) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
for entry in walkdir(data) {
|
||||
if entry.file_name().is_some_and(|n| n == ".location")
|
||||
&& let Ok(bytes) = std::fs::read(&entry)
|
||||
{
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
if let Some(at) = text.find("file:") {
|
||||
let path: String = text[at + 5..].chars().take_while(|c| !c.is_control()).collect();
|
||||
found.push(path.trim_end_matches('/').to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
fn walkdir(dir: &Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() { stack.push(path) } else { out.push(path) }
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, TextChange};
|
||||
use ide_core::{ChangeSet, Pos, Range, SymbolKind, TextChange};
|
||||
use ide_host::{Host, catalogue::TrustClass, ops};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -51,6 +51,33 @@ async fn edits_loose_files_without_project_services() {
|
||||
assert!(!Arc::ptr_eq(&project, &light));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn large_markdown_has_structure_after_embedded_images() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("paper.md");
|
||||
let image = format!("\n\n", "A".repeat(64 * 1024));
|
||||
let text = format!("# Paper\n\n{}```text\n## Inside code\n```\n\n## Results\n", image.repeat(84));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let host = host(&tmp.path().join("app"));
|
||||
host.open_light("main", &path).unwrap();
|
||||
|
||||
let doc = ops::doc::doc_open(&host, "main", path).await.unwrap();
|
||||
assert!(doc.large);
|
||||
let outline = ops::doc::doc_outline(&host, "main", doc.id).await.unwrap();
|
||||
|
||||
assert_eq!(outline.len(), 1);
|
||||
let paper = &outline[0];
|
||||
assert_eq!(paper.kind, SymbolKind::Key);
|
||||
assert_eq!(paper.name, "Paper");
|
||||
assert_eq!(paper.selection_range, Range::new(Pos::new(0, 2), Pos::new(0, 7)));
|
||||
assert_eq!(paper.children.len(), 1);
|
||||
let results = &paper.children[0];
|
||||
assert_eq!(results.kind, SymbolKind::Key);
|
||||
assert_eq!(results.name, "Results");
|
||||
assert_eq!(results.selection_range, Range::new(Pos::new(174, 3), Pos::new(174, 10)));
|
||||
assert!(results.children.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn light_windows_ignore_project_scoped_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -775,6 +775,42 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert!(result["output"].as_str().unwrap().contains("captured-output"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_configuration_left_running_is_stopped_by_its_run_id() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
id: "server".into(),
|
||||
name: "Server".into(),
|
||||
kind: "shell".into(),
|
||||
command: if cfg!(windows) { "ping -n 60 127.0.0.1" } else { "sleep 60" }.into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
h.host.mcp_requests.answer("main", id, true, None).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
assert!(result.get("exitCode").is_none());
|
||||
let id = result["runId"].as_u64().expect("a run left running carries its id");
|
||||
|
||||
let user_run = id + 1000;
|
||||
assert!(h.error("stop_run", json!({"runId": user_run})).await.contains("started by execute_run_configuration"));
|
||||
let stopped = h.json("stop_run", json!({"runId": id, "force": true, "timeout": 10000})).await;
|
||||
assert_eq!(stopped["state"], "stopped", "{stopped}");
|
||||
assert!(h.error("stop_run", json!({"runId": id})).await.contains("started by execute_run_configuration"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires rust-analyzer, like language_smoke::rust"]
|
||||
async fn rust_references_and_rename_through_mcp() {
|
||||
|
||||
@@ -274,7 +274,7 @@ async fn official_api_examples_install_and_render_real_component_contributions()
|
||||
ide_plugin::ProviderDocument { path: f.root.join("example.tests"), text: "test adds\n".into(), ..doc };
|
||||
assert!(eventually(|| {
|
||||
f.plugins
|
||||
.language_gutter_actions(&doc)
|
||||
.language_gutter_actions(&doc, Some(&f.root))
|
||||
.iter()
|
||||
.any(|(owner, action)| owner == "openidea.test-runner" && action.argument.as_deref() == Some("adds"))
|
||||
}));
|
||||
|
||||
@@ -376,3 +376,63 @@ async fn injected_lsp(host: &Host, plugins: &PluginHost, root: &Path, remote: &i
|
||||
peer.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/// Two open projects, one inside the other.
|
||||
struct Nested {
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
}
|
||||
impl ide_host::plugins::PluginWorkspace for Nested {
|
||||
fn projects(&self) -> Vec<std::path::PathBuf> {
|
||||
self.roots.clone()
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit], _: bool) -> Result<u64, ide_plugin::HostError> {
|
||||
Err(ide_plugin::HostError::NotFound("not open".into()))
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
fn publish_diagnostics(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &Path,
|
||||
_: Vec<ide_core::Diagnostic>,
|
||||
) -> Result<(), ide_plugin::HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gutter_actions_see_the_editors_window_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outer = dunce::canonicalize(tmp.path()).unwrap().join("outer");
|
||||
let inner = outer.join("inner");
|
||||
std::fs::create_dir_all(&inner).unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
p.set_workspace(Some(Arc::new(Nested { roots: vec![outer.clone(), inner.clone()] })));
|
||||
let doc = ProviderDocument {
|
||||
path: inner.join("Taskfile.txt"),
|
||||
language: "text".into(),
|
||||
version: 1,
|
||||
text: "build\n".into(),
|
||||
};
|
||||
let argument = |project: Option<&Path>| {
|
||||
let actions = p.language_gutter_actions(&doc, project);
|
||||
assert_eq!(actions.len(), 1);
|
||||
actions[0].1.argument.clone().unwrap()
|
||||
};
|
||||
// The outer project's window: the file is its, though the inner project holds it too.
|
||||
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
|
||||
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
|
||||
// No window, or a root that is no open project: no invoking project.
|
||||
assert_eq!(argument(None), "gutter");
|
||||
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! API 1.18 `[[contributes.runAnything]]`: lines starting with a plugin's prefix are
|
||||
//! suggested and run by its `run-anything-provider` export; other lines are refused.
|
||||
use ide_host::plugins::{Consent, PluginHost};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
const ID: &str = "test.run-anything";
|
||||
|
||||
fn plugins(base: &Path) -> Arc<PluginHost> {
|
||||
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/run-anything");
|
||||
let p =
|
||||
Arc::new(PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap());
|
||||
p.install_from_dir(&fixture, &Consent::all()).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plugin_suggests_and_claims_lines_of_its_prefix() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
let root = Some(tmp.path().to_path_buf());
|
||||
let labels = |text: &str| -> Vec<String> {
|
||||
p.run_anything_suggest(ID, "main", root.clone(), "task", text).unwrap().into_iter().map(|i| i.label).collect()
|
||||
};
|
||||
assert_eq!(labels("ta"), ["task build", "task test", "task docs:serve"]);
|
||||
assert_eq!(labels("task d"), ["task docs:serve"]);
|
||||
assert!(labels("task x").is_empty());
|
||||
// Only text for the declared prefix reaches the plugin.
|
||||
assert!(p.run_anything_suggest(ID, "main", root.clone(), "make", "make").is_err());
|
||||
assert!(p.run_anything_suggest(ID, "main", root.clone(), "task", "echo task").is_err());
|
||||
|
||||
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "task build").unwrap());
|
||||
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "task docs:serve ").unwrap());
|
||||
// Left to the shell by the plugin.
|
||||
assert!(!p.run_anything_run(ID, "main", root.clone(), "task", "task deploy").unwrap());
|
||||
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "tasks build").is_err());
|
||||
|
||||
let invocation = Invocation { workspace_root: root, ..Default::default() };
|
||||
let ran = p.run_command(ID, "ran", None, invocation).unwrap();
|
||||
assert_eq!(ran.as_deref(), Some("build\ndocs:serve"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (root, other) = (base.join("project"), base.join("other"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(root.join("Taskfile.yml"), "version: '3'\n").unwrap();
|
||||
let p = plugins(&base);
|
||||
let config = "plugin:test.run-anything:tasks";
|
||||
// Not provided until its program is approved.
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
|
||||
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
|
||||
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
|
||||
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|c| (c.label, c.insert, c.replace_start, c.replace_end))
|
||||
.collect()
|
||||
};
|
||||
// Options, quoted values and the task's own arguments after `--` stay outside the range.
|
||||
let text = "--dry 'a b' d -- x";
|
||||
assert_eq!(complete(text, 13), [("docs:serve".into(), "docs:serve".into(), 12, 13)]);
|
||||
assert!(complete(text, 18).is_empty(), "after `--` the arguments are the task's");
|
||||
assert!(complete(text, 3).is_empty(), "an option is not a task");
|
||||
// UTF-16 offsets.
|
||||
assert_eq!(complete("é b", 3), [("build".into(), "build".into(), 2, 3)]);
|
||||
assert_eq!(complete("", 0).len(), 3);
|
||||
assert!(p.run_configuration_complete("main", &root, config, "env", "b", 1).unwrap().is_empty());
|
||||
// Out-of-range carets, other configurations and projects without it are refused.
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 2).is_err());
|
||||
assert!(
|
||||
p.run_configuration_complete("main", &root, "plugin:test.run-anything:other", "arguments", "b", 1).is_err()
|
||||
);
|
||||
assert!(p.run_configuration_complete("main", &root, "npm:dev", "arguments", "b", 1).is_err());
|
||||
assert!(p.run_configuration_complete("main", &other, config, "arguments", "b", 1).is_err());
|
||||
// Revoking the program withdraws the configuration, and with it the completion.
|
||||
p.set_capability(ID, "process:task", false).unwrap();
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! `events.watch-paths` (API 1.18): files outside a project, within `fs.read` grants,
|
||||
//! per window project, ending with the project, the window, or the grant.
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_host::plugins::{Consent, PluginHost, PluginWorkspace};
|
||||
use ide_plugin::{FilesChanged, HostError, Invocation, Limits};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ID: &str = "watch-paths";
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/watch-paths")
|
||||
}
|
||||
|
||||
/// Windows and the project each shows.
|
||||
#[derive(Default)]
|
||||
struct Windows(Mutex<BTreeMap<String, PathBuf>>);
|
||||
|
||||
impl PluginWorkspace for Windows {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
let mut roots: Vec<PathBuf> = self.0.lock().values().cloned().collect();
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
roots
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit], _: bool) -> Result<u64, HostError> {
|
||||
Err(HostError::NotFound("not open".into()))
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf> {
|
||||
self.0.lock().get(window).cloned()
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
_tmp: tempfile::TempDir,
|
||||
host: PluginHost,
|
||||
windows: Arc<Windows>,
|
||||
outer: PathBuf,
|
||||
inner: PathBuf,
|
||||
external: PathBuf,
|
||||
}
|
||||
|
||||
/// An `outer` project with an `inner` one nested in it, each in its own window, and
|
||||
/// an `external` directory outside both that the plugin may read (and `outer` too
|
||||
/// with `grant_outer`).
|
||||
fn setup() -> Setup {
|
||||
setup_granting(false)
|
||||
}
|
||||
|
||||
fn setup_granting(grant_outer: bool) -> Setup {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (outer, external) = (base.join("outer"), base.join("external"));
|
||||
let inner = outer.join("inner");
|
||||
std::fs::create_dir_all(&inner).unwrap();
|
||||
std::fs::create_dir_all(external.join("inc")).unwrap();
|
||||
std::fs::write(external.join("Taskfile.yml"), "version: '3'\n").unwrap();
|
||||
std::fs::write(base.join("secret.yml"), "no").unwrap();
|
||||
let package = base.join("package");
|
||||
copy_dir(&fixture(), &package);
|
||||
let manifest = package.join("plugin.toml");
|
||||
let mut grants = format!("\"fs.read:{}\"", to_ipc(&external));
|
||||
if grant_outer {
|
||||
grants += &format!(", \"fs.read:{}\"", to_ipc(&outer));
|
||||
}
|
||||
let text = std::fs::read_to_string(&manifest).unwrap().replace("\"fs.read:/opt/watched\"", &grants);
|
||||
std::fs::write(&manifest, text).unwrap();
|
||||
let host = PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap();
|
||||
let windows = Arc::new(Windows::default());
|
||||
windows.0.lock().insert("outer".into(), outer.clone());
|
||||
windows.0.lock().insert("inner".into(), inner.clone());
|
||||
host.set_workspace(Some(windows.clone()));
|
||||
host.load_all();
|
||||
host.startup_finished();
|
||||
host.install_from_dir(&package, &Consent::all()).unwrap();
|
||||
Setup { _tmp: tmp, host, windows, outer, inner, external }
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for entry in std::fs::read_dir(from).unwrap().flatten() {
|
||||
let (src, dst) = (entry.path(), to.join(entry.file_name()));
|
||||
if entry.file_name() == "target" {
|
||||
continue;
|
||||
}
|
||||
if src.is_dir() { copy_dir(&src, &dst) } else { std::fs::copy(&src, &dst).map(|_| ()).unwrap() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Setup {
|
||||
fn watch(&self, window: &str, paths: &[&Path]) -> Result<(), String> {
|
||||
let arg = paths.iter().map(|p| to_ipc(p)).collect::<Vec<_>>().join("\n");
|
||||
let inv = Invocation {
|
||||
client: Some(window.into()),
|
||||
workspace_root: self.windows.project_of(window),
|
||||
..Default::default()
|
||||
};
|
||||
self.host.run_command(ID, "watch", Some(&arg), inv).map(|_| ()).map_err(|e| e.message)
|
||||
}
|
||||
|
||||
fn received(&self) -> Vec<FilesChanged> {
|
||||
let stored = self.host.run_command(ID, "events", None, Invocation::default()).unwrap();
|
||||
stored.map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Delivers what the watchers saw until `done` holds (10 s at most).
|
||||
fn until(&self, mut done: impl FnMut(&[FilesChanged]) -> bool) -> Vec<FilesChanged> {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
self.host.flush_events();
|
||||
self.host.wait_events(Duration::from_secs(5));
|
||||
let received = self.received();
|
||||
if done(&received) || Instant::now() > deadline {
|
||||
return received;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// What arrives within the time a watcher reports a change.
|
||||
fn settle(&self) -> Vec<FilesChanged> {
|
||||
let deadline = Instant::now() + Duration::from_millis(2500);
|
||||
while Instant::now() < deadline {
|
||||
self.host.flush_events();
|
||||
self.host.wait_events(Duration::from_secs(5));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
self.received()
|
||||
}
|
||||
}
|
||||
|
||||
fn changed(batches: &[FilesChanged]) -> Vec<String> {
|
||||
let mut paths: Vec<String> =
|
||||
batches.iter().flat_map(|b| b.created.iter().chain(&b.modified).chain(&b.removed).cloned()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_to_watched_files_and_directory_entries_reach_the_plugin() {
|
||||
let s = setup();
|
||||
let (taskfile, inc) = (s.external.join("Taskfile.yml"), s.external.join("inc"));
|
||||
s.watch("outer", &[&taskfile, &inc]).unwrap();
|
||||
// Let the watchers start before changing anything.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::write(&taskfile, "version: '3'\ntasks: {}\n").unwrap();
|
||||
std::fs::write(inc.join("common.yml"), "tasks: {}\n").unwrap();
|
||||
std::fs::write(s.external.join("unwatched.yml"), "").unwrap();
|
||||
std::fs::create_dir_all(inc.join("deep")).unwrap();
|
||||
std::fs::write(inc.join("deep/below.yml"), "").unwrap();
|
||||
let want = [to_ipc(&taskfile), to_ipc(&inc.join("common.yml"))];
|
||||
let received = s.until(|b| want.iter().all(|w| changed(b).contains(w)));
|
||||
let paths = changed(&received);
|
||||
assert!(want.iter().all(|w| paths.contains(w)), "{paths:?}");
|
||||
assert!(!paths.contains(&to_ipc(&s.external.join("unwatched.yml"))), "{paths:?}");
|
||||
assert!(!paths.contains(&to_ipc(&inc.join("deep/below.yml"))), "directories are watched flat: {paths:?}");
|
||||
assert!(received.iter().all(|b| b.project.as_deref() == Some(to_ipc(&s.outer).as_str())));
|
||||
|
||||
// Removal and re-creation of a watched file (an atomic save) keep it watched.
|
||||
std::fs::remove_file(&taskfile).unwrap();
|
||||
let gone = s.until(|b| b.iter().any(|b| b.removed.contains(&to_ipc(&taskfile))));
|
||||
assert!(gone.iter().any(|b| b.removed.contains(&to_ipc(&taskfile))));
|
||||
let before = gone.len();
|
||||
std::fs::write(&taskfile, "version: '3'\n").unwrap();
|
||||
let back = s.until(|b| {
|
||||
b[before..].iter().any(|b| b.created.contains(&to_ipc(&taskfile)) || b.modified.contains(&to_ipc(&taskfile)))
|
||||
});
|
||||
assert!(back.len() > before, "re-created file reported");
|
||||
|
||||
// An empty list stops watching.
|
||||
s.watch("outer", &[]).unwrap();
|
||||
let count = s.received().len();
|
||||
std::fs::write(&taskfile, "version: '3'\n# stopped\n").unwrap();
|
||||
assert_eq!(s.settle().len(), count);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watch_paths_refuses_what_the_plugin_may_not_read_or_already_gets() {
|
||||
let s = setup();
|
||||
let base = s.external.parent().unwrap().to_path_buf();
|
||||
let err = s.watch("outer", &[&base.join("secret.yml")]).unwrap_err();
|
||||
assert!(err.contains("fs.read"), "{err}");
|
||||
// Checked where it really is: a link inside the grant to a file outside it.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(base.join("secret.yml"), s.external.join("link.yml")).unwrap();
|
||||
let err = s.watch("outer", &[&s.external.join("link.yml")]).unwrap_err();
|
||||
assert!(err.contains("fs.read"), "{err}");
|
||||
}
|
||||
let err = s.watch("outer", &[&s.external.join("missing.yml")]).unwrap_err();
|
||||
assert!(err.contains("no such file"), "{err}");
|
||||
let many: Vec<PathBuf> = (0..33).map(|_| s.external.join("Taskfile.yml")).collect();
|
||||
let err = s.watch("outer", &many.iter().map(PathBuf::as_path).collect::<Vec<_>>()).unwrap_err();
|
||||
assert!(err.contains("at most 32"), "{err}");
|
||||
// No window project to belong to.
|
||||
let inv = Invocation { client: None, workspace_root: None, ..Default::default() };
|
||||
let err = s.host.run_command(ID, "watch", Some(&to_ipc(&s.external.join("Taskfile.yml"))), inv).unwrap_err();
|
||||
assert!(err.message.contains("window's project"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_files_are_refused_and_nested_projects_watch_apart() {
|
||||
// The outer project is granted too: the refusal is about the project, not the grant.
|
||||
let s = setup_granting(true);
|
||||
std::fs::write(s.inner.join("Taskfile.yml"), "").unwrap();
|
||||
std::fs::write(s.outer.join("Taskfile.yml"), "").unwrap();
|
||||
let err = s.watch("inner", &[&s.inner.join("Taskfile.yml")]).unwrap_err();
|
||||
assert!(err.contains("inside the project"), "{err}");
|
||||
let err = s.watch("outer", &[&s.inner.join("Taskfile.yml")]).unwrap_err();
|
||||
assert!(err.contains("inside the project"), "a nested project's files are the outer project's too: {err}");
|
||||
// From the inner window, the outer project's files are outside its project.
|
||||
s.watch("inner", &[&s.outer.join("Taskfile.yml")]).unwrap();
|
||||
|
||||
let (taskfile, inc) = (s.external.join("Taskfile.yml"), s.external.join("inc"));
|
||||
s.watch("inner", &[&taskfile]).unwrap();
|
||||
s.watch("outer", &[&inc]).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::write(&taskfile, "version: '3'\n# inner\n").unwrap();
|
||||
std::fs::write(inc.join("outer.yml"), "").unwrap();
|
||||
let received = s.until(|b| {
|
||||
b.iter().any(|b| b.project.as_deref() == Some(to_ipc(&s.inner).as_str()))
|
||||
&& b.iter().any(|b| b.project.as_deref() == Some(to_ipc(&s.outer).as_str()))
|
||||
});
|
||||
for batch in &received {
|
||||
let paths = changed(std::slice::from_ref(batch));
|
||||
if batch.project.as_deref() == Some(to_ipc(&s.inner).as_str()) {
|
||||
assert_eq!(paths, [to_ipc(&taskfile)], "inner's watch sees only its file");
|
||||
} else {
|
||||
assert_eq!(batch.project.as_deref(), Some(to_ipc(&s.outer).as_str()));
|
||||
assert_eq!(paths, [to_ipc(&inc.join("outer.yml"))], "outer's watch sees only its directory");
|
||||
}
|
||||
}
|
||||
|
||||
// Closing the inner project ends its watch only.
|
||||
s.windows.0.lock().remove("inner");
|
||||
s.host.project_closed(&s.inner, "inner");
|
||||
let count = s.received().len();
|
||||
std::fs::write(&taskfile, "version: '3'\n# closed\n").unwrap();
|
||||
std::fs::write(inc.join("still.yml"), "").unwrap();
|
||||
let after = s.until(|b| b.len() > count && changed(&b[count..]).contains(&to_ipc(&inc.join("still.yml"))));
|
||||
let later = changed(&after[count..]);
|
||||
assert!(later.contains(&to_ipc(&inc.join("still.yml"))), "{later:?}");
|
||||
assert!(!later.contains(&to_ipc(&taskfile)), "the closed project's watch ended: {later:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watches_end_when_the_window_closes_or_the_grant_is_revoked() {
|
||||
let s = setup();
|
||||
let taskfile = s.external.join("Taskfile.yml");
|
||||
s.watch("outer", &[&taskfile]).unwrap();
|
||||
s.host.forget_client("outer");
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::write(&taskfile, "version: '3'\n# window closed\n").unwrap();
|
||||
assert!(s.settle().is_empty(), "the closed window's watch ended");
|
||||
|
||||
s.watch("inner", &[&taskfile]).unwrap();
|
||||
s.host.set_capability(ID, &format!("fs.read:{}", to_ipc(&s.external)), false).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::write(&taskfile, "version: '3'\n# revoked\n").unwrap();
|
||||
assert!(s.settle().is_empty(), "revoking the grant ends the watch");
|
||||
let err = s.watch("inner", &[&taskfile]).unwrap_err();
|
||||
assert!(err.contains("fs.read"), "{err}");
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::TextQuery;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct Harness {
|
||||
host: Arc<Host>,
|
||||
@@ -366,6 +367,364 @@ async fn plugin_run_targets_register_prompt_route_revalidate_and_withdraw() {
|
||||
plugins.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_run_output_mode_precedence_and_disallowed_combinations() {
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
|
||||
let f = Harness::new();
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
std::fs::write(f.root.join("execution-output.marker"), "").unwrap();
|
||||
|
||||
let events = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
let captured = events.clone();
|
||||
let plugins = Arc::new(
|
||||
PluginHost::new(
|
||||
f._tmp.path().join("plugins"),
|
||||
Arc::new(move |client: Option<&str>, event: PluginEvent| {
|
||||
captured.lock().push((client.map(str::to_owned), event))
|
||||
}),
|
||||
Limits::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
plugins.set_workspace(Some(Arc::new(f.workspace())));
|
||||
f.host.set_plugin_host(&plugins);
|
||||
|
||||
let package = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/execution-output");
|
||||
plugins.install_from_dir(&package, &Consent::all()).unwrap();
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
plugins.choose_program("test.execution-output", "process:execution-tool", Some(&f.root), Some(&exe)).unwrap();
|
||||
|
||||
plugins.refresh_run_configurations(&f.root);
|
||||
let detected = plugins.run_detection().detect(&f.root);
|
||||
let by_id =
|
||||
|id: &str| detected.iter().find(|c| c.id == format!("plugin:test.execution-output:{id}")).unwrap().clone();
|
||||
assert!(by_id("detector-pty").extras.emulate_terminal);
|
||||
assert!(!by_id("detector-pipes").extras.emulate_terminal);
|
||||
assert!(by_id("pty-default").extras.emulate_terminal);
|
||||
assert!(!by_id("pipes-default").extras.emulate_terminal);
|
||||
assert!(!by_id("test-pipes").extras.emulate_terminal);
|
||||
|
||||
let invoke = |cmd: &str, arg: &str| {
|
||||
events.lock().clear();
|
||||
let inv =
|
||||
Invocation { client: Some("main".into()), workspace_root: Some(f.root.clone()), ..Default::default() };
|
||||
let res = plugins.run_command("test.execution-output", cmd, Some(arg), inv);
|
||||
let req = events.lock().iter().find_map(|(client, event)| match event {
|
||||
PluginEvent::WindowRequest { request: WindowRequest::Run { config, debug, .. }, .. } => {
|
||||
assert_eq!(client.as_deref(), Some("main"));
|
||||
Some((config.as_ref().clone(), *debug))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
(res, req)
|
||||
};
|
||||
|
||||
// 1. Plugin default applies when invocation passes None (including legacy `run.start`).
|
||||
let (res, req) = invoke("start", "pty-default|default|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(req.unwrap().0.extras.emulate_terminal);
|
||||
let (res, req) = invoke("start-legacy", "pty-default");
|
||||
assert!(res.is_ok());
|
||||
assert!(req.unwrap().0.extras.emulate_terminal);
|
||||
let (res, req) = invoke("start", "pipes-default|default|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(!req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
// 2. Per-invocation override wins over plugin default.
|
||||
let (res, req) = invoke("start", "pty-default|pipes|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(!req.unwrap().0.extras.emulate_terminal);
|
||||
let (res, req) = invoke("start", "pipes-default|pty|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
// 3. Disallowed combinations: debug + pty, test + pty, stdin_file + pty, remote target + pty.
|
||||
let (res, req) = invoke("start", "pty-default|pty|debug");
|
||||
assert!(res.unwrap_err().message.contains("debugging"));
|
||||
assert!(req.is_none());
|
||||
// Debug without explicit Pty keeps debugging working with pipes.
|
||||
let (res, req) = invoke("start", "pty-default|default|debug");
|
||||
assert!(res.is_ok());
|
||||
let (cfg, debug) = req.unwrap();
|
||||
assert!(debug && !cfg.extras.emulate_terminal);
|
||||
|
||||
let (res, req) = invoke("start", "test-pipes|pty|run");
|
||||
assert!(res.unwrap_err().message.contains("test"));
|
||||
assert!(req.is_none());
|
||||
|
||||
// Redirected stdin rejects PTY, whereas a user-saved Pipes override with stdin_file runs cleanly.
|
||||
let mut stdin_pty = by_id("pty-default");
|
||||
stdin_pty.extras.stdin_file = Some("input.txt".into());
|
||||
ide_run::save_user_configs(&f.root, &[stdin_pty]).unwrap();
|
||||
let (res, req) = invoke("start", "pty-default|default|run");
|
||||
assert!(res.unwrap_err().message.contains("redirected"));
|
||||
assert!(req.is_none());
|
||||
|
||||
let mut stdin_pipes = by_id("pipes-default");
|
||||
stdin_pipes.extras.stdin_file = Some("input.txt".into());
|
||||
ide_run::save_user_configs(&f.root, &[stdin_pipes]).unwrap();
|
||||
let (res, req) = invoke("start", "pipes-default|pty|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(!req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
// Remote run target rejects PTY.
|
||||
let mut remote_pty = by_id("pty-default");
|
||||
remote_pty.extras.target = Some("ssh:prod".into());
|
||||
ide_run::save_user_configs(&f.root, &[remote_pty]).unwrap();
|
||||
let (res, req) = invoke("start", "pty-default|default|run");
|
||||
assert!(res.unwrap_err().message.contains("target"));
|
||||
assert!(req.is_none());
|
||||
|
||||
// 4. User-saved output-mode override wins over both invocation and plugin default.
|
||||
let mut user_pipes = by_id("pty-default");
|
||||
user_pipes.extras.emulate_terminal = false;
|
||||
let mut user_pty = by_id("pipes-default");
|
||||
user_pty.extras.emulate_terminal = true;
|
||||
ide_run::save_user_configs(&f.root, &[user_pipes, user_pty]).unwrap();
|
||||
|
||||
let (res, req) = invoke("start", "pty-default|pty|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(!req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
let (res, req) = invoke("start", "pipes-default|pipes|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
// 5. Removing user overrides restores plugin default behavior; untrusted projects refuse launches.
|
||||
ide_run::save_user_configs(&f.root, &[]).unwrap();
|
||||
let (res, req) = invoke("start", "pty-default|default|run");
|
||||
assert!(res.is_ok());
|
||||
assert!(req.unwrap().0.extras.emulate_terminal);
|
||||
|
||||
f.host.set_project_trust(&f.root, false, false).await.unwrap();
|
||||
assert!(invoke("start", "pty-default|default|run").0.is_err());
|
||||
|
||||
plugins.shutdown();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop() {
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let f = Harness::new();
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
std::fs::write(f.root.join("execution-output.marker"), "").unwrap();
|
||||
|
||||
let tool = f.root.with_file_name("exec-output-tool");
|
||||
std::fs::write(
|
||||
&tool,
|
||||
"#!/bin/sh\n\
|
||||
if [ \"$1\" = \"wait\" ]; then\n\
|
||||
read line\n\
|
||||
printf 'out:%s\\n' \"$line\"\n\
|
||||
printf 'err:%s\\n' \"$line\" >&2\n\
|
||||
exit 7\n\
|
||||
fi\n\
|
||||
if [ \"$1\" = \"hang\" ]; then\n\
|
||||
trap 'exit 0' INT TERM\n\
|
||||
printf 'ready\\n'\n\
|
||||
while true; do sleep 0.1; done\n\
|
||||
fi\n\
|
||||
printf 'out-line\\n'\n\
|
||||
printf 'err-line\\n' >&2\n\
|
||||
exit 0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let events = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
let captured = events.clone();
|
||||
let plugins = Arc::new(
|
||||
PluginHost::new(
|
||||
f._tmp.path().join("plugins"),
|
||||
Arc::new(move |client: Option<&str>, event: PluginEvent| {
|
||||
captured.lock().push((client.map(str::to_owned), event))
|
||||
}),
|
||||
Limits::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
plugins.set_workspace(Some(Arc::new(f.workspace())));
|
||||
f.host.set_plugin_host(&plugins);
|
||||
|
||||
let package = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/execution-output");
|
||||
plugins.install_from_dir(&package, &Consent::all()).unwrap();
|
||||
plugins.choose_program("test.execution-output", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap();
|
||||
plugins.refresh_run_configurations(&f.root);
|
||||
|
||||
let launch_and_collect = |arg: &str, stdin: Option<&str>, stop_after_ready: bool| {
|
||||
let host = f.host.clone();
|
||||
let plugins = plugins.clone();
|
||||
let events = events.clone();
|
||||
let root = f.root.clone();
|
||||
let arg = arg.to_owned();
|
||||
let stdin = stdin.map(str::to_owned);
|
||||
async move {
|
||||
events.lock().clear();
|
||||
let inv = Invocation { client: Some("main".into()), workspace_root: Some(root), ..Default::default() };
|
||||
let op_id = plugins.run_command("test.execution-output", "start", Some(&arg), inv).unwrap().unwrap();
|
||||
let config = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|(_, event)| match event {
|
||||
PluginEvent::WindowRequest { request: WindowRequest::Run { config, .. }, .. } => {
|
||||
Some(config.as_ref().clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let chunks = Arc::new(parking_lot::Mutex::new(Vec::<ide_run::OutputChunk>::new()));
|
||||
let out_chunks = chunks.clone();
|
||||
let info = ide_host::ops::run::run_start(
|
||||
&host,
|
||||
"main",
|
||||
config,
|
||||
ide_host::ops::Channel::new(move |c| out_chunks.lock().push(c)),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
if let Some(data) = stdin {
|
||||
ide_host::ops::run::run_stdin(&host, info.id, data).unwrap();
|
||||
}
|
||||
if stop_after_ready {
|
||||
for _ in 0..100 {
|
||||
if chunks
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|c| matches!(c, ide_run::OutputChunk::Stdout { text } if text.contains("ready")))
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
ide_host::ops::run::run_stop(&host, "main", info.id).unwrap();
|
||||
}
|
||||
for _ in 0..150 {
|
||||
if host.processes.list().iter().any(|r| r.id == info.id && !r.running) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
let exit = host.processes.exit_code(info.id).unwrap();
|
||||
let collected = chunks.lock().clone();
|
||||
(op_id, info, exit, collected)
|
||||
}
|
||||
};
|
||||
|
||||
// PTY run: combined stdout/stderr on stdout stream, stdin works, exit status 7 delivered.
|
||||
|
||||
// Default PTY run (`args: ["pty", "extra"]`): stdout and stderr arrive combined as Stdout chunks.
|
||||
let (_op, info, exit, chunks) = launch_and_collect("pty-default|default|run", None, false).await;
|
||||
assert!(info.pty);
|
||||
assert_eq!(exit, Some(Some(0)));
|
||||
let pty_stdout: String = chunks
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_run::OutputChunk::Stdout { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let pty_stderr: String = chunks
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_run::OutputChunk::Stderr { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(pty_stdout.contains("out-line") && pty_stdout.contains("err-line"), "{pty_stdout:?}");
|
||||
assert!(pty_stderr.is_empty(), "ordinary PTYs combine stdout and stderr: {pty_stderr:?}");
|
||||
|
||||
// Piped run (`args: ["pipes", "extra"]`): stdout and stderr stay separate.
|
||||
let (_op, info, exit, chunks) = launch_and_collect("pipes-default|default|run", None, false).await;
|
||||
assert!(!info.pty);
|
||||
assert_eq!(exit, Some(Some(0)));
|
||||
let pipe_stdout: String = chunks
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_run::OutputChunk::Stdout { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let pipe_stderr: String = chunks
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_run::OutputChunk::Stderr { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(pipe_stdout.contains("out-line"), "{pipe_stdout:?}");
|
||||
assert!(pipe_stderr.contains("err-line"), "{pipe_stderr:?}");
|
||||
|
||||
// Interactive PTY run with input + non-zero exit code + run-exited event.
|
||||
let mut wait_cfg = plugins
|
||||
.run_detection()
|
||||
.detect(&f.root)
|
||||
.into_iter()
|
||||
.find(|c| c.id == "plugin:test.execution-output:pty-default")
|
||||
.unwrap();
|
||||
wait_cfg.args = vec!["wait".into()];
|
||||
ide_run::save_user_configs(&f.root, &[wait_cfg]).unwrap();
|
||||
let (op_wait, info, exit, chunks) = launch_and_collect("pty-default|default|run", Some("hi\n"), false).await;
|
||||
assert!(info.pty);
|
||||
assert_eq!(exit, Some(Some(7)));
|
||||
let combined: String = chunks
|
||||
.iter()
|
||||
.filter_map(|c| match c {
|
||||
ide_run::OutputChunk::Stdout { text } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(combined.contains("out:hi") && combined.contains("err:hi"), "{combined:?}");
|
||||
|
||||
// Cancellation / stop on PTY run.
|
||||
let mut hang_cfg = plugins
|
||||
.run_detection()
|
||||
.detect(&f.root)
|
||||
.into_iter()
|
||||
.find(|c| c.id == "plugin:test.execution-output:pty-default")
|
||||
.unwrap();
|
||||
hang_cfg.args = vec!["hang".into()];
|
||||
ide_run::save_user_configs(&f.root, &[hang_cfg]).unwrap();
|
||||
let (op_stop, info, _exit, _chunks) = launch_and_collect("pty-default|default|run", None, true).await;
|
||||
assert!(info.pty);
|
||||
|
||||
plugins.flush_events_at(std::time::Instant::now() + Duration::from_secs(3));
|
||||
for _ in 0..50 {
|
||||
if plugins.wait_events(Duration::from_millis(50)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let recorded = plugins
|
||||
.run_command(
|
||||
"test.execution-output",
|
||||
"events",
|
||||
None,
|
||||
Invocation { client: Some("main".into()), workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let recorded: serde_json::Value = serde_json::from_str(&recorded).unwrap();
|
||||
let arr = recorded.as_array().unwrap();
|
||||
assert!(arr.iter().any(|e| {
|
||||
e["kind"] == "run-exited"
|
||||
&& serde_json::from_str::<serde_json::Value>(e["data"].as_str().unwrap())
|
||||
.is_ok_and(|d| d["id"] == op_wait && d["status"] == 7 && d["killed"] == false)
|
||||
}));
|
||||
assert!(arr.iter().any(|e| {
|
||||
e["kind"] == "run-exited"
|
||||
&& serde_json::from_str::<serde_json::Value>(e["data"].as_str().unwrap())
|
||||
.is_ok_and(|d| d["id"] == op_stop && d["killed"] == true)
|
||||
}));
|
||||
|
||||
plugins.shutdown();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn run_target_api15_overrides_and_frozen_api14_registration() {
|
||||
|
||||
@@ -1391,6 +1391,65 @@ fn ungranted_capabilities_are_denied_not_trapped() {
|
||||
assert_eq!(f.workspace.text("src/notes.txt"), "one two three\nfour five\n");
|
||||
}
|
||||
|
||||
/// A missing `agents` grant is an error the plugin can handle, not a trap.
|
||||
#[test]
|
||||
fn ungranted_agents_fork_is_denied_not_trapped() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&misbehave_pkg());
|
||||
let err = f
|
||||
.host
|
||||
.run_command("misbehave", "fork-session", Some("claude 11111111-2222-3333-4444-555555555555 /tmp"), f.inv())
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}");
|
||||
assert!(err.message.contains("agents"), "{err:?}");
|
||||
let info = f.host.info_of("misbehave").unwrap();
|
||||
assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on");
|
||||
assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing");
|
||||
}
|
||||
|
||||
/// With the `agents` grant the call reaches the core fork over a real project:
|
||||
/// an unknown session is the core's `not-found`, not a denial or a host stub.
|
||||
#[tokio::test]
|
||||
async fn granted_agents_fork_reaches_the_core() {
|
||||
let f = fixture(Limits::default());
|
||||
// Hermetic: the core scans the home transcript folders; a real ~/.codex with
|
||||
// thousands of rollouts would time the command out.
|
||||
// SAFETY: set before the Host reads HOME; nextest isolates this test's process.
|
||||
unsafe { std::env::set_var("HOME", f._tmp.path().join("home")) };
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: f._tmp.path().join("config"),
|
||||
data_dir: f._tmp.path().join("data"),
|
||||
local_data_dir: f._tmp.path().join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
host.trust.decide(&f.project, true, false).unwrap();
|
||||
host.open_project("main", &f.project).unwrap();
|
||||
f.host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
|
||||
// `misbehave` with the `agents` grant, which needs API 1.18.
|
||||
let pkg = f._tmp.path().join("misbehave-agents");
|
||||
copy_dir(&misbehave_pkg(), &pkg);
|
||||
let manifest = pkg.join("plugin.toml");
|
||||
let text = std::fs::read_to_string(&manifest).unwrap();
|
||||
let text = text
|
||||
.replace("required = [\"project.read\"]", "required = [\"project.read\", \"agents\"]")
|
||||
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\"");
|
||||
std::fs::write(&manifest, text).unwrap();
|
||||
f.install(&pkg);
|
||||
|
||||
let session = "11111111-2222-3333-4444-555555555555";
|
||||
let arg = format!("claude {session} {}", f.project.to_str().unwrap());
|
||||
let err = f.run("misbehave", "fork-session", Some(&arg)).unwrap_err();
|
||||
assert!(err.contains("unknown claude session"), "{err}");
|
||||
// Detached: the blocking close joins the LSP/index workers, which can stall under nextest.
|
||||
host.close_project_detached("main");
|
||||
}
|
||||
|
||||
/// A trap drops the instance, which restarts on next use after a
|
||||
/// backoff that doubles; only consecutive crashes stop the plugin.
|
||||
#[test]
|
||||
@@ -1652,7 +1711,7 @@ fn idle_instances_are_reclaimed_and_schedules_reactivate() {
|
||||
assert_eq!(f.host.instances(), 0);
|
||||
let info = f.host.info_of("misbehave").unwrap();
|
||||
assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1));
|
||||
assert_eq!(f.command_titles("misbehave").len(), 24, "contributions stay");
|
||||
assert_eq!(f.command_titles("misbehave").len(), 25, "contributions stay");
|
||||
assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y"));
|
||||
assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2);
|
||||
|
||||
@@ -2274,6 +2333,45 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
assert_eq!(launch(), (plain, vec![]));
|
||||
}
|
||||
|
||||
/// A Java agent bound to an executor (`executor = "Hot Reload"`, API 1.18): the plugin's
|
||||
/// "Run/Debug with Hot Reload" launches get it, plain launches don't, and the same grant
|
||||
/// and jar pin apply.
|
||||
#[test]
|
||||
fn an_executor_bound_java_agent_loads_only_through_its_executor() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("java-agent");
|
||||
copy_dir(&sample("java-agent"), &pkg);
|
||||
let manifest = std::fs::read_to_string(pkg.join("plugin.toml")).unwrap();
|
||||
let manifest = manifest
|
||||
.replace("^1.10", "^1.18")
|
||||
.replace("args = \"mode=test\"", "args = \"mode=test\"\nexecutor = \"Hot Reload\"");
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest).unwrap();
|
||||
|
||||
let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap();
|
||||
assert!(info.contributions.iter().any(|c| c.label == "fixture agent.jar=mode=test (Run with Hot Reload)"));
|
||||
let agent = info.java_agent.expect("agent metadata");
|
||||
assert_eq!(agent.executor.as_deref(), Some("Hot Reload"));
|
||||
assert!(!agent.approved);
|
||||
let source = f.host.java_agents();
|
||||
let ungranted = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent"));
|
||||
assert!(ungranted.options.is_empty());
|
||||
assert!(ungranted.notes[0].contains("needs the java.agent permission"), "{:?}", ungranted.notes);
|
||||
|
||||
f.host.set_capability("java-agent", "java.agent", true).unwrap();
|
||||
let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap();
|
||||
let option = format!("-javaagent:{}=mode=test", jar.display());
|
||||
let plain = ide_run::java_agent::for_executor(&source.agents(), None, None);
|
||||
assert_eq!(plain, ide_run::java_agent::Agents::default(), "a plain Run leaves it out");
|
||||
let through = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent"));
|
||||
assert_eq!(through.options, [option]);
|
||||
assert!(through.notes.is_empty());
|
||||
|
||||
f.host.set_enabled("java-agent", false).unwrap();
|
||||
let gone = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent"));
|
||||
assert!(gone.options.is_empty() && gone.notes.len() == 1);
|
||||
}
|
||||
|
||||
/// Compiled components are cached across runs (keyed by module and
|
||||
/// engine), so a cold activation only deserializes.
|
||||
#[test]
|
||||
@@ -6125,6 +6223,7 @@ fn files_changed_wakes_idle_once_and_keeps_every_delta() {
|
||||
created: vec![to_ipc(&f.project.join(format!("新建😀-{i}.rs")))],
|
||||
modified: vec![to_ipc(&f.project.join("shared.rs"))],
|
||||
removed: vec![to_ipc(&f.project.join("gone.rs"))],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
}
|
||||
@@ -6262,6 +6361,7 @@ fn files_changed_filters_each_category_before_waking_idle_plugins() {
|
||||
created: vec![path("src/unrelated.rs")],
|
||||
modified: vec![path("notes.txt")],
|
||||
removed: vec![path("elsewhere/a.yaml")],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
f.host.flush_events();
|
||||
@@ -6272,6 +6372,7 @@ fn files_changed_filters_each_category_before_waking_idle_plugins() {
|
||||
created: vec![path("config/new.yaml"), path("src/unrelated.rs")],
|
||||
modified: vec![path("config/changed.yaml"), path("notes.txt")],
|
||||
removed: vec![path("config/gone.yaml"), path("elsewhere/a.yaml")],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
f.host.flush_events();
|
||||
@@ -6284,6 +6385,7 @@ fn files_changed_filters_each_category_before_waking_idle_plugins() {
|
||||
created: vec![path("config/new.yaml")],
|
||||
modified: vec![path("config/changed.yaml")],
|
||||
removed: vec![path("config/gone.yaml")],
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -7626,7 +7728,7 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
|
||||
"id = \"acme.mixed-skills\"\n\
|
||||
name = \"Mixed Skills\"\n\
|
||||
version = \"1.0.0\"\n\
|
||||
engines.openidea = \"^1.15\"\n\n\
|
||||
engines.openidea = \"^1.18\"\n\n\
|
||||
[[contributes.skills]]\npath = \"skills/good-skill/SKILL.md\"\n\
|
||||
[[contributes.skills]]\npath = \"../outside/SKILL.md\"\n\
|
||||
[[contributes.skills]]\npath = \"skills/not-skill-md/README.md\"\n\
|
||||
|
||||
@@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!rejected.status.success());
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}");
|
||||
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
|
||||
let resumed = old_open().await;
|
||||
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
|
||||
@@ -798,6 +798,60 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
/// `--attach --replace` stops another build's backend that refuses to retire (#6119).
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn replace_stops_another_builds_busy_backend() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
const OLD_BUILD: &str = "fedcba9876543210";
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("h");
|
||||
let base = tmp.path().join("s");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
let mut previous_build = tokio::process::Command::new(SERVER)
|
||||
.arg("--daemon")
|
||||
.arg(&guard.0)
|
||||
.arg(OLD_BUILD)
|
||||
.envs(server_env(&home, &base, 10_800))
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
let old = Peer::connect(reader, writer, Arc::new(Client::default()));
|
||||
initialize(&old).await;
|
||||
let term = looping_terminal(&old, &project).await;
|
||||
old.kill();
|
||||
old.closed().await;
|
||||
|
||||
let client = Arc::new(Client::default());
|
||||
let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec();
|
||||
let env = server_env(&home, &base, 10_800);
|
||||
let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap();
|
||||
initialize(&new).await;
|
||||
let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap();
|
||||
assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}");
|
||||
until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
|
||||
assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty());
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
|
||||
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
|
||||
@@ -147,7 +147,7 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
@@ -157,6 +157,9 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
// Open and clean, but changed on disk before the watcher reported it.
|
||||
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
|
||||
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
@@ -175,6 +178,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,8 @@ pub(crate) fn mask_bit(b: u8) -> u64 {
|
||||
match b.to_ascii_lowercase() {
|
||||
c @ b'a'..=b'z' => 1 << (c - b'a'),
|
||||
c @ b'0'..=b'9' => 1 << (26 + c - b'0'),
|
||||
b'_' => 1 << 36,
|
||||
b'-' => 1 << 37,
|
||||
// One bit: file and folder matching takes `-` and `_` for each other.
|
||||
b'_' | b'-' => 1 << 36,
|
||||
b'.' => 1 << 38,
|
||||
b'/' => 1 << 39,
|
||||
b'$' => 1 << 40,
|
||||
|
||||
@@ -31,6 +31,8 @@ const TYPE_LIKE: u32 = 20;
|
||||
|
||||
thread_local! {
|
||||
static MATCHER: RefCell<Matcher> = RefCell::new(Matcher::new(Config::DEFAULT.match_paths()));
|
||||
/// An ASCII candidate with `_` read as `-`, for a folding [`Needle`].
|
||||
static FOLDED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn with_matcher<R>(f: impl FnOnce(&mut Matcher) -> R) -> R {
|
||||
@@ -43,30 +45,74 @@ struct Needle {
|
||||
original: String,
|
||||
utf32: Utf32String,
|
||||
mask: u64,
|
||||
/// A file or folder needle with `-` or `_`: either matches both in a candidate
|
||||
/// (`bit_matcher` finds `bit-matcher/`); both sides are matched with `_` read as `-`.
|
||||
fold: bool,
|
||||
}
|
||||
|
||||
impl Needle {
|
||||
fn new(s: &str) -> Self {
|
||||
let lower = s.to_lowercase();
|
||||
Self { mask: char_mask(&lower), utf32: Utf32String::from(lower.as_str()), lower, original: s.to_owned() }
|
||||
Self {
|
||||
mask: char_mask(&lower),
|
||||
utf32: Utf32String::from(lower.as_str()),
|
||||
lower,
|
||||
original: s.to_owned(),
|
||||
fold: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A needle for file and folder names, whose `-` and `_` match each other.
|
||||
fn file(s: &str) -> Self {
|
||||
let mut needle = Self::new(s);
|
||||
needle.fold = needle.lower.contains(['-', '_']);
|
||||
if needle.fold {
|
||||
needle.utf32 = Utf32String::from(needle.lower.replace('_', "-").as_str());
|
||||
}
|
||||
needle
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.lower.is_empty()
|
||||
}
|
||||
|
||||
/// `hay` as the matcher reads it; for a folding needle, a copy with `_` as `-`.
|
||||
fn hay<'a>(&self, hay: &'a str, buf: &'a mut Vec<char>) -> Utf32Str<'a> {
|
||||
if !self.fold {
|
||||
return Utf32Str::new(hay, buf);
|
||||
}
|
||||
// The same characters `Utf32Str::new` would give, so match indices stay valid.
|
||||
if matches!(Utf32Str::new(hay, &mut *buf), Utf32Str::Ascii(_)) {
|
||||
buf.clear();
|
||||
buf.extend(hay.bytes().map(char::from));
|
||||
}
|
||||
for c in buf.iter_mut() {
|
||||
if *c == '_' {
|
||||
*c = '-';
|
||||
}
|
||||
}
|
||||
Utf32Str::Unicode(buf)
|
||||
}
|
||||
|
||||
fn score(&self, m: &mut Matcher, hay: &str, buf: &mut Vec<char>) -> Option<u32> {
|
||||
m.fuzzy_match(Utf32Str::new(hay, buf), self.utf32.slice(..)).map(u32::from)
|
||||
m.fuzzy_match(self.hay(hay, buf), self.utf32.slice(..)).map(u32::from)
|
||||
}
|
||||
|
||||
/// `hay` is pure ASCII: skip `Utf32Str::new`'s check and UTF-32 conversion.
|
||||
fn score_ascii(&self, m: &mut Matcher, hay: &str) -> Option<u32> {
|
||||
m.fuzzy_match(Utf32Str::Ascii(hay.as_bytes()), self.utf32.slice(..)).map(u32::from)
|
||||
if !self.fold {
|
||||
return m.fuzzy_match(Utf32Str::Ascii(hay.as_bytes()), self.utf32.slice(..)).map(u32::from);
|
||||
}
|
||||
FOLDED.with_borrow_mut(|folded| {
|
||||
folded.clear();
|
||||
folded.extend(hay.bytes().map(|b| if b == b'_' { b'-' } else { b }));
|
||||
m.fuzzy_match(Utf32Str::Ascii(folded), self.utf32.slice(..)).map(u32::from)
|
||||
})
|
||||
}
|
||||
|
||||
fn indices(&self, m: &mut Matcher, hay: &str, buf: &mut Vec<char>, out: &mut Vec<u32>) -> Option<u32> {
|
||||
out.clear();
|
||||
let s = m.fuzzy_indices(Utf32Str::new(hay, buf), self.utf32.slice(..), out).map(u32::from);
|
||||
let s = m.fuzzy_indices(self.hay(hay, buf), self.utf32.slice(..), out).map(u32::from);
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
s
|
||||
@@ -282,8 +328,8 @@ pub(crate) fn find_files(
|
||||
.collect();
|
||||
}
|
||||
let fq = match q.rsplit_once('/') {
|
||||
Some((dir, name)) => FileQuery::Path { dir: Needle::new(dir), name: Needle::new(name) },
|
||||
None => FileQuery::Name(Needle::new(&q)),
|
||||
Some((dir, name)) => FileQuery::Path { dir: Needle::file(dir), name: Needle::file(name) },
|
||||
None => FileQuery::Name(Needle::file(&q)),
|
||||
};
|
||||
let tiebreak = |a: &Cand, b: &Cand| a.len.cmp(&b.len).then_with(|| data.hot.rel(a.slot).cmp(data.hot.rel(b.slot)));
|
||||
let pool = limit * 4 + 64;
|
||||
@@ -350,7 +396,7 @@ pub(crate) fn find_dirs(data: &IndexData, query: &str, root: Option<&Path>, limi
|
||||
return Vec::new();
|
||||
}
|
||||
let by_path = q.contains('/');
|
||||
let needle = Needle::new(q.trim_end_matches('/'));
|
||||
let needle = Needle::file(q.trim_end_matches('/'));
|
||||
let text = data.dirs_hot.text();
|
||||
// (score, rel without the trailing `/`, char offset of the name when it matched by name)
|
||||
let (mut best, _): (Vec<_>, Vec<char>) = data
|
||||
@@ -734,4 +780,53 @@ mod tests {
|
||||
assert!(hump_bonus("OrderController", &[0, 5, 6]) > hump_bonus("OrderController", &[0, 3, 6]));
|
||||
assert_eq!(hump_bonus("abc", &[]), 0);
|
||||
}
|
||||
|
||||
fn index(rels: &[&str]) -> IndexData {
|
||||
let mut data = IndexData::default();
|
||||
for rel in rels {
|
||||
let record =
|
||||
crate::data::FileRecord { mtime: 0, size: 0, hash: [0; 32], symbols: Vec::new(), ignored: false };
|
||||
let (entry, symbols) = FileEntry::new(Path::new("/p").join(rel), (*rel).to_owned(), record);
|
||||
data.insert(entry, symbols);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn files(data: &IndexData, q: &str) -> Vec<String> {
|
||||
find_files(data, &Recents::new(&[]), q, None, 20).into_iter().map(|m| m.rel_path).collect()
|
||||
}
|
||||
|
||||
fn dirs(data: &IndexData, q: &str) -> Vec<String> {
|
||||
find_dirs(data, q, None, 20).into_iter().map(|m| m.rel_path).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_and_underscore_match_each_other_in_file_and_folder_names() {
|
||||
let data =
|
||||
index(&["bit-matcher/lib.rs", "line_parser/lib.rs", "docs/token-stream.rs", "docs/frame_sampler.rs"]);
|
||||
assert_eq!(dirs(&data, "bit_matcher"), ["bit-matcher/"]);
|
||||
assert_eq!(dirs(&data, "line-parser"), ["line_parser/"]);
|
||||
assert_eq!(files(&data, "token_stream"), ["docs/token-stream.rs"]);
|
||||
assert_eq!(files(&data, "frame-sampler"), ["docs/frame_sampler.rs"]);
|
||||
assert_eq!(files(&data, "docs/token_stream"), ["docs/token-stream.rs"]);
|
||||
// As before: a space or no separator matches any; `.` is not a word separator here.
|
||||
assert_eq!(dirs(&data, "bit matcher"), ["bit-matcher/"]);
|
||||
assert_eq!(dirs(&data, "bitmatcher"), ["bit-matcher/"]);
|
||||
assert!(dirs(&data, "bit.matcher").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exact_separator_ranks_first() {
|
||||
let data = index(&["src/bit-matcher.rs", "src/bit_matcher.rs"]);
|
||||
assert_eq!(files(&data, "bit_matcher"), ["src/bit_matcher.rs", "src/bit-matcher.rs"]);
|
||||
assert_eq!(files(&data, "bit-matcher"), ["src/bit-matcher.rs", "src/bit_matcher.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_the_other_separator() {
|
||||
let data = index(&["bit-matcher/lib.rs", "docs/token-stream.rs"]);
|
||||
assert_eq!(find_dirs(&data, "bit_matcher", None, 1)[0].indices, (0..11).collect::<Vec<u32>>());
|
||||
let file = &find_files(&data, &Recents::new(&[]), "token_stream", None, 1)[0];
|
||||
assert_eq!(file.indices, (5..17).collect::<Vec<u32>>());
|
||||
}
|
||||
}
|
||||
@@ -148,9 +148,10 @@ pub fn client_capabilities() -> Value {
|
||||
"macro", "keyword", "modifier", "comment", "string", "number", "regexp",
|
||||
"operator", "decorator"
|
||||
],
|
||||
// The native TypeScript server only sends modifiers the client advertises.
|
||||
"tokenModifiers": [
|
||||
"declaration", "definition", "readonly", "static", "deprecated", "abstract",
|
||||
"async", "modification", "documentation", "defaultLibrary"
|
||||
"async", "modification", "documentation", "defaultLibrary", "local"
|
||||
],
|
||||
"formats": ["relative"],
|
||||
"overlappingTokenSupport": false,
|
||||
|
||||
@@ -780,6 +780,51 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires OPENIDEA_TEST_NPM_TOOLS (vtsls and typescript-language-server) and OPENIDEA_TEST_TS7 (native tsc)"]
|
||||
async fn typescript_servers_distinguish_global_and_local_function_calls() {
|
||||
let tools = std::env::var_os("OPENIDEA_TEST_NPM_TOOLS").expect("set OPENIDEA_TEST_NPM_TOOLS");
|
||||
let tools = Path::new(&tools);
|
||||
let mut native = npm_server(tools, "typescript-7", "tsc", None);
|
||||
native.command = std::env::var("OPENIDEA_TEST_TS7").expect("set OPENIDEA_TEST_TS7");
|
||||
native.args.insert(0, "--lsp".into());
|
||||
|
||||
let text = "function outer(x) { return x; }\nexport function run() {\n function local() { return 1; }\n return outer(local());\n}\n";
|
||||
for server in [
|
||||
native,
|
||||
npm_server(tools, "vtsls", "vtsls", None),
|
||||
npm_server(tools, "typescript-language-server", "typescript-language-server", None),
|
||||
] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{"type":"module"}"#).unwrap();
|
||||
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions":{"allowJs":true}}"#).unwrap();
|
||||
let name = server.name.clone();
|
||||
let registry = LanguageRegistry::from_configs(vec![
|
||||
lang("typescript", "ts", server.clone()),
|
||||
lang("javascript", "js", server),
|
||||
]);
|
||||
let (mgr, _) = manager(&root, registry);
|
||||
for (language, ext) in [("typescript", "ts"), ("javascript", "js")] {
|
||||
let file = root.join(format!("sample.{ext}"));
|
||||
std::fs::write(&file, text).unwrap();
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &file, &LanguageId::new(language), 1, text);
|
||||
let tokens = retry(&format!("{name} {language} tokens"), Duration::from_secs(8), || async {
|
||||
mgr.semantic_tokens(doc).await.ok().flatten().filter(|t| !t.data.is_empty())
|
||||
})
|
||||
.await;
|
||||
let local = tokens.token_modifiers.iter().position(|m| m == "local").expect(&name);
|
||||
for (column, is_local) in [(9, false), (15, true)] {
|
||||
let token = tokens.data.as_chunks::<5>().0.iter().find(|t| t[0] == 3 && t[1] == column).unwrap();
|
||||
assert_eq!(tokens.token_types[token[3] as usize], "function", "{name} {language}");
|
||||
assert_eq!(token[4] & (1 << local) != 0, is_local, "{name} {language}:{column}");
|
||||
}
|
||||
}
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Vue Language Server 3 in hybrid mode: its `tsserver/request`s go through the
|
||||
/// client to vtsls with `@vue/typescript-plugin` (issue #25). Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@6 @vtsls/language-server`.
|
||||
|
||||
@@ -73,6 +73,28 @@ pub struct ContentTabReply {
|
||||
pub diff: Option<ContentDiff>,
|
||||
}
|
||||
|
||||
/// Output stream transport for a plugin-owned run configuration (API 1.18).
|
||||
///
|
||||
/// Ordinary pseudo-terminals combine stdout and stderr and can change
|
||||
/// buffering, input handling, and terminal behavior.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PluginOutputMode {
|
||||
/// Separate stdout and stderr pipes in the Run console (default).
|
||||
#[default]
|
||||
Pipes,
|
||||
/// Pseudo-terminal ("Emulate terminal in output console").
|
||||
Pty,
|
||||
}
|
||||
|
||||
/// Per-launch options for `run.start-with-options` (API 1.18).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginRunStartOptions {
|
||||
pub debug: bool,
|
||||
pub output_mode: Option<PluginOutputMode>,
|
||||
}
|
||||
|
||||
/// PluginRunConfiguration data exchanged with the IDE.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -90,6 +112,9 @@ pub struct PluginRunConfiguration {
|
||||
/// API 1.9: how Debug starts the configuration.
|
||||
#[serde(default)]
|
||||
pub debugger: Option<PluginDebugger>,
|
||||
/// API 1.18: default output stream transport (`pipes` or `pty`).
|
||||
#[serde(default)]
|
||||
pub output_mode: PluginOutputMode,
|
||||
}
|
||||
|
||||
/// How Debug starts a plugin configuration (API 1.9 `launch-configurations.debugger`).
|
||||
|
||||
@@ -20,6 +20,8 @@ use crate::wit_host::completion_list_bindings::exports::openidea::plugin::comple
|
||||
use crate::wit_host::hover_actions_bindings::exports::openidea::plugin::hover_actions as wit_hia;
|
||||
use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj;
|
||||
use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf;
|
||||
use crate::wit_host::run_anything_bindings::exports::openidea::plugin::run_anything_provider as wit_ra;
|
||||
use crate::wit_host::run_config_completion_bindings::exports::openidea::plugin::run_configuration_completion as wit_rcc;
|
||||
use crate::wit_host::run_target_validation_bindings::exports::openidea::plugin::run_target_validation as wit_rtv;
|
||||
use crate::wit_host::search_bindings::exports::openidea::plugin::search_provider as wit_search;
|
||||
use crate::wit_host::{
|
||||
@@ -39,10 +41,13 @@ use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder, UpdateDea
|
||||
use wasmtime_wasi::p2::pipe::MemoryOutputPipe;
|
||||
use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
|
||||
|
||||
use crate::wit_host::execution_configurations_bindings::exports::openidea::plugin::execution_configurations as wit_exec;
|
||||
use crate::wit_host::execution_configurations_bindings::openidea::plugin::launch_configurations as wit_exec_launch;
|
||||
use crate::wit_host::launch_configurations_bindings::exports::openidea::plugin::launch_configurations as wit_launch;
|
||||
use crate::wit_host::run_configurations_bindings::exports::openidea::plugin::run_configurations as wit_configs;
|
||||
use crate::wit_host::test_results_bindings::exports::openidea::plugin::test_results as wit_tests;
|
||||
use bindings::openidea::plugin::events as wit_events;
|
||||
use bindings::openidea::plugin::run as wit_run;
|
||||
use bindings::openidea::plugin::types as wit_types;
|
||||
use commit_checks_bindings::exports::openidea::plugin::commit_checker as wit_cc;
|
||||
use details_bindings::exports::openidea::plugin::detail_provider as wit_detail;
|
||||
@@ -59,7 +64,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.17";
|
||||
pub const API_VERSION: &str = "1.18";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -115,7 +120,12 @@ pub trait HostApi: Send + Sync {
|
||||
fn extension_contributions(&self, point: &str) -> Result<Vec<(String, String)>, HostError>;
|
||||
|
||||
/// Registers a project-scoped wrapper after validating its process grant and pin.
|
||||
fn register_run_target(&self, root: &Path, target: crate::PluginRunTarget) -> Result<(), HostError>;
|
||||
fn register_run_target(
|
||||
&self,
|
||||
root: &Path,
|
||||
target: crate::PluginRunTarget,
|
||||
generation: Option<u64>,
|
||||
) -> Result<(), HostError>;
|
||||
/// Withdraws this plugin's target, preserving the user's remembered prompt answer.
|
||||
fn unregister_run_target(&self, root: &Path, id: &str);
|
||||
|
||||
@@ -125,17 +135,20 @@ pub trait HostApi: Send + Sync {
|
||||
client: &str,
|
||||
config: &str,
|
||||
args: Vec<String>,
|
||||
debug: bool,
|
||||
options: crate::PluginRunStartOptions,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError>;
|
||||
/// Opens/reuses a keyed terminal, retained across idle instance reclamation.
|
||||
/// Opens/reuses a keyed terminal, retained across idle instance reclamation; `cwd`
|
||||
/// (API 1.18) is a directory relative to the window's project root.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn open_terminal_session(
|
||||
&self,
|
||||
client: &str,
|
||||
key: String,
|
||||
title: String,
|
||||
cmd: ProcessCommand,
|
||||
cwd: Option<String>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError>;
|
||||
@@ -195,6 +208,9 @@ pub trait HostApi: Send + Sync {
|
||||
) -> Result<(), HostError>;
|
||||
/// Replace all `(path, icon)` entries of a tree decoration set at once (API 1.8).
|
||||
fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError>;
|
||||
/// Fork a recorded native agent session into a new task in the invoking
|
||||
/// window's project, returning the new task id (API 1.18).
|
||||
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError>;
|
||||
/// Trusted repository history.
|
||||
fn vcs_log(
|
||||
&self,
|
||||
@@ -417,7 +433,24 @@ pub trait HostApi: Send + Sync {
|
||||
/// Delivers every event of `kind`, dropping its path filter.
|
||||
fn subscribe(&self, kind: EventKind);
|
||||
/// Delivers `kind` (`file-opened`, `file-saved`, `files-changed`) only for matching paths.
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError>;
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
|
||||
self.subscribe_paths_with_options(kind, globs, None)
|
||||
}
|
||||
/// Delivers `kind` with optional debounce window in milliseconds (API 1.18).
|
||||
fn subscribe_paths_with_options(
|
||||
&self,
|
||||
kind: &str,
|
||||
globs: Vec<String>,
|
||||
debounce_ms: Option<u32>,
|
||||
) -> Result<(), HostError>;
|
||||
/// Monotonically increasing project generation (API 1.18).
|
||||
fn project_generation(&self, root: &Path) -> Result<u64, HostError>;
|
||||
/// Replaces what this plugin watches outside `project` for the window `client`
|
||||
/// (API 1.18): `paths` are real paths an `fs.read` grant covers, already checked.
|
||||
/// Empty stops watching.
|
||||
fn watch_paths(&self, _client: &str, _project: &Path, _paths: Vec<PathBuf>) -> Result<(), HostError> {
|
||||
Err(HostError::Failed("watching paths is unavailable here".into()))
|
||||
}
|
||||
fn unsubscribe(&self, kind: &str);
|
||||
/// Starts `cmd` and returns the handle to it without waiting.
|
||||
fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result<u64, HostError>;
|
||||
@@ -878,6 +911,8 @@ pub struct Runtime {
|
||||
/// What the component exports: the `plugin` world, plus optional interfaces.
|
||||
struct Exports {
|
||||
run_target_validation: Option<wit_rtv::Guest>,
|
||||
run_anything: Option<wit_ra::Guest>,
|
||||
run_config_completion: Option<wit_rcc::Guest>,
|
||||
language_features: Option<wit_lf::Guest>,
|
||||
injections: Option<wit_inj::Guest>,
|
||||
plugin: bindings::Plugin,
|
||||
@@ -898,6 +933,7 @@ struct Exports {
|
||||
completion_list: Option<wit_cl::Guest>,
|
||||
run_configurations: Option<wit_configs::Guest>,
|
||||
launch_configurations: Option<wit_launch::Guest>,
|
||||
execution_configurations: Option<wit_exec::Guest>,
|
||||
test_results: Option<wit_tests::Guest>,
|
||||
mcp: Option<crate::wit_host::mcp_bindings::exports::openidea::plugin::mcp_provider::Guest>,
|
||||
}
|
||||
@@ -961,11 +997,19 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
|
||||
kind: "files-changed".into(),
|
||||
data: serde_json::to_string(&batch).expect("file paths serialize"),
|
||||
}),
|
||||
WorkbenchEvent::WatchedFilesChanged(batch) => wit_events::Event::Other(wit_types::Extension {
|
||||
kind: "watched-files-changed".into(),
|
||||
data: serde_json::to_string(&batch).expect("file paths serialize"),
|
||||
}),
|
||||
WorkbenchEvent::EditorFocused(p) => wit_events::Event::EditorFocused(p),
|
||||
WorkbenchEvent::VcsChanged(p) => wit_events::Event::VcsChanged(p),
|
||||
WorkbenchEvent::ProblemsChanged => {
|
||||
wit_events::Event::Other(wit_types::Extension { kind: "problems-changed".into(), data: "{}".into() })
|
||||
}
|
||||
WorkbenchEvent::ProjectClosed(p) => wit_events::Event::Other(wit_types::Extension {
|
||||
kind: "project-closed".into(),
|
||||
data: serde_json::to_string(&p).expect("path serializes"),
|
||||
}),
|
||||
WorkbenchEvent::Scheduled => wit_events::Event::Scheduled,
|
||||
WorkbenchEvent::ActionPerformed(a) => wit_events::Event::ActionPerformed(wit_events::ActionPerformed {
|
||||
action: a.action,
|
||||
@@ -1051,8 +1095,11 @@ impl Runtime {
|
||||
let completion_list_indices = wit_cl::GuestIndices::new(&pre).ok();
|
||||
let configs_indices = wit_configs::GuestIndices::new(&pre).ok();
|
||||
let launch_indices = wit_launch::GuestIndices::new(&pre).ok();
|
||||
let exec_indices = wit_exec::GuestIndices::new(&pre).ok();
|
||||
let tests_indices = wit_tests::GuestIndices::new(&pre).ok();
|
||||
let validation_indices = wit_rtv::GuestIndices::new(&pre).ok();
|
||||
let run_anything_indices = wit_ra::GuestIndices::new(&pre).ok();
|
||||
let run_config_completion_indices = wit_rcc::GuestIndices::new(&pre).ok();
|
||||
let lf_indices = wit_lf::GuestIndices::new(&pre).ok();
|
||||
let inj_indices = wit_inj::GuestIndices::new(&pre).ok();
|
||||
let mcp_indices =
|
||||
@@ -1063,11 +1110,16 @@ impl Runtime {
|
||||
configs_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let launch_configurations =
|
||||
launch_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let execution_configurations =
|
||||
exec_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let test_results = tests_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let language_features = lf_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let injections = inj_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let run_target_validation =
|
||||
validation_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let run_anything = run_anything_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let run_config_completion =
|
||||
run_config_completion_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
|
||||
let plugin = plugin_indices.load(&mut store, &instance).map_err(api_hint)?;
|
||||
let syntax = match syntax_indices {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
@@ -1126,6 +1178,8 @@ impl Runtime {
|
||||
store,
|
||||
exports: Exports {
|
||||
run_target_validation,
|
||||
run_anything,
|
||||
run_config_completion,
|
||||
language_features,
|
||||
injections,
|
||||
plugin,
|
||||
@@ -1145,6 +1199,7 @@ impl Runtime {
|
||||
completion_list,
|
||||
run_configurations,
|
||||
launch_configurations,
|
||||
execution_configurations,
|
||||
test_results,
|
||||
mcp,
|
||||
file_actions,
|
||||
@@ -1154,6 +1209,84 @@ impl Runtime {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn has_run_anything(&self) -> bool {
|
||||
self.exports.run_anything.is_some()
|
||||
}
|
||||
|
||||
/// Run Anything entries for `text` (API 1.18); none without the export.
|
||||
pub fn run_anything_suggest(
|
||||
&mut self,
|
||||
prefix: &str,
|
||||
text: &str,
|
||||
invocation: Invocation,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<crate::RunAnythingItem>, CallError> {
|
||||
if self.exports.run_anything.is_none() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let root = invocation.workspace_root.as_deref().map(to_ipc).unwrap_or_default();
|
||||
let items = self.call(invocation, timeout, |e, store| {
|
||||
e.run_anything.as_ref().unwrap().call_suggest(store, &root, prefix, text)
|
||||
})?;
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.take(crate::MAX_RUN_ANYTHING_ITEMS)
|
||||
.map(|i| crate::RunAnythingItem {
|
||||
label: clip(i.label, MAX_TITLE),
|
||||
detail: i.detail.map(|d| clip(d, MAX_TITLE)),
|
||||
line: i.line.map(|l| clip(l, 4096)),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Runs a Run Anything line (API 1.18): whether the plugin claimed it.
|
||||
pub fn run_anything_run(
|
||||
&mut self,
|
||||
prefix: &str,
|
||||
line: &str,
|
||||
invocation: Invocation,
|
||||
timeout: Duration,
|
||||
) -> Result<bool, CallError> {
|
||||
if self.exports.run_anything.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let root = invocation.workspace_root.as_deref().map(to_ipc).unwrap_or_default();
|
||||
self.call(invocation, timeout, |e, store| e.run_anything.as_ref().unwrap().call_run(store, &root, prefix, line))
|
||||
}
|
||||
|
||||
/// Completions for `field` of this plugin's configuration `config` (API 1.18); none
|
||||
/// without the export. Items whose range falls outside `text` are dropped.
|
||||
pub fn run_configuration_complete(
|
||||
&mut self,
|
||||
config: &str,
|
||||
field: &str,
|
||||
text: &str,
|
||||
caret: u32,
|
||||
invocation: Invocation,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<crate::RunConfigCompletion>, CallError> {
|
||||
if self.exports.run_config_completion.is_none() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let root = invocation.workspace_root.as_deref().map(to_ipc).unwrap_or_default();
|
||||
let items = self.call(invocation, timeout, |e, store| {
|
||||
e.run_config_completion.as_ref().unwrap().call_complete(store, &root, config, field, text, caret)
|
||||
})?;
|
||||
let len = text.encode_utf16().count() as u32;
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.filter(|i| i.replace_start <= i.replace_end && i.replace_end <= len)
|
||||
.take(crate::MAX_RUN_CONFIG_COMPLETIONS)
|
||||
.map(|i| crate::RunConfigCompletion {
|
||||
insert: clip(i.insert.unwrap_or_else(|| i.label.clone()), 4096),
|
||||
label: clip(i.label, MAX_TITLE),
|
||||
detail: i.detail.map(|d| clip(d, MAX_TITLE)),
|
||||
replace_start: i.replace_start,
|
||||
replace_end: i.replace_end,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn has_run_target_validation(&self) -> bool {
|
||||
self.exports.run_target_validation.is_some()
|
||||
}
|
||||
@@ -1184,14 +1317,48 @@ impl Runtime {
|
||||
.map(|r| r.map_err(|message| clip(message, 4096)))
|
||||
}
|
||||
|
||||
/// Complete configurations from the optional API 1.9 export, else the API 1.4 one.
|
||||
/// Complete configurations from the optional API 1.18 export, else API 1.9, else API 1.4.
|
||||
pub fn run_configurations(
|
||||
&mut self,
|
||||
root: String,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<crate::PluginRunConfiguration>, CallError> {
|
||||
let invocation = Invocation { workspace_root: Some(root.clone().into()), ..Default::default() };
|
||||
let items: Vec<crate::PluginRunConfiguration> = if self.exports.launch_configurations.is_some() {
|
||||
let items: Vec<crate::PluginRunConfiguration> = if self.exports.execution_configurations.is_some() {
|
||||
let items = self.call(invocation, timeout, |e, store| {
|
||||
e.execution_configurations.as_ref().unwrap().call_configurations(store, &root)
|
||||
})?;
|
||||
if items.len() > 1000 {
|
||||
return Err(CallError::Guest(GuestError::Invalid("too many run configurations".into())));
|
||||
}
|
||||
items
|
||||
.into_iter()
|
||||
.map(|c| crate::PluginRunConfiguration {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
program: c.program,
|
||||
args: c.args,
|
||||
cwd: c.cwd,
|
||||
test: c.test,
|
||||
framework: c.framework,
|
||||
env: c.env,
|
||||
debugger: match c.debugger {
|
||||
Some(wit_exec_launch::Debugger::Launch(language)) => {
|
||||
Some(crate::PluginDebugger::Launch { language })
|
||||
}
|
||||
Some(wit_exec_launch::Debugger::AttachChild(a)) => Some(crate::PluginDebugger::AttachChild {
|
||||
kind: a.kind,
|
||||
command_contains: a.command_contains,
|
||||
}),
|
||||
Some(wit_exec_launch::Debugger::Other(_)) | None => None,
|
||||
},
|
||||
output_mode: match c.output_mode {
|
||||
wit_run::OutputMode::Pipes => crate::PluginOutputMode::Pipes,
|
||||
wit_run::OutputMode::Pty => crate::PluginOutputMode::Pty,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
} else if self.exports.launch_configurations.is_some() {
|
||||
let items = self.call(invocation, timeout, |e, store| {
|
||||
e.launch_configurations.as_ref().unwrap().call_configurations(store, &root)
|
||||
})?;
|
||||
@@ -1219,6 +1386,7 @@ impl Runtime {
|
||||
}),
|
||||
Some(wit_launch::Debugger::Other(_)) | None => None,
|
||||
},
|
||||
output_mode: crate::PluginOutputMode::Pipes,
|
||||
})
|
||||
.collect()
|
||||
} else if self.exports.run_configurations.is_some() {
|
||||
@@ -2391,6 +2559,7 @@ fn event_to_wit_view(e: ViewEvent) -> wit_vt::ViewEvent {
|
||||
kind: "sort".into(),
|
||||
data: format!(r#"{{"column":{column},"descending":{descending}}}"#),
|
||||
}),
|
||||
ViewEvent::Closed => W::Other(wit_types::Extension { kind: "closed".into(), data: "{}".into() }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2524,11 +2693,22 @@ impl Runtime {
|
||||
&mut self,
|
||||
timeout: Duration,
|
||||
f: impl FnOnce(&wit_lf::Guest, &mut Store<StoreData>) -> wasmtime::Result<R>,
|
||||
) -> Result<R, CallError> {
|
||||
self.language_feature_call_in(None, timeout, f)
|
||||
}
|
||||
/// [`Self::language_feature_call`] for an editor of the project at `project`, which the
|
||||
/// call has as its invocation's project (`workspace.project-of` prefers it).
|
||||
fn language_feature_call_in<R>(
|
||||
&mut self,
|
||||
project: Option<&Path>,
|
||||
timeout: Duration,
|
||||
f: impl FnOnce(&wit_lf::Guest, &mut Store<StoreData>) -> wasmtime::Result<R>,
|
||||
) -> Result<R, CallError> {
|
||||
if self.exports.language_features.is_none() {
|
||||
return Err(CallError::missing_export("language-features"));
|
||||
}
|
||||
self.call(Invocation::default(), timeout, |e, s| f(e.language_features.as_ref().expect("checked"), s))
|
||||
let invocation = Invocation { workspace_root: project.map(Path::to_path_buf), ..Default::default() };
|
||||
self.call(invocation, timeout, |e, s| f(e.language_features.as_ref().expect("checked"), s))
|
||||
}
|
||||
pub fn language_format(
|
||||
&mut self,
|
||||
@@ -2726,9 +2906,11 @@ impl Runtime {
|
||||
let result = self.language_feature_call(timeout, |p, s| p.call_type_definition(s, &d, pos_to_wit(at)))?;
|
||||
Ok(result.into_iter().take(10000).map(location_from_wit).collect())
|
||||
}
|
||||
/// Gutter actions of `doc`, open in an editor of the project at `project`.
|
||||
pub fn language_gutter_actions(
|
||||
&mut self,
|
||||
doc: &ProviderDocument,
|
||||
project: Option<&Path>,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<crate::language_features::GutterAction>, CallError> {
|
||||
let d = wit_lf::Document {
|
||||
@@ -2737,13 +2919,15 @@ impl Runtime {
|
||||
version: doc.version,
|
||||
text: doc.text.clone(),
|
||||
};
|
||||
let result = self.language_feature_call(timeout, |p, s| p.call_gutter_actions(s, &d))?;
|
||||
let result = self.language_feature_call_in(project, timeout, |p, s| p.call_gutter_actions(s, &d))?;
|
||||
Ok(result.into_iter().take(10000).map(gutter_action_from).collect())
|
||||
}
|
||||
|
||||
/// Hover actions of `doc`, open in an editor of the project at `project`.
|
||||
pub fn language_hover_actions(
|
||||
&mut self,
|
||||
doc: &ProviderDocument,
|
||||
project: Option<&Path>,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<crate::language_features::HoverAction>, CallError> {
|
||||
if self.exports.hover_actions.is_none() {
|
||||
@@ -2755,7 +2939,8 @@ impl Runtime {
|
||||
version: doc.version,
|
||||
text: doc.text.clone(),
|
||||
};
|
||||
let result = self.call(Invocation::default(), timeout, |exports, store| {
|
||||
let invocation = Invocation { workspace_root: project.map(Path::to_path_buf), ..Default::default() };
|
||||
let result = self.call(invocation, timeout, |exports, store| {
|
||||
exports.hover_actions.as_ref().expect("checked").call_hover_actions(store, &d)
|
||||
})?;
|
||||
Ok(result.into_iter().take(10_000).map(hover_action_from).collect())
|
||||
@@ -2844,6 +3029,12 @@ mod tests {
|
||||
assert_eq!(fields[2].value, FieldValue::ReadonlyText { text: "author".into(), multiline: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_dialog_leaves_as_an_other_event() {
|
||||
let wit_vt::ViewEvent::Other(extension) = event_to_wit_view(ViewEvent::Closed) else { panic!("other") };
|
||||
assert_eq!((extension.kind.as_str(), extension.data.as_str()), ("closed", "{}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_row_events_leave_through_released_extension_case() {
|
||||
for (event, kind) in [
|
||||
|
||||
@@ -169,11 +169,15 @@ pub enum EventKind {
|
||||
VcsChanged,
|
||||
/// Problems of the window's files changed (a language server or a report).
|
||||
ProblemsChanged,
|
||||
/// A project was closed (or its window closed): the project root path.
|
||||
ProjectClosed,
|
||||
/// Paths outside the project watched with `events.watch-paths` changed (API 1.18).
|
||||
WatchedFilesChanged,
|
||||
Scheduled,
|
||||
}
|
||||
|
||||
impl EventKind {
|
||||
pub const ALL: [Self; 18] = [
|
||||
pub const ALL: [Self; 20] = [
|
||||
Self::DocumentChanged,
|
||||
Self::WebsocketReady,
|
||||
Self::FileClosed,
|
||||
@@ -191,6 +195,8 @@ impl EventKind {
|
||||
Self::ActionPerformed,
|
||||
Self::VcsChanged,
|
||||
Self::ProblemsChanged,
|
||||
Self::ProjectClosed,
|
||||
Self::WatchedFilesChanged,
|
||||
Self::Scheduled,
|
||||
];
|
||||
|
||||
@@ -213,6 +219,8 @@ impl EventKind {
|
||||
Self::ActionPerformed => "action-performed",
|
||||
Self::VcsChanged => "vcs-changed",
|
||||
Self::ProblemsChanged => "problems-changed",
|
||||
Self::ProjectClosed => "project-closed",
|
||||
Self::WatchedFilesChanged => "watched-files-changed",
|
||||
Self::Scheduled => "scheduled",
|
||||
}
|
||||
}
|
||||
@@ -274,6 +282,12 @@ pub struct ActionPerformed {
|
||||
/// Debounced worktree changes. Paths use the same absolute form as `file-saved`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct FilesChanged {
|
||||
/// Canonical absolute root of the project where changes occurred (API 1.18).
|
||||
#[serde(default)]
|
||||
pub project: Option<String>,
|
||||
/// Project state generation at the time this batch was emitted (API 1.18).
|
||||
#[serde(default)]
|
||||
pub generation: Option<u64>,
|
||||
pub created: Vec<String>,
|
||||
pub modified: Vec<String>,
|
||||
pub removed: Vec<String>,
|
||||
@@ -367,6 +381,11 @@ pub enum WorkbenchEvent {
|
||||
VcsChanged(String),
|
||||
/// Problems of the window's files changed; plugins re-read `problems`.
|
||||
ProblemsChanged,
|
||||
/// A project closed (API 1.18); payload is the canonical absolute root path.
|
||||
ProjectClosed(String),
|
||||
/// Changes to paths outside the project watched with `events.watch-paths` (API 1.18);
|
||||
/// `project` is the project the watch belongs to, `generation` is unset.
|
||||
WatchedFilesChanged(FilesChanged),
|
||||
Scheduled,
|
||||
}
|
||||
|
||||
@@ -390,6 +409,8 @@ impl WorkbenchEvent {
|
||||
Self::ActionPerformed(_) => EventKind::ActionPerformed,
|
||||
Self::VcsChanged(_) => EventKind::VcsChanged,
|
||||
Self::ProblemsChanged => EventKind::ProblemsChanged,
|
||||
Self::ProjectClosed(_) => EventKind::ProjectClosed,
|
||||
Self::WatchedFilesChanged(_) => EventKind::WatchedFilesChanged,
|
||||
Self::Scheduled => EventKind::Scheduled,
|
||||
}
|
||||
}
|
||||
@@ -943,6 +964,9 @@ pub enum ViewEvent {
|
||||
Sort { column: u32, descending: bool },
|
||||
TableSelect { row: u32 },
|
||||
TableActivate { row: u32 },
|
||||
// A plugin dialog closed (API 1.18): its close button, Escape or its page.
|
||||
// Leaves as an `other` view-event, kind `closed`.
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// A plugin's HTTP route declaration in a project.
|
||||
@@ -1105,3 +1129,31 @@ pub struct PluginDataSource {
|
||||
pub url: Option<String>,
|
||||
pub options: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Most Run Anything entries kept from one `run-anything-provider.suggest` answer.
|
||||
pub const MAX_RUN_ANYTHING_ITEMS: usize = 100;
|
||||
|
||||
/// A Run Anything entry from a plugin's `run-anything-provider` export (API 1.18).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RunAnythingItem {
|
||||
pub label: String,
|
||||
pub detail: Option<String>,
|
||||
/// The line Tab completes and Enter runs; `label` when absent.
|
||||
pub line: Option<String>,
|
||||
}
|
||||
|
||||
/// Most completions kept from one `run-configuration-completion.complete` answer.
|
||||
pub const MAX_RUN_CONFIG_COMPLETIONS: usize = 200;
|
||||
|
||||
/// A completion for a field of a plugin's own run configuration (API 1.18).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RunConfigCompletion {
|
||||
pub label: String,
|
||||
pub detail: Option<String>,
|
||||
/// Replaces the UTF-16 range `[replace_start, replace_end)` of the field's text.
|
||||
pub insert: String,
|
||||
pub replace_start: u32,
|
||||
pub replace_end: u32,
|
||||
}
|
||||
@@ -237,9 +237,10 @@ use bindings::openidea::plugin::{
|
||||
settings, storage, tasks, types as wit, ui, vcs, views, workspace,
|
||||
};
|
||||
|
||||
/// A project handle: its root.
|
||||
/// A project handle: its root and generation when borrowed.
|
||||
pub struct ProjectRes {
|
||||
root: PathBuf,
|
||||
pub(crate) root: PathBuf,
|
||||
pub(crate) generation: u64,
|
||||
}
|
||||
|
||||
/// A program a plugin started behind a handle (`process.start`); dropping the
|
||||
@@ -896,7 +897,23 @@ impl workspace::Host for StoreData {
|
||||
}
|
||||
|
||||
fn project_of(&mut self, path: String) -> wasmtime::Result<Option<Resource<ProjectRes>>> {
|
||||
self.host.project_of(Path::new(&path)).map(|root| self.push(ProjectRes { root })).transpose()
|
||||
self.host
|
||||
.project_of(Path::new(&path))
|
||||
.map(|root| {
|
||||
let generation = self.host.project_generation(&root).unwrap_or(0);
|
||||
self.push(ProjectRes { root, generation })
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn invoking_project(&mut self) -> wasmtime::Result<Option<Resource<ProjectRes>>> {
|
||||
// Only a project that is still open: a closed window's root is no project any more.
|
||||
let root = self.invocation.workspace_root.clone().filter(|root| self.host.projects().contains(root));
|
||||
root.map(|root| {
|
||||
let generation = self.host.project_generation(&root).unwrap_or(0);
|
||||
self.push(ProjectRes { root, generation })
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn projects(&mut self) -> Fallible<Vec<Resource<ProjectRes>>> {
|
||||
@@ -905,7 +922,8 @@ impl workspace::Host for StoreData {
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for root in self.host.projects() {
|
||||
out.push(self.push(ProjectRes { root })?);
|
||||
let generation = self.host.project_generation(&root).unwrap_or(0);
|
||||
out.push(self.push(ProjectRes { root, generation })?);
|
||||
}
|
||||
Ok(Ok(out))
|
||||
}
|
||||
@@ -1092,6 +1110,17 @@ impl workspace::HostProject for StoreData {
|
||||
Ok(self.host.write_text_file(&real, &text).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn generation(&mut self, this: Resource<ProjectRes>) -> Fallible<u64> {
|
||||
if let Err(e) = self.require(Capability::ProjectRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
if let Err(e) = self.host.require_api("project.generation", 18) {
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
Ok(self.host.project_generation(&root).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn drop(&mut self, rep: Resource<ProjectRes>) -> wasmtime::Result<()> {
|
||||
self.table.delete(rep)?;
|
||||
Ok(())
|
||||
@@ -1320,7 +1349,10 @@ impl invocation::Host for StoreData {}
|
||||
impl invocation::HostInvocation for StoreData {
|
||||
fn project(&mut self, _this: Resource<InvocationRes>) -> wasmtime::Result<Option<Resource<ProjectRes>>> {
|
||||
match self.invocation.workspace_root.clone() {
|
||||
Some(root) => Ok(Some(self.push(ProjectRes { root })?)),
|
||||
Some(root) => {
|
||||
let generation = self.host.project_generation(&root).unwrap_or(0);
|
||||
Ok(Some(self.push(ProjectRes { root, generation })?))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -1592,6 +1624,11 @@ impl events::Host for StoreData {
|
||||
{
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
if kind == EventKind::ProjectClosed
|
||||
&& let Err(e) = self.host.require_api(kind.name(), 18)
|
||||
{
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
if kind == EventKind::DocumentChanged {
|
||||
return Ok(Err(wit::Error::Invalid(
|
||||
"document-changed is delivered only for paths named with subscribe-paths".into(),
|
||||
@@ -1621,12 +1658,73 @@ impl events::Host for StoreData {
|
||||
Ok(self.host.subscribe_paths(&kind, globs).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn subscribe_paths_with_options(
|
||||
&mut self,
|
||||
kind: String,
|
||||
options: bindings::openidea::plugin::events::SubscriptionOptions,
|
||||
) -> Fallible<()> {
|
||||
if let Err(e) = self.require(Capability::Events) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
if let Err(e) = self.host.require_api("subscribe-paths-with-options", 18) {
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
if kind == EventKind::DocumentChanged.name() {
|
||||
if let Err(e) = self.host.require_api(&kind, 6) {
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
if let Err(e) = self.require(Capability::ProjectRead).and_then(|_| self.require(Capability::EditorRead)) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
}
|
||||
Ok(self.host.subscribe_paths_with_options(&kind, options.globs, options.debounce_ms).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn unsubscribe(&mut self, kind: String) -> wasmtime::Result<()> {
|
||||
self.host.unsubscribe(&kind);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn watch_paths(&mut self, paths: Vec<String>) -> Fallible<()> {
|
||||
if let Err(e) = self.require(Capability::Events) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
if let Err(e) = self.host.require_api("watch-paths", 18) {
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
let project = self.invocation.workspace_root.clone().filter(|root| self.host.projects().contains(root));
|
||||
let (Some(client), Some(project)) = (self.client().map(str::to_owned), project) else {
|
||||
return Ok(Err(wit::Error::Invalid("watch-paths needs a call that serves a window's project".into())));
|
||||
};
|
||||
if paths.len() > MAX_WATCHED_PATHS {
|
||||
return Ok(Err(wit::Error::Invalid(format!("at most {MAX_WATCHED_PATHS} watched paths"))));
|
||||
}
|
||||
let real_project = dunce::canonicalize(&project).unwrap_or_else(|_| project.clone());
|
||||
let mut resolved = Vec::with_capacity(paths.len());
|
||||
for path in &paths {
|
||||
let real = match self.granted_file(path) {
|
||||
Ok(real) => real,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
if real.starts_with(&real_project) {
|
||||
return Ok(Err(wit::Error::Invalid(format!(
|
||||
"{path} is inside the project: subscribe to files-changed for it"
|
||||
))));
|
||||
}
|
||||
if !resolved.contains(&real) {
|
||||
resolved.push(real);
|
||||
}
|
||||
}
|
||||
if !resolved.is_empty() {
|
||||
self.host.subscribe(EventKind::WatchedFilesChanged);
|
||||
}
|
||||
Ok(self.host.watch_paths(&client, &project, resolved).map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
/// The most paths one plugin watches outside one project (`events.watch-paths`).
|
||||
const MAX_WATCHED_PATHS: usize = 32;
|
||||
|
||||
impl tasks::Host for StoreData {
|
||||
fn begin(&mut self, title: String, cancellable: bool) -> wasmtime::Result<Resource<TaskRes>> {
|
||||
let token = self.cancel.token();
|
||||
@@ -2095,8 +2193,14 @@ impl process::HostChild for StoreData {
|
||||
}
|
||||
}
|
||||
|
||||
impl views::Host for StoreData {
|
||||
fn open_terminal_session(&mut self, key: String, title: String, cmd: process::Command) -> Fallible<String> {
|
||||
impl StoreData {
|
||||
fn open_keyed_terminal(
|
||||
&mut self,
|
||||
key: String,
|
||||
title: String,
|
||||
cmd: process::Command,
|
||||
cwd: Option<String>,
|
||||
) -> Fallible<String> {
|
||||
if let Err(e) = self.require_window() {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
@@ -2111,11 +2215,30 @@ impl views::Host for StoreData {
|
||||
key,
|
||||
title,
|
||||
cmd,
|
||||
cwd,
|
||||
&self.cancel.token(),
|
||||
self.remaining(),
|
||||
)
|
||||
.map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
impl views::Host for StoreData {
|
||||
fn open_terminal_session(&mut self, key: String, title: String, cmd: process::Command) -> Fallible<String> {
|
||||
self.open_keyed_terminal(key, title, cmd, None)
|
||||
}
|
||||
fn open_terminal_session_in(
|
||||
&mut self,
|
||||
key: String,
|
||||
title: String,
|
||||
cmd: process::Command,
|
||||
cwd: String,
|
||||
) -> Fallible<String> {
|
||||
if let Err(e) = self.host.require_api("views.open-terminal-session-in", 18) {
|
||||
return Ok(Err(to_wit(e)));
|
||||
}
|
||||
self.open_keyed_terminal(key, title, cmd, Some(cwd))
|
||||
}
|
||||
fn write_terminal(&mut self, key: String, text: String) -> Fallible<()> {
|
||||
if let Err(e) = self.require_window() {
|
||||
return Ok(Err(e));
|
||||
@@ -2558,8 +2681,12 @@ impl StoreData {
|
||||
if let Err(e) = self.require(Capability::Process(target.program.clone())) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
Ok(self.host.register_run_target(&root, target).map_err(to_wit))
|
||||
let res = self.table.get(&project)?;
|
||||
let root = res.root.clone();
|
||||
// Components built for API 1.18 or later have a registration from an outdated
|
||||
// handle refused; older ones keep registering whatever the generation.
|
||||
let generation = self.host.require_api("project.generation", 18).is_ok().then_some(res.generation);
|
||||
Ok(self.host.register_run_target(&root, target, generation).map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2625,19 +2752,40 @@ impl bindings::openidea::plugin::run_targets::Host for StoreData {
|
||||
|
||||
impl bindings::openidea::plugin::run::Host for StoreData {
|
||||
fn start(&mut self, config: String, args: Vec<String>, debug: bool) -> Fallible<String> {
|
||||
self.start_with_options(
|
||||
config,
|
||||
args,
|
||||
bindings::openidea::plugin::run::StartOptions { debug, output_mode: None },
|
||||
)
|
||||
}
|
||||
|
||||
fn start_with_options(
|
||||
&mut self,
|
||||
config: String,
|
||||
args: Vec<String>,
|
||||
options: bindings::openidea::plugin::run::StartOptions,
|
||||
) -> Fallible<String> {
|
||||
use bindings::openidea::plugin::run::OutputMode as WitOutputMode;
|
||||
if let Err(e) = self.require_window() {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
if args.len() > MAX_ARGS || args.iter().any(|a| a.len() > MAX_ARG_BYTES || a.contains('\0')) {
|
||||
return Ok(Err(wit::Error::Invalid("invalid run arguments".into())));
|
||||
}
|
||||
let options = crate::PluginRunStartOptions {
|
||||
debug: options.debug,
|
||||
output_mode: options.output_mode.map(|m| match m {
|
||||
WitOutputMode::Pipes => crate::PluginOutputMode::Pipes,
|
||||
WitOutputMode::Pty => crate::PluginOutputMode::Pty,
|
||||
}),
|
||||
};
|
||||
Ok(self
|
||||
.host
|
||||
.start_run(
|
||||
self.invocation.client.as_deref().unwrap(),
|
||||
&config,
|
||||
args,
|
||||
debug,
|
||||
options,
|
||||
&self.cancel.token(),
|
||||
self.remaining(),
|
||||
)
|
||||
@@ -2652,6 +2800,14 @@ pub(crate) mod launch_configurations_bindings {
|
||||
with: { "openidea:plugin/types": super::bindings::openidea::plugin::types },
|
||||
});
|
||||
}
|
||||
pub(crate) mod execution_configurations_bindings {
|
||||
wasmtime::component::bindgen!({ world: "execution-configurations-provider", path: "../../wit",
|
||||
with: {
|
||||
"openidea:plugin/types": super::bindings::openidea::plugin::types,
|
||||
"openidea:plugin/run": super::bindings::openidea::plugin::run,
|
||||
},
|
||||
});
|
||||
}
|
||||
pub(crate) mod test_results_bindings {
|
||||
wasmtime::component::bindgen!({ world: "test-results-provider", path: "../../wit",
|
||||
with: { "openidea:plugin/types": super::bindings::openidea::plugin::types },
|
||||
@@ -3165,6 +3321,19 @@ impl bindings::openidea::plugin::mcp::Host for StoreData {
|
||||
}
|
||||
}
|
||||
|
||||
impl bindings::openidea::plugin::agents::Host for StoreData {
|
||||
fn fork_session(&mut self, agent: String, session_id: String, cwd: String) -> Fallible<String> {
|
||||
if let Err(e) = self.require(Capability::Agents) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
if let Err(e) = self.require_window() {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let client = self.invocation.client.clone().unwrap_or_default();
|
||||
Ok(self.host.fork_agent_session(&client, &agent, &session_id, Path::new(&cwd)).map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod mcp_bindings {
|
||||
wasmtime::component::bindgen!({ world: "mcp-tools", path: "../../wit",
|
||||
with: {
|
||||
@@ -3175,6 +3344,16 @@ pub(crate) mod mcp_bindings {
|
||||
}
|
||||
|
||||
/// Optional API 1.5 run-target launch validation.
|
||||
/// The optional `run-anything-provider` export (API 1.18), bound on its own when present.
|
||||
pub(crate) mod run_anything_bindings {
|
||||
wasmtime::component::bindgen!({ world: "run-anything-exports", path: "../../wit" });
|
||||
}
|
||||
|
||||
/// The optional `run-configuration-completion` export (API 1.18), bound on its own when present.
|
||||
pub(crate) mod run_config_completion_bindings {
|
||||
wasmtime::component::bindgen!({ world: "run-configuration-completion-exports", path: "../../wit" });
|
||||
}
|
||||
|
||||
pub(crate) mod run_target_validation_bindings {
|
||||
wasmtime::component::bindgen!({ world: "run-target-validator", path: "../../wit" });
|
||||
}
|
||||
@@ -38,8 +38,11 @@ fn components() -> Vec<PathBuf> {
|
||||
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm"),
|
||||
];
|
||||
let official = repo().join("plugins/official");
|
||||
let mut dirs: Vec<_> = std::fs::read_dir(&official).unwrap().map(|e| e.unwrap().path()).collect();
|
||||
@@ -95,7 +98,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.17.0");
|
||||
let host = v("1.18.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -113,15 +116,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
"1.17.0",
|
||||
"1.18.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.18.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.18") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.19.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.19") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.17 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.18 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
@@ -183,6 +187,21 @@ fn the_completion_list_component_exports_the_optional_completion_list_world() {
|
||||
assert!(!old.iter().any(|name| name.starts_with("openidea:plugin/completion-list-provider")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_execution_configurations_component_exports_the_optional_execution_configurations_world() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let exports_of = |path: &str| -> Vec<String> {
|
||||
let component = engine.compile(&repo().join(path)).unwrap();
|
||||
component.component_type().exports(engine.engine()).map(|(name, _)| name.to_owned()).collect()
|
||||
};
|
||||
let exports = exports_of("crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm");
|
||||
let exec = format!("openidea:plugin/execution-configurations@{API_VERSION}.0");
|
||||
assert!(exports.iter().any(|name| name.starts_with(&exec)), "{exports:?}");
|
||||
// An older-world plugin that only exports launch-configurations stays valid.
|
||||
let old = exports_of("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm");
|
||||
assert!(!old.iter().any(|name| name.starts_with("openidea:plugin/execution-configurations")));
|
||||
}
|
||||
|
||||
// --- a later host, simulated -------------------------------------------------------------
|
||||
|
||||
struct Data {
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
98e9c2b886df177bafb68a712fc1efadc4f3a7b82e8425cd1b3f4c2355bdb785
|
||||
ba019d950ae83c45845a5cfcb2e890eca25c6f102b78f8cd3090f604c56aaf17
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
bb77bc0963451ca4259591bf68c72ae3eb70b1c6f855fa29dfc84d2be675404c
|
||||
926ca24c9a08166e34fb8a6b2c6dd06a92cf3370dc01ff3054b533356314c84b
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
f381b0e20520bccf5acd46b95641f5542885184352e52ec2fed3fd53665c353b
|
||||
dd7e4dcc429bf44b839cabe682f36cb3951a3dcf535f500f90cb60ff749e31e6
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
f72a53e7b800b8c5408c7ac67034821f814da7b1d66f527949450431bcf52e02
|
||||
1acae0035935e9f6e7b52826e9731aeb15dafb5cfcc561a2b98dae10676f53f8
|
||||
Loaded 100 of 687 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача