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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 4f697bf274 fix(settings): align field edges across settings sections 2026-12-02 19:07:39 +08:00
Ivan 2221afad01 feat(mcp): tools for the project's dev container (#7378)
Five MCP tools report, start, rebuild and run commands in the project's dev container through the IDE's own Docker and Dev Containers support, inside its trust checks and confirmations.

Runs keep a structured host-or-container target and refuse to start when an approved container target is missing or no longer matches; the container is identified by both devcontainer labels, pinned to the approved ID, and its config may not escape the project through a symlink. The tools are listed and dispatched only on the local desktop.

Closes #7293

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 19:06:17 +08:00
l0ng-ai 471bce2bb1 test: make the Windows Rust job pass again (#7516)
git_workflows: the 700 overlong paths of the two command-line batching tests exceeded Windows' 260-char MAX_PATH (Git for Windows enforces it without core.longpaths), so git add failed; on Windows they use shorter names that still overflow its 32,000-char command line. xcode_index: the test formatted a path into buildServer.json, and a Windows path's backslashes made the JSON invalid; it is built with serde_json now.
2026-12-02 18:46:03 +08:00
Qslia b630dfad55 fix(notebook): keep source lines whole when typing in a cell (#7502)
Rewriting a cell's source kept every old source element that still prefixed or suffixed the new text, including partial lines, so code typed character by character was saved one character per element and showed one character per line in VS Code and Cursor. Only whole lines (an element ending in a newline, starting at a line start) are reused now; the line being edited is written as one element, the notebook's own JSON layout and string-valued sources stay as they were, and a source already split into characters is joined into lines where it is edited.

Co-authored-by: qslia <[email protected]>
2026-12-02 18:41:09 +08:00
LU XIANGRUIтаwildcatDownstairs 74b50f7592 test(new-project): make apple_app_trees pass on Windows (#7507)
A Windows checkout gives the generator templates CRLF line endings; the test normalizes them before comparing the generated Swift file's first lines. Generated projects are unchanged.

Closes #7506

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:37:42 +08:00
l0ng-ai 95bc3622ab feat(vue): pick the managed Vue language server version per project (#7513)
Vue 2 projects (detected from package.json, or the installed vue for alias/workspace specs) use vue-language-server 3.0.x, which still supports Vue 2; other projects use latest. Each release installs in its own directory with its paired TypeScript. A version setting overrides detection.

Fixes #7357
2026-12-02 18:36:19 +08:00
l0ng-ai b911366115 fix(java): give project-wide Java usages time instead of falling back to a wider search (#7511)
Find Usages in large projects went through the Java usages extension with the default 30 s timeout and, when it ran out, fell back to jdtls' wider textDocument/references, so the user waited for both. A project-wide usages request now gets 300 s (still cancellable), and an extension timeout is returned as a timeout instead of starting the fallback; other extension failures still fall back.

Fixes #7376
2026-12-02 18:31:05 +08:00
l0ng-ai b2a9d105e2 feat(search): Endpoints tab in Search Everywhere and a Go to Endpoint action (#7510)
The request mappings the IDE indexes were only a section of Search Everywhere's All tab. They now have their own Endpoints tab, as in IDEA Ultimate (also /endpoints), and Navigate > Go to Endpoint... opens it with the editor selection as the query. No default shortcut; bindable in Settings > Keymap.
2026-12-02 18:29:03 +08:00
l0ng-ai b83c2cf11a docs(readme): refresh the WeChat group QR code 2026-12-02 18:26:46 +08:00
l0ng-ai 6648f502f1 feat(services): list Spring Boot configurations by default and show their address (#7508)
Projects without a saved Services list show Spring Boot run configurations by default; a saved list stays authoritative. Running Spring Boot nodes show the port and announced context path for runs and debug sessions.

Fixes #7346
2026-12-02 18:25:48 +08:00
LU XIANGRUIтаwildcatDownstairs 115003f0b6 feat(nuget): central package management awareness and one-click update (#7434)
The NuGet Packages window reads Directory.Packages.props: each package shows where its version is defined or pinned and any VersionOverride, and Check NuGet Package Updates offers an update to the newest version.

Metadata and update checks are scoped to the selected project, configuration and framework and run independently; one-click updates are withheld when compatibility across target frameworks is not verified.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:23:33 +08:00
nako-ruruтаnako-ruru 02d912d72a feat(keymap): add NetBeans keymap presets for Windows/Linux and macOS (#7481)
Adds NetBeans presets beside IntelliJ, Eclipse and VS Code, taken from JetBrains' NetBeans keymap (keymaps/NetBeans 6.5.xml) on top of the IntelliJ defaults; actions without an OpenIDEA counterpart keep the IntelliJ binding. IDEA's EditorDeleteLine now maps to code.deleteLine for imported keymaps.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 18:21:59 +08:00
LU XIANGRUIтаwildcatDownstairs 70fe0e6653 feat(nuget): manage NuGet package sources (#7424)
A Package sources panel lists NuGet sources and adds, enables, disables or removes them through dotnet nuget, writing to a chosen NuGet.Config under the workspace or the user-wide file.

Edits go only to the config file that defines a source, stale work is cancelled when the project or selection changes, and URL credentials are redacted from errors. CI installs SDK 10 and 11 for the real-CLI tests.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:34 +08:00
LU XIANGRUIтаwildcatDownstairs 950bf986d6 fix(libraries): tell same-named library roots apart in External Libraries (#7463)
A uv venv reports its own .venv/Lib beside the base interpreter's Lib, so External Libraries showed two rows called Lib. Roots sharing a name in one SDK group now show their parent folder after "library root". A root inside a sibling root (.venv/Lib/site-packages under .venv/Lib) also got the same tree key as its row in the sibling's listing, so the virtual list drew two rows on top of each other; nested roots now get their own key namespace.

Refs #7444

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:02 +08:00
LU XIANGRUIтаwildcatDownstairs 310d923480 feat(dotnet): show solution folders and solution items in the Project view (#7435)
Solution folders from .sln and .slnx files appear as nested nodes under the solution, holding their projects and solution items; projects outside every folder follow.

Parent folders an SLNX file only implies are created, literal slashes in legacy folder names are kept, and uppercase .SLNX extensions are accepted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:19:58 +08:00
l0ng-ai 0c506fa479 style: format the Razor scanner and use spacing tokens in SVN working copies (#7505)
Fixes pnpm format:check and the spacing-scale test on main: two for headers in the Razor scanner are formatted as oxfmt expects, and the SVN Working Copies panel uses --space-* tokens for its gaps (same values, no visible change).
2026-12-02 18:18:43 +08:00
LU XIANGRUIтаwildcatDownstairs bc86836492 feat(dotnet): Dependencies node under each project in the Project view (#7430)
Each .NET project lists its packages, project references, framework references and analyzers under a Dependencies node.

Expandable .csproj rows keep their file behaviour (open, rename, context menu), same-named references and analyzers stay distinct, and the evaluated target framework is labelled.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:16:53 +08:00
l0ng-ai dead55af21 feat(windows): open project windows on the display last worked on (#7123)
On Windows, the display of the last focused or moved project window is saved to last-display.json. A project window opened without a position of its own is centred on that display and sized to its work area while the display is still connected and unchanged; otherwise it opens on the primary display. Cascaded windows keep their place, and macOS and Linux are unchanged.

Fixes #7031
2026-12-02 18:16:48 +08:00
langxpтаkradme c7a4201ce9 fix(agents): support context menu and stable selection (#7490)
Right-clicking the agent composer offered no editing menu. It now has Cut, Copy and Paste; menu paste goes through the same copied-code, link, project-path and long-text handling as a keyboard paste, and falls back to a clipboard image. A deferred multi-click selection handler no longer moves a selection that already left its conversation row back to it, which scrolled the conversation.

Co-authored-by: kradme <[email protected]>
2026-12-02 18:16:31 +08:00
l0ng-ai 91cf66e72e refactor(agents): simplify the automations dashboard and editor (#7491)
The Agents sidebar has a single clock button for Automations, with a dot for unread runs or runs waiting for input. The dashboard puts search and tabs on one row and moves import and pause-all into an Options menu. The automation dialog keeps provider tools with the prompt, moves permissions, continuity and run limits under Advanced, and expands Advanced when an edited schedule uses non-default settings.
2026-12-02 18:16:25 +08:00
l0ng-ai 4a87022e58 fix(agents): retry Cursor capacity errors and show attempt counts (#7500)
Cursor ACP can end a turn successfully while streaming a resource_exhausted error. Such turns now continue in the same conversation after 5, 15 and 30 seconds, with the countdown and attempt number in the working row and each continuation numbered in the history. Stop cancels the wait and Send Now replaces it; after three failed retries the task pauses with a manual Retry button.
2026-12-02 18:15:55 +08:00
l0ng-ai c92bd0999b fix(agents): render ANSI styles in tool output (#7495)
Agent tool cards now render ANSI colours and emphasis in command output with the shared console parser, instead of showing raw escape codes. Plain output keeps its text rendering path.
2026-12-02 18:15:39 +08:00
l0ng-ai 880835f0ac fix(agents): clean up plugin settings layout (#7497)
Plugin rows show the name and version with secondary metadata on its own line, keeping enable toggles and review buttons clear of the text. Manifest formats and marketplace move into the expandable details, and the list adapts to narrow Settings panes.
2026-12-02 18:15:12 +08:00
l0ng-ai ce938df81b fix(welcome): flatten recent project lists across hosts (#7504) 2026-12-02 18:05:39 +08:00
137 змінених файлів з 7828 додано та 1759 видалено

No files matched your search

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 169 KiB

Після

Ширина:  |  Висота:  |  Розмір: 192 KiB

+5 -2
Переглянути файл
@@ -370,9 +370,12 @@ jobs:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts runs the real `dotnet sln` / `dotnet add reference`.
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
with: { dotnet-version: 10.0.x }
with:
dotnet-version: |
10.0.x
11.0.x
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
+112 -17
Переглянути файл
@@ -154,6 +154,9 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
/// can trail its `session/prompt` response by this much.
const TURN_GRACE: Duration = Duration::from_millis(100);
const CURSOR_CAPACITY_MESSAGE: &str = "Error: RetriableError: [resource_exhausted] Error";
const CURSOR_RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(30)];
/// A session open can arrive before the agent finishes activating its plugins and MCP
/// servers (OpenCode: "Location plugins did not finish activating"). That is a transient
/// startup race. The window bounds the session-open requests and the waits between them.
@@ -2815,6 +2818,7 @@ impl AgentManager {
let approval_drifted = intr.approval_mode != current_fp;
let eligible = first_reconcile
&& policy_allows
&& intr.reason != InterruptionReason::CursorCapacity
&& safe_session
&& !intr.was_waiting_for_input
&& !approval_drifted
@@ -3619,6 +3623,7 @@ impl AgentManager {
};
self.detach_sinks();
for task in tasks {
task.network_poke.notify_waiters();
let was_live = task.kill().is_some();
task.finish_shutdown(was_live, reason);
}
@@ -4204,6 +4209,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
});
}
if in_flight {
@@ -4443,12 +4449,13 @@ impl Task {
self.explicit_stop.store(false, Ordering::Release);
self.force_resume_now.store(false, Ordering::Release);
let mut network_resumes_this_turn: u32 = 0;
let mut capacity_retries = 0;
loop {
if self.shared.shut_down_since(epoch) {
return;
}
self.state.lock().active_scheduled_turn = scheduled.clone();
if recovery.is_none() {
if recovery.is_none() || recovery == Some(InterruptionReason::CursorCapacity) {
if let Err(err) = self.verify_worktree_cwd_confined() {
self.state.lock().active_scheduled_turn = None;
return self.fail(Failure::from(err.to_string()), epoch);
@@ -4469,7 +4476,9 @@ impl Task {
}
}
// The message shows before the checkout is recorded, which can take a while in a large repository.
if !self.show_prompt(&prompt, recovery.take(), epoch) {
let retry_attempt = (recovery == Some(InterruptionReason::CursorCapacity) && capacity_retries > 0)
.then_some(capacity_retries as u32);
if !self.show_prompt(&prompt, recovery.take(), retry_attempt, epoch) {
self.state.lock().active_scheduled_turn = None;
return;
}
@@ -4481,11 +4490,6 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
let explicit_stop = self.explicit_stop.swap(false, Ordering::AcqRel);
if explicit_stop && result.is_err() {
result = Ok("cancelled".into());
}
self.cancel_pending.store(false, Ordering::Release);
tokio::time::sleep(TURN_GRACE).await;
if self.shared.shut_down_since(epoch) {
return;
@@ -4494,13 +4498,41 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
// Cursor ACP ends the turn successfully even when its final response is a
// capacity error. Check after TURN_GRACE so trailing chunks have arrived.
if self.cursor_at_capacity(&result) {
if self.cancel_pending.load(Ordering::Acquire) || self.send_now.load(Ordering::Acquire) {
result = Ok("cancelled".into());
} else if let Some(&delay) = CURSOR_RETRY_DELAYS.get(capacity_retries) {
capacity_retries += 1;
if self.wait_for_cursor_retry(capacity_retries, delay, epoch).await {
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
recovery = Some(InterruptionReason::CursorCapacity);
prompt = continuation_prompt_for(InterruptionReason::CursorCapacity);
continue;
}
if self.shared.shut_down_since(epoch) {
return;
}
result = Ok("cancelled".into());
} else {
self.settle_interrupted(InterruptionReason::CursorCapacity, epoch);
return;
}
}
let explicit_stop = self.explicit_stop.swap(false, Ordering::AcqRel);
if explicit_stop && result.is_err() {
result = Ok("cancelled".into());
}
self.cancel_pending.store(false, Ordering::Release);
if let Err(ref failure) = result
&& failure.network
&& !explicit_stop
{
let window_mins = self.effective_recovery_window_mins();
if window_mins == 0 {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
if network_resumes_this_turn < MAX_NETWORK_RESUMES_PER_TURN {
@@ -4514,7 +4546,7 @@ impl Task {
result = Ok("cancelled".into());
}
NetworkWaitOutcome::Expired => {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
NetworkWaitOutcome::Recovered { forced } => {
@@ -4526,7 +4558,7 @@ impl Task {
recovery = Some(InterruptionReason::NetworkTimeout);
continue;
} else {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
}
@@ -4573,6 +4605,7 @@ impl Task {
}
self.emit_task();
network_resumes_this_turn = 0;
capacity_retries = 0;
prompt = queued.prompt;
scheduled = queued.scheduled;
recovery = None;
@@ -4699,9 +4732,53 @@ impl Task {
}
}
fn settle_network_timeout(self: &Arc<Self>, epoch: u64) {
fn cursor_at_capacity(&self, result: &Result<String, Failure>) -> bool {
let s = self.state.lock();
if s.task.provider != "cursor" {
return false;
}
matches!(result, Ok(stop) if stop == "end_turn")
&& matches!(
s.history.conversation.main.entries.last(),
Some(AgentEntry::Agent { text }) if text.trim() == CURSOR_CAPACITY_MESSAGE
)
}
async fn wait_for_cursor_retry(&self, attempt: usize, delay: Duration, epoch: u64) -> bool {
#[cfg(test)]
let delay = delay.min(Duration::from_millis(150));
let until = tokio::time::Instant::now() + delay;
self.set_retry(Some(AgentRetry {
attempt: attempt as u32,
max_retries: Some(CURSOR_RETRY_DELAYS.len() as u32),
retry_at_ms: now_ms() + delay.as_secs_f64() * 1000.0,
error: Some(CURSOR_CAPACITY_MESSAGE.into()),
deadline_ms: None,
}));
loop {
let notified = self.network_poke.notified();
if self.shared.shut_down_since(epoch)
|| self.cancel_pending.load(Ordering::Acquire)
|| self.explicit_stop.load(Ordering::Acquire)
|| self.send_now.load(Ordering::Acquire)
{
return false;
}
if tokio::time::Instant::now() >= until {
return true;
}
tokio::select! {
_ = tokio::time::sleep_until(until) => {}
_ = notified => {}
}
}
}
fn settle_interrupted(self: &Arc<Self>, reason: InterruptionReason, epoch: u64) {
self.cancel_permissions();
if let Some(live) = self.live.lock().take() {
if reason == InterruptionReason::NetworkTimeout
&& let Some(live) = self.live.lock().take()
{
live.peer.kill();
}
let mut file = self.file.lock();
@@ -4714,12 +4791,15 @@ impl Task {
let dirty = s.history.conversation.settle(now);
let approval_mode = config::approval_fingerprint(&s.task.config);
s.busy = false;
s.task.background.clear();
s.background_tasks.clear();
s.active_scheduled_turn = None;
if reason == InterruptionReason::NetworkTimeout {
s.task.background.clear();
s.background_tasks.clear();
}
s.change_status(AgentStatus::Ready, None);
s.task.unread = true;
s.task.interrupted = Some(Box::new(AgentInterrupted {
reason: InterruptionReason::NetworkTimeout,
reason,
at_ms: now,
was_waiting_for_input: false,
approval_mode,
@@ -4733,6 +4813,9 @@ impl Task {
self.mark_dirty(dirty);
self.emit_task();
self.emit_attention(AgentAttentionReason::Failed);
if reason == InterruptionReason::CursorCapacity {
self.release_when_idle();
}
}
/// Drops an idle resumable live session so the next turn reloads it.
@@ -4976,7 +5059,9 @@ impl Task {
let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed());
let running = {
let s = self.state.lock();
s.busy && s.task.status == AgentStatus::Running
// During Cursor backoff the ACP turn has already ended. Send Now must
// cancel the wait and dispatch the new prompt as a turn of its own.
s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some())
};
let Some((live, method)) = live
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
@@ -5015,12 +5100,19 @@ impl Task {
done_ms: None,
steered: true,
recovery: None,
retry_attempt: None,
});
Ok(())
}
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt, recovery: Option<InterruptionReason>, epoch: u64) -> bool {
fn show_prompt(
self: &Arc<Self>,
prompt: &AgentPrompt,
recovery: Option<InterruptionReason>,
retry_attempt: Option<u32>,
epoch: u64,
) -> bool {
let attachments = prompt
.files
.iter()
@@ -5044,6 +5136,7 @@ impl Task {
done_ms: None,
steered: false,
recovery,
retry_attempt,
});
s.change_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
i
@@ -6038,6 +6131,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
})
}
};
@@ -6733,6 +6827,7 @@ fn continuation_prompt_for(reason: InterruptionReason) -> AgentPrompt {
InterruptionReason::BackendStop => "the OpenIDEA backend stopped",
InterruptionReason::UnexpectedExit => "OpenIDEA exited unexpectedly",
InterruptionReason::NetworkTimeout => "the network connection dropped",
InterruptionReason::CursorCapacity => "Cursor reported a capacity limit",
};
AgentPrompt {
text: format!(
+4
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -641,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
+97
Переглянути файл
@@ -69,6 +69,8 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
capacity_errors: Mutex<u32>,
/// Queued errors returned on the next session-open calls before succeeding.
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
@@ -297,6 +299,22 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
{
let mut remaining = self.capacity_errors.lock();
if *remaining > 0 {
*remaining -= 1;
if text == "edit once" {
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
"title": "Edit file", "kind": "edit", "status": "completed"}),
);
}
self.say(&session, "\n\nError: RetriableError: ");
self.say(&session, "[resource_exhausted] Error");
return Ok(json!({"stopReason": "end_turn"}));
}
}
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
@@ -7263,6 +7281,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 4;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let snap = handle.state.lock().snapshot();
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
assert!(snap.retry.is_none());
let entries = mgr.entries(&task.id, None).unwrap();
let attempts: Vec<_> = entries
.iter()
.filter_map(|e| match e {
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
_ => None,
})
.collect();
assert_eq!(attempts, [1, 2, 3]);
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
assert_eq!(agent.prompts.lock().len(), 4);
mgr.resume(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(handle.state.lock().task.interrupted.is_none());
assert_eq!(agent.prompts.lock().len(), 5);
assert!(
agent
.prompts
.lock()
.iter()
.skip(1)
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
);
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
for send_now in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 1;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
let handle = mgr.task(&task.id).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().task.retry.is_none() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
let retry = handle.state.lock().task.retry.clone().unwrap();
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
if !send_now {
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 1);
assert!(handle.state.lock().task.retry.is_none());
}
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 2);
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
+2
Переглянути файл
@@ -646,6 +646,7 @@ mod tests {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -668,6 +669,7 @@ mod tests {
done_ms: None,
steered,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+1 -1
Переглянути файл
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
}
}
flush(&mut batch, on_batch);
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
#[cfg(all(test, unix))]
+5 -5
Переглянути файл
@@ -175,7 +175,7 @@ impl CliTool {
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
@@ -301,9 +301,9 @@ impl Lines {
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
/// `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
@@ -314,6 +314,6 @@ impl Lines {
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
Ok(status)
}
}
+9
Переглянути файл
@@ -11,6 +11,14 @@ use specta::Type;
use std::collections::BTreeMap;
use std::sync::Arc;
/// The execution target recorded with an MCP agent run.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum McpAgentRunTarget {
Host,
Container { id: String },
}
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
target: McpAgentRunTarget,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
+2
Переглянути файл
@@ -705,6 +705,8 @@ pub struct ToolDownloadSettings {
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
/// crates.io). Off by default.
pub configured_registries_only: bool,
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
pub vue_language_server_version: String,
}
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
+5
Переглянути файл
@@ -403,6 +403,11 @@ pub(crate) fn snapshot(ep: &DockerEndpoint, timeout: Duration) -> Option<DockerS
Some(snap)
}
/// Every container (`docker ps --all`).
pub(crate) fn containers(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<Vec<DockerContainer>>> {
Some(list_containers(&address(ep)?, timeout))
}
fn list_containers(addr: &Address, timeout: Duration) -> IdeResult<Vec<DockerContainer>> {
let body = check(request(addr, "GET", "/containers/json?all=1", timeout)?)?;
Ok(map_containers(&body))
+19
Переглянути файл
@@ -193,6 +193,25 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
snap
}
/// The containers (running or not) that carry every label in `labels`, each `key=value` (or
/// just `key`): `docker ps --all --filter label=…`.
pub fn containers(ep: &DockerEndpoint, labels: &[String]) -> IdeResult<Vec<DockerContainer>> {
if docker_executable().is_none()
&& let Some(listed) = engine::containers(ep, QUICK)
{
let has = |c: &DockerContainer, label: &String| match label.split_once('=') {
Some((key, value)) => c.labels.get(key).is_some_and(|v| v == value),
None => c.labels.contains_key(label),
};
return listed.map(|all| all.into_iter().filter(|c| labels.iter().all(|l| has(c, l))).collect());
}
let filters: Vec<String> = labels.iter().flat_map(|l| ["--filter".to_owned(), format!("label={l}")]).collect();
let mut args: Vec<&str> = vec!["ps", "--all", "--no-trunc"];
args.extend(filters.iter().map(String::as_str));
args.extend(["--format", PS_FORMAT]);
run(ep, &args, QUICK).map(|text| parse_containers(&text))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ContainerOp {
+72
Переглянути файл
@@ -0,0 +1,72 @@
//! Dev containers as the backend sees them: the Dev Containers CLI, and which containers a
//! window is open in.
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
pub fn cli(data_dir: &Path) -> IdeResult<PathBuf> {
ide_tools::Tools::new(data_dir)
.info("devcontainer", &[])
.ok()
.and_then(|t| t.path)
.map(ide_core::IpcPath::into_path_buf)
.ok_or_else(|| {
IdeError::unavailable(
"The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.",
)
})
}
/// The containers a window is attached to (Reopen in Container), by id. A container may be held
/// by more than one window.
#[derive(Default)]
pub struct AttachedContainers(Mutex<Vec<String>>);
impl AttachedContainers {
/// Marks `id` attached until the returned guard is dropped.
pub fn hold(self: &Arc<Self>, id: &str) -> AttachedContainer {
self.0.lock().push(id.to_owned());
AttachedContainer { set: self.clone(), id: id.to_owned() }
}
/// Whether a window is attached to the container `id` (a full id or a prefix of one).
pub fn contains(&self, id: &str) -> bool {
!id.is_empty() && self.0.lock().iter().any(|held| held.starts_with(id) || id.starts_with(held.as_str()))
}
}
/// A window's attachment to a container, released on drop.
pub struct AttachedContainer {
set: Arc<AttachedContainers>,
id: String,
}
impl Drop for AttachedContainer {
fn drop(&mut self) {
let mut held = self.set.0.lock();
if let Some(at) = held.iter().position(|id| *id == self.id) {
held.remove(at);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_container_stays_attached_until_every_window_released_it() {
let set = Arc::new(AttachedContainers::default());
let id = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
let (first, second) = (set.hold(id), set.hold(id));
assert!(set.contains(id) && set.contains(&id[..12]));
assert!(!set.contains("ffffffffffff") && !set.contains(""));
drop(first);
assert!(set.contains(id));
drop(second);
assert!(!set.contains(id));
}
}
+12
Переглянути файл
@@ -9,6 +9,7 @@ pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod devcontainer;
pub mod diagnostics_store;
mod direnv;
pub mod environment;
@@ -91,6 +92,7 @@ impl HostConfig {
}
pub struct Host {
pub(crate) local_desktop: bool,
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
@@ -106,6 +108,8 @@ pub struct Host {
pub mcp_requests: mcp::Requests,
/// Commands agents run in the Run tool window (`run_command`).
pub mcp_agent_runs: mcp::AgentRuns,
/// Dev containers a window is attached to; the MCP tools leave them alone.
pub dev_containers_attached: Arc<devcontainer::AttachedContainers>,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
@@ -212,6 +216,12 @@ impl Host {
windows
}
/// Enables tools that control services on the local desktop.
pub fn with_local_desktop(mut self) -> Self {
self.local_desktop = true;
self
}
/// Enables user-approved database helper processes on the local desktop.
pub fn with_local_database_tunnels(mut self) -> Self {
self.local_database_tunnels = true;
@@ -262,6 +272,7 @@ impl Host {
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_desktop: false,
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
@@ -271,6 +282,7 @@ impl Host {
mcp_reports: Default::default(),
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
dev_containers_attached: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
+894
Переглянути файл
@@ -0,0 +1,894 @@
//! `devcontainer_*`: the project's dev container for agents. Which container is the project's
//! is decided by the labels the Dev Containers CLI puts on it (folder and configuration file);
//! nothing else is ever touched. Starting and running go through the CLI, listing, logs and
//! stopping through `ops::docker`.
use super::run::agent::{Execution, tab_name};
use super::run::agent_tools::{
INTERVENTIONS, MAX_LINES, NAME, OUTPUT, SEQUENCE, TRUNCATE_MODE, Tab, busy, start_in_tab,
};
use super::run::timeout;
use super::tool::{Call, Output, Param, ParamType, Tool, ensure_inside};
use crate::Host;
use crate::ops::docker as ops;
use ide_core::{IdeError, IdeResult};
use ide_docker::{DockerAvailability, DockerContainer, DockerEndpoint, DockerObject};
use ide_remote::devcontainer::{CONFIG_LABEL, FOLDER_LABEL, Target, UP_TIMEOUT, label_value};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
const EXEC_TIMEOUT_MS: usize = 120_000;
const DEFAULT_TAIL: i64 = 200;
const MAX_TAIL: i64 = 5000;
const COMPOSE_PROJECT: &str = "com.docker.compose.project";
const CONFIG_NAMES: [&str; 2] = ["devcontainer.json", ".devcontainer.json"];
const CONFIG: &str = "Which configuration file to use: a path inside the project to a `devcontainer.json` or \
`.devcontainer.json`. Default: `.devcontainer/devcontainer.json`, else `.devcontainer.json` (`devcontainer_status` \
lists the others)";
const WHICH: &str = "The project's container is the one the Dev Containers CLI started for the project folder and \
configuration file (its `devcontainer.local_folder` and `devcontainer.config_file` labels), plus the other containers \
of its Docker Compose project; no other container is ever touched. Needs Docker on this machine.";
pub fn tools() -> Vec<Tool> {
vec![status(), logs(), up(), exec(), stop()]
}
// ---- which container is the project's ----
/// Containers with both project labels, running before stopped, then newest.
fn project_containers(mut candidates: Vec<DockerContainer>, target: &Target) -> Vec<DockerContainer> {
let Some(config) = target.config_label() else { return Vec::new() };
let folder = target.folder_label();
candidates.retain(|c| {
let label = |key: &str| c.labels.get(key).map(|value| label_value(value));
label(FOLDER_LABEL).as_deref() == Some(&folder) && label(CONFIG_LABEL).as_deref() == Some(&config)
});
// `created_at` is docker's `2026-01-02 03:04:05 +0000 UTC`: newest sorts last as text.
candidates.sort_by(|a, b| b.running().cmp(&a.running()).then_with(|| b.created_at.cmp(&a.created_at)));
candidates
}
/// The project's containers.
#[derive(Default)]
struct Found {
primary: Option<DockerContainer>,
/// Other containers with the project's labels, such as one left from before a rebuild.
stale: Vec<DockerContainer>,
/// The other containers of the primary's Compose project.
siblings: Vec<DockerContainer>,
}
impl Found {
fn primary_id(&self) -> Option<&str> {
self.primary.as_ref().map(|c| c.id.as_str())
}
fn all(&self) -> impl Iterator<Item = &DockerContainer> {
self.primary.iter().chain(&self.stale).chain(&self.siblings)
}
/// What `stop` acts on: the primary and its Compose project.
fn running_group(&self) -> Vec<&DockerContainer> {
self.primary.iter().chain(&self.siblings).filter(|c| c.running()).collect()
}
}
async fn find(host: &Host, target: &Target) -> IdeResult<Found> {
if target.config().is_none() {
return Ok(Found::default());
}
let ep = || DockerEndpoint::Default;
let folder =
ops::containers_with_labels(host, ep(), vec![format!("{FOLDER_LABEL}={}", target.folder_label())]).await?;
let mut matching = project_containers(folder, target).into_iter();
let primary = matching.next();
let stale: Vec<DockerContainer> = matching.collect();
let mut siblings = Vec::new();
if let Some(project) = primary.as_ref().and_then(|p| p.compose_project.clone()) {
let members = ops::containers_with_labels(host, ep(), vec![format!("{COMPOSE_PROJECT}={project}")]).await?;
siblings = siblings_of(primary.as_ref().unwrap(), members);
}
Ok(Found { primary, stale, siblings })
}
/// The other containers of `primary`'s Compose project. Another checkout may give its project the
/// same name, so only those of the same working directory, which the primary has to have.
fn siblings_of(primary: &DockerContainer, members: Vec<DockerContainer>) -> Vec<DockerContainer> {
let dir = primary.compose_working_dir.as_deref();
let same = |c: &DockerContainer| dir.is_some() && c.compose_working_dir.as_deref() == dir;
members
.into_iter()
.filter(|c| {
same(c)
&& c.id != primary.id
&& !c.labels.contains_key(FOLDER_LABEL)
&& !c.labels.contains_key(CONFIG_LABEL)
})
.collect()
}
/// The container `containerId` names, among the project's containers: the primary without one.
fn choose<'a>(found: &'a Found, wanted: Option<&str>) -> IdeResult<&'a DockerContainer> {
let Some(wanted) = wanted.map(str::trim).filter(|w| !w.is_empty()) else {
return found.primary.as_ref().ok_or_else(|| {
IdeError::not_found("this project has no dev container yet; start it with devcontainer_up")
});
};
let wanted = wanted.to_ascii_lowercase();
let mut hits = found.all().filter(|c| wanted.len() >= 12 && c.id.to_ascii_lowercase().starts_with(&wanted));
match (hits.next(), hits.next()) {
(Some(container), None) => Ok(container),
_ => Err(IdeError::invalid(format!("container {wanted} does not belong to this project's dev container"))),
}
}
fn describe(container: &DockerContainer) -> String {
format!("{} ({})", container.name, ide_docker::short_id(&container.id))
}
// ---- docker, the CLI and the arguments ----
/// Docker is installed, its daemon answers and is on this machine (the project folder is
/// bind-mounted, and its labels name this machine's folders).
fn daemon() -> IdeResult<()> {
match ide_docker::availability(&DockerEndpoint::Default) {
DockerAvailability::Ready { .. } => {}
DockerAvailability::NotInstalled => return Err(IdeError::unavailable("Docker is not installed")),
DockerAvailability::DaemonDown { message, .. } => return Err(IdeError::unavailable(message)),
}
if ide_docker::endpoint_is_local(&DockerEndpoint::Default)? {
Ok(())
} else {
Err(IdeError::unavailable(
"The Docker daemon of the current context is not on this machine; dev containers need a local one.",
))
}
}
async fn docker_ready(host: &Host) -> IdeResult<()> {
host.blocking(daemon).await
}
fn is_config_file(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| CONFIG_NAMES.contains(&n))
}
/// The folder and configuration the call is about: the project root as opened, and `config`
/// (or the default one) joined to it, as the CLI is given them and labels the container.
fn target(call: &Call) -> IdeResult<Target> {
let root = call.root();
let config = match call.opt_str("config")?.map(|c| c.trim().to_owned()).filter(|c| !c.is_empty()) {
Some(raw) => {
let real = call.resolve_inside(&raw)?;
if !is_config_file(&real) {
return Err(IdeError::invalid("config must be a devcontainer.json or .devcontainer.json file"));
}
if !real.is_file() {
return Err(IdeError::not_found(format!("config {raw} does not exist")));
}
let base = dunce::canonicalize(root)?;
let inside =
real.strip_prefix(&base).map_err(|_| IdeError::invalid("config must be inside the project"))?;
Some(root.join(inside))
}
None => {
let config = ide_workspace::devcontainer::find(root);
if let Some(config) = &config {
ensure_inside(root, config)?;
}
config
}
};
Ok(Target::new(root, config))
}
/// Every configuration file of the project the CLI can be pointed at.
fn config_files(root: &Path) -> Vec<PathBuf> {
let dir = root.join(".devcontainer");
let mut files = vec![dir.join("devcontainer.json"), root.join(".devcontainer.json")];
if ensure_inside(root, &dir).is_ok() {
let mut named: Vec<PathBuf> = std::fs::read_dir(&dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path().join("devcontainer.json"))
.collect();
named.sort();
files.extend(named);
}
files.retain(|f| f.is_file() && ensure_inside(root, f).is_ok());
files
}
/// The error of a project without a configuration the tools can use by default.
fn no_config(call: &Call) -> IdeError {
let root = call.root().display();
let others: Vec<String> = config_files(call.root()).iter().map(|f| call.display(f)).collect();
if others.is_empty() {
return IdeError::not_found(format!("{root} has no devcontainer.json"));
}
IdeError::not_found(format!(
"{root} has no .devcontainer/devcontainer.json or .devcontainer.json: pass `config` with one of {}",
others.join(", ")
))
}
/// `timeout` in milliseconds for a start: a positive number.
fn start_timeout(call: &Call) -> IdeResult<std::time::Duration> {
if call.opt_i64("timeout")?.is_some_and(|n| n <= 0) {
return Err(IdeError::invalid("timeout must be positive"));
}
timeout(call, UP_TIMEOUT.as_millis() as usize)
}
fn tail_of(tail: Option<i64>) -> IdeResult<u32> {
match tail.unwrap_or(DEFAULT_TAIL) {
n @ 1..=MAX_TAIL => Ok(n as u32),
_ => Err(IdeError::invalid(format!("tail must be between 1 and {MAX_TAIL}"))),
}
}
/// `envs` as `(name, value)`: names a shell accepts.
fn envs_of(call: &Call) -> IdeResult<Vec<(String, String)>> {
let Some(value) = call.args.get("envs").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
if !value.is_object() {
return Err(IdeError::invalid("envs must be an object"));
}
let envs = call.str_map("envs")?;
for (name, value) in &envs {
let valid = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !valid {
return Err(IdeError::invalid(format!("envs: `{name}` is not a valid variable name")));
}
if value.contains('\0') {
return Err(IdeError::invalid(format!("envs: the value of {name} contains a NUL character")));
}
}
Ok(envs)
}
/// Pass the full approved ID to the CLI, including when the Run tab reruns this command.
fn exec_argv(
cli: &Path,
docker: &Path,
target: &Target,
container_id: &str,
envs: &[(String, String)],
command: &str,
) -> Vec<String> {
let lossy = |p: &std::ffi::OsStr| p.to_string_lossy().into_owned();
let mut argv = vec![lossy(cli.as_os_str()), "exec".to_owned()];
argv.extend(target.args().iter().map(|a| lossy(a)));
argv.extend(["--container-id".to_owned(), container_id.to_owned()]);
argv.extend(["--docker-path".to_owned(), lossy(docker.as_os_str())]);
argv.extend(envs.iter().map(|(k, v)| format!("--remote-env={k}={v}")));
argv.extend(["sh".to_owned(), "-c".to_owned(), command.to_owned()]);
argv
}
/// A command line for people: the arguments that need it in quotes.
fn shown(argv: &[String]) -> String {
let word = |a: &String| {
if !a.is_empty() && a.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@%+,".contains(c)) {
a.clone()
} else {
format!("'{}'", a.replace('\'', r"'\''"))
}
};
argv.iter().map(word).collect::<Vec<_>>().join(" ")
}
/// Refuses to change a container a window is open in.
fn not_attached(call: &Call, containers: &[&DockerContainer], what: &str) -> IdeResult<()> {
let attached = &call.host.dev_containers_attached;
match containers.iter().find(|c| attached.contains(&c.id)) {
Some(c) => Err(IdeError::invalid(format!(
"cannot {what}: {} is open in a window (Reopen in Container). Close that window or use Rebuild Container in it.",
describe(c)
))),
None => Ok(()),
}
}
// ---- the tools ----
fn status() -> Tool {
Tool::new(
"devcontainer_status",
&format!(
"Reports the project's dev container: `configFile` (the configuration in use, relative to the project, \
or null), `configFiles` (every configuration the project has, including `.devcontainer/<name>/devcontainer.json`), \
`forwardPorts` of the configuration, the project's `containers` (`id`, `name`, `state`, `status`, `image`, `ports`, \
`service` for Docker Compose, `primary`: the one the other tools act on; none when it was never started), `docker` \
(`ready`, or why Docker cannot be used), `dockerLocal` (the Docker daemon is on this machine) and `cliInstalled` \
(the Dev Containers CLI that starts it). Starts nothing. {WHICH}"
),
|call| async move {
let target = target(&call)?;
let data_dir = call.host.local_data_dir.clone();
let cli = call.host.blocking(move || Ok(crate::devcontainer::cli(&data_dir).is_ok())).await?;
let (docker, local, found) = match docker_ready(&call.host).await {
Ok(()) => match find(&call.host, &target).await {
Ok(found) => ("ready".to_owned(), true, found),
Err(e) => (format!("cannot list the containers: {}", e.message), true, Found::default()),
},
// Not usable: say why, and whether the fault is only that it is not local.
Err(e) => {
let local = call
.host
.blocking(|| Ok(ide_docker::endpoint_is_local(&DockerEndpoint::Default).unwrap_or(false)))
.await?;
(e.message, local, Found::default())
}
};
let root = call.root();
let primary = found.primary.as_ref().map(|p| p.id.clone());
let containers: Vec<Value> = found
.all()
.map(|c| {
let mut v = json!({
"id": c.id, "name": c.name, "state": c.state, "status": c.status,
"image": c.image, "ports": c.ports, "primary": Some(&c.id) == primary.as_ref(),
});
if let Some(service) = &c.compose_service {
v["service"] = service.clone().into();
}
v
})
.collect();
let mut out = Map::new();
out.insert("configFile".into(), target.config().map(|c| call.display(c)).into());
let files: Vec<String> = config_files(root).iter().map(|f| call.display(f)).collect();
out.insert("configFiles".into(), files.into());
let mut ports: Vec<Value> = Vec::new();
if let Some(config) = target.config() {
match ide_workspace::devcontainer::load_file(config) {
Ok(c) => {
ports.extend(c.forward_ports.iter().map(|p| Value::from(*p)));
ports.extend(c.forward_host_ports.iter().map(|(h, p)| Value::from(format!("{h}:{p}"))));
}
Err(e) => {
out.insert("configError".into(), e.into());
}
}
}
out.insert("forwardPorts".into(), ports.into());
out.insert("containers".into(), containers.into());
out.insert("docker".into(), docker.into());
out.insert("dockerLocal".into(), local.into());
out.insert("cliInstalled".into(), cli.into());
Output::json(Value::Object(out))
},
)
.param(Param::optional("config", ParamType::String, CONFIG))
}
fn logs() -> Tool {
Tool::new(
"devcontainer_logs",
&format!(
"Reads the end of a container's log (`docker logs`): the last `tail` lines (default {DEFAULT_TAIL}, at \
most {MAX_TAIL}) of the project's dev container, or of `containerId`, which must be one of the containers \
`devcontainer_status` lists (a Compose service's, for example). Returns `containerId`, `lines` (`text`, and `stderr` \
for what the container wrote to its error output) and `truncated` (the log may go on before them). Works on a \
stopped container. {WHICH}"
),
|call| async move {
let tail = tail_of(call.opt_i64("tail")?)?;
let timestamps = call.flag("timestamps", false)?;
let wanted = call.opt_str("containerId")?;
let target = target(&call)?;
docker_ready(&call.host).await?;
let found = find(&call.host, &target).await?;
let id = choose(&found, wanted.as_deref())?.id.clone();
let lines =
ops::log_tail(&call.host, DockerEndpoint::Default, id.clone(), tail, timestamps, call.cancel.clone())
.await?;
let truncated = lines.len() >= tail as usize;
let lines: Vec<Value> = lines.iter().map(|l| json!({ "text": l.text, "stderr": l.stderr })).collect();
Output::json(json!({ "containerId": id, "lines": lines, "truncated": truncated }))
},
)
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"containerId",
ParamType::String,
"A container of the project (at least 12 characters of its id, from `devcontainer_status`); default: the \
primary one",
))
.param(Param::optional("tail", ParamType::Integer, "Lines from the end of the log (1 to 5000, default 200)"))
.param(Param::optional("timestamps", ParamType::Boolean, "Prefix every line with its time (default false)"))
}
async fn start(call: Call) -> IdeResult<Output> {
let rebuild = call.flag("rebuild", false)?;
let target = target(&call)?;
let config = target.config().ok_or_else(|| no_config(&call))?;
let limit = start_timeout(&call)?;
let no_cache = call.flag("noCache", false)?;
if no_cache && !rebuild {
return Err(IdeError::invalid("noCache needs rebuild: true"));
}
let data_dir = call.host.local_data_dir.clone();
let (cli, docker) = call
.host
.blocking(move || {
daemon()?;
let docker =
ide_docker::docker_executable().ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
Ok((crate::devcontainer::cli(&data_dir)?, docker))
})
.await?;
let found = find(&call.host, &target).await?;
if !found.stale.is_empty() {
return Err(IdeError::unavailable("multiple dev containers match this configuration; see devcontainer_status"));
}
// Held until the start ends; a second one for the folder is refused, not queued.
let _busy = ide_remote::devcontainer::Busy::take(target.folder())?;
// Explicit labels disable the CLI's fallback to containers with the folder label alone.
let mut extra = vec![
"--id-label".to_owned(),
format!("{FOLDER_LABEL}={}", target.folder_label()),
"--id-label".to_owned(),
format!("{CONFIG_LABEL}={}", label_value(&config.to_string_lossy())),
];
if rebuild {
not_attached(&call, &found.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
}
if no_cache {
extra.push("--build-no-cache".to_owned());
}
let mut command = vec!["devcontainer".to_owned(), "up".to_owned()];
command.extend(target.args().iter().map(|a| a.to_string_lossy().into_owned()));
command.extend(extra.iter().cloned());
let removed = found.primary_id().filter(|_| rebuild);
let command = match removed {
Some(id) => format!("docker container rm --force {id}\n{}", shown(&command)),
None => shown(&command),
};
let existing = found.primary.as_ref().map(describe);
let detail = format!(
"{}\n\nContainer: {}",
command,
match (&existing, rebuild) {
(Some(c), true) => format!("{c}, removed first"),
(Some(c), false) => c.clone(),
(None, _) => "none yet".to_owned(),
}
);
call.confirm(if rebuild { "Rebuild dev container" } else { "Start dev container" }, Some(detail)).await?;
docker_ready(&call.host).await?;
let current = find(&call.host, &target).await?;
if found.primary_id() != current.primary_id() || !current.stale.is_empty() {
return Err(IdeError::unavailable(
"the dev container changed while awaiting approval; call devcontainer_up again",
));
}
if rebuild {
not_attached(&call, &current.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
}
ensure_inside(call.root(), config)?;
if let Some(id) = removed {
ide_workspace::devcontainer::load_file(config).map_err(IdeError::invalid)?;
if call.cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
call.project.require_trust()?;
// The CLI's rebuild flag resolves labels again. Remove only the ID shown for approval.
ops::docker_remove(&call.host, DockerEndpoint::Default, DockerObject::Container, vec![id.to_owned()], true)
.await?;
if find(&call.host, &target).await?.primary.is_some() {
return Err(IdeError::unavailable("a replacement dev container appeared; call devcontainer_up again"));
}
}
let removed = removed.map(str::to_owned);
let cancel = call.cancel.clone();
let up = call
.host
.blocking(move || {
if let Some(config) = target.config() {
ensure_inside(target.folder(), config)?;
}
let extra: Vec<&str> = extra.iter().map(String::as_str).collect();
ide_remote::devcontainer::up(
&cli,
&docker,
&target,
&extra,
limit,
&mut |line| tracing::debug!(target: "devcontainer", "{line}"),
&cancel,
)
})
.await?;
let mut out = json!({
"containerId": up.container, "remoteUser": up.user, "remoteWorkspaceFolder": up.folder, "outcome": "success",
});
if rebuild {
out["removed"] = removed.into();
}
Output::json(out)
}
fn up() -> Tool {
Tool::new(
"devcontainer_up",
&format!(
"Starts the project's dev container with the Dev Containers CLI (`devcontainer up`): builds the image \
when needed, creates or starts the container and runs the lifecycle commands of its configuration, which run the \
project's code on this machine and in the container; the user is asked first (unless the IDE runs tools without \
confirmation). With `rebuild` it removes the project's approved container first and builds \
and starts it again, to pick up a changed `devcontainer.json`, Dockerfile or features; files in the container that \
are not in the project folder or a volume are lost, and a container a window is open in is refused (use Rebuild \
Container in that window). Waits for it to finish, up to `timeout` milliseconds (default 30 minutes; the CLI is \
stopped when it passes), and returns `containerId`, `remoteUser`, `remoteWorkspaceFolder` and `outcome`, and with \
`rebuild` `removed`, the id of the container it replaced (null when there was none). An error carries the end of \
the CLI's log. One start per project folder runs at a time. {WHICH}"
),
start,
)
.write()
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"rebuild",
ParamType::Boolean,
"Remove the existing container and build it again (default false)",
))
.param(Param::optional(
"noCache",
ParamType::Boolean,
"With `rebuild`: build the image without Docker's cache (default false); refused without `rebuild`",
))
.param(Param::optional(
"timeout",
ParamType::Integer,
"Milliseconds to wait at most, more than 0 (default 1800000); the CLI is stopped when it passes",
))
}
fn exec() -> Tool {
Tool::new(
"devcontainer_exec",
&format!(
"Runs a shell command line in the project's running dev container (`devcontainer exec`: as the \
configuration's `remoteUser`, with its `remoteEnv`, in the project folder of the container), in a new or reused \
tab of OpenIDEA's Run tool window, as `run_command` does in the shell of this machine: the user is asked first \
(unless the IDE runs tools without confirmation), and the call returns when the command finishes, its output \
matches `pattern` or `timeout` milliseconds (default {EXEC_TIMEOUT_MS}) pass, with the same result (`state`, \
`exitCode`, `output`, `waitEnded`…) plus `containerId`; `wait_for_run`, `read_run_output`, `get_run_status`, \
`send_run_input` and `stop_run` follow it up by name. Stopping the tab ends the CLI on this machine; a process it \
started in the container may keep running there. The container must be running (see `devcontainer_status`, \
`devcontainer_up`). {WHICH}{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
),
|call| async move {
call.needs_window()?;
let name = tab_name(&call.str("name")?)?;
let command = call.str("command")?;
if command.trim().is_empty() {
return Err(IdeError::invalid("command must not be empty"));
}
let envs = envs_of(&call)?;
let target = target(&call)?;
let config = target.config().ok_or_else(|| no_config(&call))?.to_path_buf();
if let Some(run) = call.host.mcp_agent_runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
let data_dir = call.host.local_data_dir.clone();
let (cli, docker) = call
.host
.blocking(move || {
daemon()?;
let docker = ide_docker::docker_executable()
.ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
Ok((crate::devcontainer::cli(&data_dir)?, docker))
})
.await?;
let found = find(&call.host, &target).await?;
let container = found.primary.filter(DockerContainer::running).ok_or_else(|| {
IdeError::unavailable("the dev container is not running; start it with devcontainer_up")
})?;
let argv = exec_argv(&cli, &docker, &target, &container.id, &envs, &command);
let mut detail = format!(
"{command}\n\nTab: {name}\nContainer: {}\nCommand line: {}",
describe(&container),
shown(&argv)
);
for (key, value) in &envs {
detail.push_str(&format!("\n{key}={value}"));
}
let mut extra = Map::new();
extra.insert("containerId".into(), container.id.clone().into());
let tab = Tab {
subject: "Run in dev container".into(),
command: format!("in dev container {}: {command}", container.name),
name,
detail,
cwd: call.root().to_path_buf(),
env: Vec::new(),
execution: Execution::Container { id: container.id, config, argv },
extra,
};
start_in_tab(&call, tab, EXEC_TIMEOUT_MS).await
},
)
.write()
.param(Param::required("name", ParamType::String, NAME))
.param(Param::required(
"command",
ParamType::String,
"Shell command line to run in the container with `sh -c`, e.g. `npm test` or `pytest -x`",
))
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"envs",
ParamType::StringMap,
"Environment variables added for this command (names of letters, digits and `_`)",
))
.param(Param::optional(
"timeout",
ParamType::Integer,
"Milliseconds to wait for the command to finish before returning (0 returns once it started); the command \
keeps running after it",
))
.param(Param::optional(
"pattern",
ParamType::String,
"Regular expression that ends the wait when the command's output matches it. `waitEnded` is then `matched`",
))
.param(Param::optional("maxLinesCount", ParamType::Integer, MAX_LINES))
.param(Param::optional("truncateMode", ParamType::String, TRUNCATE_MODE))
}
fn stop() -> Tool {
Tool::new(
"devcontainer_stop",
&format!(
"Stops the project's dev container and the other containers of its Docker Compose project \
(`docker container stop`); nothing is removed, and `devcontainer_up` starts it again. Refused for a container a \
window is open in. The user is asked first (unless the IDE runs tools without confirmation). Returns `stopped`, \
the ids of the containers that were running (none when nothing was). {WHICH}"
),
|call| async move {
let target = target(&call)?;
docker_ready(&call.host).await?;
let found = find(&call.host, &target).await?;
let running = found.running_group();
if running.is_empty() {
return Output::json(json!({ "stopped": [] }));
}
not_attached(&call, &running, "stop it")?;
let ids: Vec<String> = running.iter().map(|c| c.id.clone()).collect();
let names: Vec<String> = running.iter().map(|c| describe(c)).collect();
let mut command = vec!["docker".to_owned(), "container".to_owned(), "stop".to_owned()];
command.extend(ids.iter().cloned());
call.confirm(
"Stop dev container",
Some(format!("{}\n\nContainers: {}", shown(&command), names.join(", "))),
)
.await?;
ops::stop_containers(&call.host, DockerEndpoint::Default, ids.clone()).await?;
Output::json(json!({ "stopped": ids }))
},
)
.write()
.param(Param::optional("config", ParamType::String, CONFIG))
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT: &str = "/work/app";
const CONFIG_FILE: &str = "/work/app/.devcontainer/devcontainer.json";
fn container(id: &str, labels: &[(&str, &str)]) -> DockerContainer {
DockerContainer {
id: id.repeat(64 / id.len()),
name: format!("name-{id}"),
image: "img".into(),
command: String::new(),
state: "running".into(),
status: "Up".into(),
ports: String::new(),
created_at: "2026-01-01 10:00:00 +0000 UTC".into(),
compose_project: None,
compose_service: None,
compose_working_dir: None,
compose_files: Vec::new(),
mounts: Vec::new(),
networks: Vec::new(),
labels: labels.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
}
}
fn target() -> Target {
Target::new(ROOT, Some(PathBuf::from(CONFIG_FILE)))
}
#[test]
fn labels_decide_which_container_is_the_projects() {
let both = container("a", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)]);
let legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
let other_folder = container("c", &[(FOLDER_LABEL, "/work/other"), (CONFIG_LABEL, CONFIG_FILE)]);
let other_config =
container("d", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, "/work/app/.devcontainer/b/devcontainer.json")]);
let unlabelled = container("e", &[("com.docker.compose.project", "app")]);
let t = target();
let config_only = container("f", &[(CONFIG_LABEL, CONFIG_FILE)]);
assert!(project_containers(vec![legacy.clone()], &t).is_empty());
let matches =
project_containers(vec![both.clone(), legacy, other_folder, other_config, unlabelled, config_only], &t);
assert_eq!(matches.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), [both.id.as_str()]);
assert!(project_containers(vec![both], &Target::new(ROOT, None)).is_empty());
}
#[test]
fn a_windows_drive_letter_is_matched_in_lower_case() {
let root = r"C:\Users\me\app";
let config = r"C:\Users\me\app\.devcontainer\devcontainer.json";
let t = Target::new(root, Some(PathBuf::from(config)));
let written = container("a", &[(FOLDER_LABEL, r"c:\Users\me\app"), (CONFIG_LABEL, config)]);
assert_eq!(project_containers(vec![written], &t).len(), 1);
assert_eq!(t.folder_label(), r"c:\Users\me\app");
}
#[test]
fn the_primary_is_running_before_stopped_and_new_before_old() {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut old_running = container("a", &labels);
old_running.created_at = "2026-01-01 10:00:00 +0000 UTC".into();
let mut new_running = container("b", &labels);
new_running.created_at = "2026-02-01 10:00:00 +0000 UTC".into();
let mut newest_stopped = container("c", &labels);
newest_stopped.created_at = "2026-03-01 10:00:00 +0000 UTC".into();
newest_stopped.state = "exited".into();
let order: Vec<String> = project_containers(vec![old_running, newest_stopped, new_running], &target())
.into_iter()
.map(|c| c.name)
.collect();
assert_eq!(order, ["name-b", "name-a", "name-c"]);
}
fn found() -> Found {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut sibling = container("d", &[("com.docker.compose.project", "app")]);
sibling.compose_service = Some("db".into());
Found { primary: Some(container("a", &labels)), stale: vec![container("b", &labels)], siblings: vec![sibling] }
}
#[test]
fn compose_siblings_share_the_working_directory_of_a_primary_that_has_one() {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut primary = container("a", &labels);
let (mut mine, mut foreign, mut unlabelled) = (container("d", &[]), container("e", &[]), container("f", &[]));
primary.compose_working_dir = Some("/work/app/.devcontainer".into());
mine.compose_working_dir = primary.compose_working_dir.clone();
foreign.compose_working_dir = Some("/other/app/.devcontainer".into());
let mut legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
legacy.compose_working_dir = primary.compose_working_dir.clone();
let members = vec![primary.clone(), mine.clone(), foreign.clone(), unlabelled.clone(), legacy];
let ids: Vec<String> = siblings_of(&primary, members.clone()).into_iter().map(|c| c.id).collect();
assert_eq!(ids, [mine.id.clone()]);
// A primary without a working directory matches nobody, not even containers without one.
primary.compose_working_dir = None;
unlabelled.compose_working_dir = None;
assert!(siblings_of(&primary, members).is_empty());
}
#[test]
fn a_container_id_must_name_one_of_the_projects_containers() {
let found = found();
let id = |c: &DockerContainer| c.id.clone();
let primary = id(found.primary.as_ref().unwrap());
assert_eq!(choose(&found, None).unwrap().id, primary);
assert_eq!(choose(&found, Some(&primary)).unwrap().id, primary);
assert_eq!(choose(&found, Some(&primary[..12].to_uppercase())).unwrap().id, primary);
assert_eq!(choose(&found, Some(&id(&found.siblings[0]))).unwrap().name, "name-d");
for foreign in ["e".repeat(64).as_str(), "ffffffffffff", &primary[..11], "", "--all", "name-a"] {
let refused = choose(&found, Some(foreign)).map(|c| c.id.clone());
if foreign.trim().is_empty() {
assert_eq!(refused.unwrap(), primary);
continue;
}
let message = refused.unwrap_err().message;
assert!(message.ends_with("does not belong to this project's dev container"), "{foreign}: {message}");
}
let none = Found { primary: None, stale: Vec::new(), siblings: Vec::new() };
assert!(choose(&none, None).unwrap_err().message.contains("devcontainer_up"));
}
#[test]
fn stop_acts_on_the_primary_and_its_compose_project_only() {
let mut found = found();
found.stale[0].state = "running".into();
let names: Vec<&str> = found.running_group().into_iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["name-a", "name-d"]);
found.siblings[0].state = "exited".into();
assert_eq!(found.running_group().len(), 1);
}
#[test]
fn tail_is_one_to_five_thousand() {
assert_eq!(tail_of(None).unwrap(), 200);
assert_eq!(tail_of(Some(1)).unwrap(), 1);
assert_eq!(tail_of(Some(5000)).unwrap(), 5000);
for bad in [0, -1, 5001] {
assert!(tail_of(Some(bad)).is_err(), "{bad}");
}
}
#[test]
fn only_devcontainer_json_files_are_configurations() {
assert!(is_config_file(Path::new("/p/.devcontainer/devcontainer.json")));
assert!(is_config_file(Path::new("/p/.devcontainer.json")));
assert!(!is_config_file(Path::new("/p/package.json")));
assert!(!is_config_file(Path::new("/p/.devcontainer/Dockerfile")));
}
#[test]
fn every_configuration_of_the_project_is_listed() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for f in [".devcontainer/devcontainer.json", ".devcontainer/py/devcontainer.json", ".devcontainer.json"] {
std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap();
std::fs::write(root.join(f), "{}").unwrap();
}
std::fs::create_dir_all(root.join(".devcontainer/empty")).unwrap();
let found: Vec<String> = config_files(root)
.iter()
.map(|f| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"))
.collect();
assert_eq!(
found,
[".devcontainer/devcontainer.json", ".devcontainer.json", ".devcontainer/py/devcontainer.json"]
);
}
#[test]
fn a_command_line_for_people_quotes_what_needs_it() {
let argv = ["devcontainer", "exec", "--remote-env=A=b c", "sh", "-c", "echo 'x' && ls"].map(String::from);
assert_eq!(shown(&argv), r#"devcontainer exec '--remote-env=A=b c' sh -c 'echo '\''x'\'' && ls'"#);
}
/// A stand-in for the Dev Containers CLI that checks where `exec` and `sh -c` are.
#[cfg(unix)]
#[test]
fn exec_pins_the_approved_id_even_when_a_replacement_matches() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let cli = dir.path().join("devcontainer");
let approved = "a".repeat(64);
let replacement = "b".repeat(64);
let script = format!(
r#"#!/bin/sh
[ "$1" = exec ] || {{ echo "exec is not first: $*" >&2; exit 2; }}
[ "$2 $3" = "--workspace-folder {ROOT}" ] || {{ echo "no folder: $*" >&2; exit 2; }}
[ "$4 $5" = "--config {CONFIG_FILE}" ] || {{ echo "no config: $*" >&2; exit 2; }}
[ "$6" = "--container-id" ] || {{ echo "no approved id: $*" >&2; exit 2; }}
[ "$7" = "$MATCHING_CONTAINER" ] || {{ echo "pinned container unavailable" >&2; exit 3; }}
[ "$8 $9" = "--docker-path /usr/bin/docker" ] || {{ echo "no docker: $*" >&2; exit 2; }}
shift 9
[ "$1" = "--remote-env=A=1 2" ] && [ "$2" = "--remote-env=B_=" ] || {{ echo "no env: $*" >&2; exit 2; }}
[ $# -eq 5 ] && [ "$3 $4" = "sh -c" ] || {{ echo "sh -c is not last: $*" >&2; exit 2; }}
printf '%s' "$5"
"#,
);
std::fs::write(&cli, script).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
let command = "echo \"$A\" && ls -- 'x y'; exit 3";
let envs = vec![("A".to_owned(), "1 2".to_owned()), ("B_".to_owned(), String::new())];
let argv = exec_argv(&cli, Path::new("/usr/bin/docker"), &target(), &approved, &envs, command);
assert_eq!(argv[1], "exec");
assert_eq!(&argv[argv.len() - 3..], ["sh", "-c", command]);
let invoke =
|id| std::process::Command::new(&argv[0]).args(&argv[1..]).env("MATCHING_CONTAINER", id).output().unwrap();
let out = invoke(&approved);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8_lossy(&out.stdout), command);
let out = invoke(&replacement);
assert_eq!(out.status.code(), Some(3));
assert!(out.stdout.is_empty());
}
}
+20 -5
Переглянути файл
@@ -2,6 +2,7 @@
mod background;
mod check;
mod debug;
mod devcontainer;
mod edit;
mod editors;
mod requests;
@@ -27,7 +28,7 @@ use ide_mcp::{ToolCallError, ToolRegistry};
pub use reports::{
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM, TARGET_PARAM};
use serde_json::json;
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
@@ -40,7 +41,7 @@ impl Registry {
}
}
fn tools() -> Vec<tool::Tool> {
fn tools(local_desktop: bool) -> Vec<tool::Tool> {
let mut tools = files::tools();
tools.extend(search::tools());
tools.extend(editors::tools());
@@ -53,6 +54,9 @@ fn tools() -> Vec<tool::Tool> {
tools.extend(run::tools());
tools.extend(vcs::tools());
tools.extend(http::tools());
if local_desktop {
tools.extend(devcontainer::tools());
}
tools
}
@@ -63,7 +67,7 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
}
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
let mut all: Vec<_> = tools(host.local_desktop).into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
}
@@ -144,7 +148,7 @@ impl Registry {
{
return Some(Found::Plugin { plugins, plugin, tool, metadata });
}
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
tools(self.0.local_desktop).into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
}
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
@@ -307,10 +311,21 @@ impl Registry {
mod tests {
#[test]
fn restricted_mode_excludes_execution_tools() {
let mut tool = super::tools().remove(0).metadata;
let mut tool = super::tools(false).remove(0).metadata;
assert!(super::allowed(&tool, false));
tool.read_only = false;
assert!(!super::allowed(&tool, false));
assert!(super::allowed(&tool, true));
}
#[test]
fn dev_container_tools_that_start_run_or_stop_are_not_read_only() {
let tools = super::devcontainer::tools();
let read_only = |name: &str| tools.iter().find(|t| t.metadata.name == name).unwrap().metadata.read_only;
assert!(read_only("devcontainer_status") && read_only("devcontainer_logs"));
for name in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
assert!(!read_only(name), "{name}");
}
assert_eq!(tools.len(), 5);
}
}
+216 -44
Переглянути файл
@@ -9,7 +9,8 @@
use super::output::{TRUNCATED_MARKER, temp_output_file};
use crate::ops::Emit;
use ide_core::{IdeEvent, IdeResult, RunId, SharedSink};
use ide_core::event::McpAgentRunTarget;
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use ide_run::{OutputChunk, RunConfig, RunInfo};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
@@ -20,6 +21,8 @@ use std::time::SystemTime;
/// Run configuration parameter naming the agent tab a start belongs to.
pub const AGENT_PARAM: &str = "mcp.agentRun";
/// Run configuration parameter containing the serialized execution target.
pub const TARGET_PARAM: &str = "mcp.agentTarget";
/// Run configuration parameter with Settings › Tools › Terminal › Shell path (may be empty).
pub const SHELL_PARAM: &str = "mcp.agentShell";
/// What every agent tab's name starts with.
@@ -28,6 +31,21 @@ const MAX_NAME_LENGTH: usize = 64;
/// How much of the log a wait for a pattern reads at a time.
const SCAN_CHUNK: usize = 4 << 20;
#[derive(Clone)]
pub(crate) enum Execution {
Host,
Container { id: String, config: PathBuf, argv: Vec<String> },
}
impl Execution {
pub(crate) fn target(&self) -> McpAgentRunTarget {
match self {
Self::Host => McpAgentRunTarget::Host,
Self::Container { id, .. } => McpAgentRunTarget::Container { id: id.clone() },
}
}
}
/// The tab name for what an agent asked for: trimmed, with [`NAME_PREFIX`] once.
pub fn tab_name(raw: &str) -> IdeResult<String> {
let raw = raw.trim();
@@ -58,7 +76,7 @@ impl AgentRuns {
}
/// The tab for the agent's next start of `name`: refused while its process runs, since
/// only an explicit `stop_run` may end it.
/// only an explicit `stop_run` may end it. The execution applies to exactly this command.
pub(crate) fn prepare(
&self,
root: &Path,
@@ -66,6 +84,7 @@ impl AgentRuns {
name: &str,
command: &str,
cwd: &str,
execution: Execution,
) -> Result<Arc<AgentRun>, Arc<AgentRun>> {
let mut runs = self.0.lock();
let run = match runs.iter().find(|r| r.root == root && r.name == name) {
@@ -78,13 +97,15 @@ impl AgentRuns {
};
drop(runs);
let mut s = run.state.lock();
if s.running() {
if s.running() || s.agent_start {
drop(s);
return Err(run);
}
*run.window.lock() = window.to_owned();
s.previous = Some(Previous { command: s.command.clone(), cwd: s.cwd.clone(), execution: s.execution.clone() });
s.command = command.to_owned();
s.cwd = cwd.to_owned();
s.execution = execution;
s.agent_start = true;
s.start_error = None;
s.closed_at = None;
@@ -94,11 +115,16 @@ impl AgentRuns {
Ok(run)
}
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped.
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped, and
/// one that did keeps the command and execution its window still has the configuration of.
pub(crate) fn abandon(&self, run: &Arc<AgentRun>) {
let never_ran = {
let mut s = run.state.lock();
s.agent_start = false;
if std::mem::take(&mut s.agent_start)
&& let Some(Previous { command, cwd, execution }) = s.previous.take()
{
(s.command, s.cwd, s.execution) = (command, cwd, execution);
}
s.process.is_none()
};
if never_ran {
@@ -109,31 +135,59 @@ impl AgentRuns {
/// Called for every run start: for a start of an agent tab, turns its command line into
/// the shell's invocation and opens a new process record.
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> Option<Launch> {
let name = config.extras.params.get(AGENT_PARAM).cloned()?;
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> IdeResult<Option<Launch>> {
let unavailable = || IdeError::invalid("the approved agent run target is unavailable; start a new MCP run");
let Some(name) = config.extras.params.get(AGENT_PARAM) else {
if config.id.starts_with("mcp-agent:") || config.extras.params.contains_key(TARGET_PARAM) {
return Err(unavailable());
}
return Ok(None);
};
let target: McpAgentRunTarget = config
.extras
.params
.get(TARGET_PARAM)
.and_then(|target| serde_json::from_str(target).ok())
.ok_or_else(unavailable)?;
let line = config.command.clone();
let cwd = config.cwd.as_deref().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
let run = {
let mut runs = self.0.lock();
match runs.iter().find(|r| r.root == root && r.name == name) {
match runs.iter().find(|r| r.root == root && r.name == *name) {
Some(run) => run.clone(),
None => {
let run = Arc::new(AgentRun::new(root, &name, &line, &cwd));
None if target == McpAgentRunTarget::Host => {
let run = Arc::new(AgentRun::new(root, name, &line, &cwd));
runs.push(run.clone());
run
}
None => return Err(unavailable()),
}
};
let mut state = run.state.lock();
if state.execution.target() != target || state.running() {
return Err(unavailable());
}
let (program, args) = match &state.execution {
Execution::Host => shell_invocation(config.extras.params.get(SHELL_PARAM).map(String::as_str), &line),
Execution::Container { config, argv, .. } => {
if state.command != line {
return Err(unavailable());
}
crate::mcp::tool::ensure_inside(root, config)?;
let (program, args) = argv.split_first().ok_or_else(unavailable)?;
(program.clone(), args.to_vec())
}
};
*run.window.lock() = window.to_owned();
let shell = config.extras.params.get(SHELL_PARAM).cloned();
let (program, args) = shell_invocation(shell.as_deref(), &line);
config.command = program;
config.args = args;
config.extras.target = Some(String::new());
// Pipes: the Run tool window's console shows the output and sends the user's input lines.
config.extras.emulate_terminal = false;
let generation = run.begin(&line);
Some(Launch { run, generation })
*run.window.lock() = window.to_owned();
let generation = state.begin(&line);
drop(state);
run.changed.notify_waiters();
Ok(Some(Launch { run, generation }))
}
fn by_process(&self, id: RunId) -> Option<Arc<AgentRun>> {
@@ -255,9 +309,18 @@ struct Process {
stopped_by: Option<Actor>,
}
struct Previous {
command: String,
cwd: String,
execution: Execution,
}
struct State {
command: String,
cwd: String,
execution: Execution,
/// What the tab was before the agent's pending start, for [`AgentRuns::abandon`].
previous: Option<Previous>,
log: Option<(PathBuf, std::fs::File)>,
log_len: u64,
generation: u64,
@@ -280,6 +343,32 @@ impl State {
fn running(&self) -> bool {
self.process.as_ref().is_some_and(|p| p.ended.is_none())
}
fn begin(&mut self, line: &str) -> u64 {
self.generation += 1;
let by = if std::mem::take(&mut self.agent_start) { Actor::Agent } else { Actor::User };
let now = SystemTime::now();
if by == Actor::User {
self.interventions.push((now, Intervention::Rerun));
}
self.command = line.to_owned();
self.previous = None;
self.agent_stop = false;
self.start_error = None;
self.closed_at = None;
self.typed.clear();
self.escape = Escape::None;
self.process = Some(Process {
generation: self.generation,
run: None,
by,
started_at: now,
offset: self.log_len,
ended: None,
stopped_by: None,
});
self.generation
}
}
/// An agent tab.
@@ -326,6 +415,8 @@ impl AgentRun {
state: Mutex::new(State {
command: command.to_owned(),
cwd: cwd.to_owned(),
execution: Execution::Host,
previous: None,
log: None,
log_len: 0,
generation: 0,
@@ -348,28 +439,6 @@ impl AgentRun {
self.window.lock().clone()
}
fn begin(&self, line: &str) -> u64 {
let mut s = self.state.lock();
s.generation += 1;
let generation = s.generation;
let by = if std::mem::take(&mut s.agent_start) { Actor::Agent } else { Actor::User };
let now = SystemTime::now();
if by == Actor::User {
s.interventions.push((now, Intervention::Rerun));
}
s.command = line.to_owned();
s.agent_stop = false;
s.start_error = None;
s.closed_at = None;
s.typed.clear();
s.escape = Escape::None;
let offset = s.log_len;
s.process = Some(Process { generation, run: None, by, started_at: now, offset, ended: None, stopped_by: None });
drop(s);
self.changed.notify_waiters();
generation
}
fn output(&self, text: &str) {
let mut s = self.state.lock();
if s.log.is_none() {
@@ -874,6 +943,109 @@ mod tests {
run.take_interventions().iter().map(|v| v["message"].as_str().unwrap().to_owned()).collect()
}
fn agent_config(line: &str, target: McpAgentRunTarget) -> RunConfig {
let mut config = RunConfig {
id: "mcp-agent:x".into(),
name: "x".into(),
kind: "shell".into(),
command: line.into(),
args: Vec::new(),
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: true,
extras: Default::default(),
};
config.extras.params.insert(AGENT_PARAM.into(), "_agent_x".into());
config.extras.params.insert(SHELL_PARAM.into(), "/bin/sh".into());
config.extras.params.insert(TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
config
}
fn container_execution(root: &Path, id: &str) -> Execution {
Execution::Container {
id: id.to_owned(),
config: root.join(".devcontainer.json"),
argv: ["devcontainer", "exec", "--container-id", id, "sh", "-c", "echo 'a b'"].map(str::to_owned).to_vec(),
}
}
#[test]
fn reruns_keep_the_approved_container_and_refuse_missing_or_changed_targets() {
let runs = AgentRuns::default();
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let id = "a".repeat(64);
let execution = container_execution(root, &id);
let line = "in the container: echo";
let saved = agent_config(line, execution.target());
let approve = |execution| runs.prepare(root, "main", "_agent_x", line, "", execution).ok().unwrap();
let run = approve(execution);
for _ in 0..2 {
let mut config = saved.clone();
let launch = runs.launch(root, "main", &mut config).unwrap().unwrap();
assert_eq!(config.command, "devcontainer");
assert_eq!(config.args, ["exec", "--container-id", &id, "sh", "-c", "echo 'a b'"]);
run.exited(launch.generation, Some(0));
}
let mut missing = saved.clone();
missing.extras.params.remove(TARGET_PARAM);
assert!(runs.launch(root, "main", &mut missing).is_err());
missing.extras.params.remove(AGENT_PARAM);
assert!(runs.launch(root, "main", &mut missing).is_err());
let mut other_line = saved.clone();
other_line.command = "something else".into();
assert!(runs.launch(root, "main", &mut other_line).is_err());
let mut wrong_kind = agent_config(line, McpAgentRunTarget::Host);
assert!(runs.launch(root, "main", &mut wrong_kind).is_err());
approve(container_execution(root, &"b".repeat(64)));
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
runs.abandon(&run);
runs.forget_window("main");
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
let mut shell = agent_config("ls", McpAgentRunTarget::Host);
runs.launch(root, "main", &mut shell).unwrap().unwrap();
assert_eq!((shell.command.as_str(), shell.args.last().map(String::as_str)), ("/bin/sh", Some("ls")));
}
#[test]
fn an_abandoned_start_leaves_the_tab_as_its_window_knows_it() {
let runs = AgentRuns::default();
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let execution = container_execution(root, &"a".repeat(64));
let target = execution.target();
let finish = |run: &AgentRun| {
let generation = run.state.lock().generation;
run.exited(generation, Some(0));
};
// A shell command, then a dev container one whose start never reaches the window: a
// rerun of the shell configuration still runs in the shell.
let run = runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
runs.launch(root, "main", &mut agent_config("ls", McpAgentRunTarget::Host)).unwrap().unwrap();
finish(&run);
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution.clone()).ok().unwrap();
runs.abandon(&run);
let mut rerun = agent_config("ls", McpAgentRunTarget::Host);
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
assert_eq!(rerun.command, "/bin/sh");
finish(&run);
// And the other way round: the dev container configuration keeps its argv.
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution).ok().unwrap();
runs.launch(root, "main", &mut agent_config("in the container: ls", target.clone())).unwrap().unwrap();
finish(&run);
runs.prepare(root, "main", "_agent_x", "pwd", "", Execution::Host).ok().unwrap();
runs.abandon(&run);
let mut rerun = agent_config("in the container: ls", target);
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
assert_eq!(rerun.command, "devcontainer");
}
#[test]
fn names_get_the_prefix_once() {
assert_eq!(tab_name(" build ").unwrap(), "_agent_build");
@@ -898,11 +1070,11 @@ mod tests {
fn starts_that_the_agent_did_not_ask_for_are_reruns() {
let run = run();
run.state.lock().agent_start = true;
let first = run.begin("echo");
let first = run.state.lock().begin("echo");
assert!(messages(&run).is_empty());
run.exited(first, Some(0));
assert_eq!(run.status()["state"], "succeeded");
run.begin("echo");
run.state.lock().begin("echo");
let told = messages(&run);
assert_eq!(told.len(), 1);
assert!(told[0].starts_with("The user reran this command at "), "{told:?}");
@@ -913,7 +1085,7 @@ mod tests {
fn stops_are_the_agents_only_when_it_asked() {
let run = run();
run.state.lock().agent_start = true;
let generation = run.begin("sleep 9");
let generation = run.state.lock().begin("sleep 9");
run.state.lock().process.as_mut().unwrap().run = Some(RunId(7));
run.stopping(RunId(7));
run.stopping(RunId(7));
@@ -922,7 +1094,7 @@ mod tests {
assert_eq!(run.status()["state"], "stoppedByUser");
run.state.lock().agent_start = true;
let generation = run.begin("sleep 9");
let generation = run.state.lock().begin("sleep 9");
run.state.lock().process.as_mut().unwrap().run = Some(RunId(8));
run.agent_stopping();
run.stopping(RunId(8));
@@ -934,12 +1106,12 @@ mod tests {
fn faults_are_crashes_and_other_codes_failures() {
let run = run();
for (code, state) in [(1, "failed"), (130, "failed")] {
let generation = run.begin("x");
let generation = run.state.lock().begin("x");
run.exited(generation, Some(code));
assert_eq!(run.status()["state"], state, "{code}");
}
if cfg!(unix) {
let generation = run.begin("x");
let generation = run.state.lock().begin("x");
run.exited(generation, Some(139));
let status = run.status();
assert_eq!(status["state"], "crashed");
@@ -950,7 +1122,7 @@ mod tests {
#[test]
fn reads_whole_characters_and_tails_lines() {
let run = run();
run.begin("x");
run.state.lock().begin("x");
run.output("one\n");
run.output("twö\nthree\n");
// `ö` is bytes 6..8: a cut inside it moves to the character's end or start.
+80 -38
Переглянути файл
@@ -1,13 +1,14 @@
//! `run_command` and the tools that follow its tab up: `wait_for_run`, `read_run_output`,
//! `get_run_status`, `send_run_input`, `stop_run` and `list_runs` (see [`super::agent`]).
use super::agent::{AgentRun, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
use super::agent::{AgentRun, Execution, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
use super::output::RUN_PREVIEW_MAX_LENGTH;
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::run::timeout;
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value};
use std::path::PathBuf;
use std::sync::Arc;
const RUN_TIMEOUT_MS: usize = 10_000;
@@ -20,21 +21,22 @@ const READ_CAP: usize = 1 << 20;
/// Lines of output quoted when a name is still running.
const BUSY_TAIL_LINES: usize = 20;
const NAME: &str = "Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
pub(crate) const NAME: &str =
"Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
pub(crate) const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
has finished starts the next command in the same tab. A name whose command is still running is refused (with that \
command and its last output); stop it with `stop_run` first or use another name. Nothing is stopped implicitly.";
const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
pub(crate) const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
it. Results then carry `interventions` (for example `User input: …` or `The user reran this command at …`) and \
`advice`: unless the user asked otherwise, stop what you are doing, tell the user you received the intervention and \
wait for their confirmation before you continue.";
const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
pub(crate) const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
bars). `output` is that text cleaned of escape sequences, at most `maxLinesCount` lines (default 2000): beyond it, \
`truncateMode` START (default) keeps the end, END the start, MIDDLE both ends, NONE everything, with a \
`<<<...content truncated...>>>` line where lines were left out and `truncatedLines` saying how many. `outputStart` \
and `nextOffset` are positions in the tab's raw output log; pass `nextOffset` as `offset` to read on.";
const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
pub(crate) const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
pub(crate) const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
(keeps the start), MIDDLE (keeps both ends) or NONE";
/// `list_runs`: tabs returned by default, and characters of each command, enough to tell them apart.
const LIST_LIMIT: usize = 10;
@@ -112,7 +114,7 @@ fn offset(call: &Call, name: &str) -> IdeResult<Option<u64>> {
}
}
fn busy(run: &AgentRun) -> IdeError {
pub(crate) fn busy(run: &AgentRun) -> IdeError {
let tail = run.tail(run.process_offset(), BUSY_TAIL_LINES, RUN_PREVIEW_MAX_LENGTH).map(|t| t.0).unwrap_or_default();
IdeError::invalid(format!(
"`{}` is still running `{}`. Stop it with stop_run first, or use another name.\nLast output:\n{}",
@@ -122,6 +124,66 @@ fn busy(run: &AgentRun) -> IdeError {
))
}
/// A command to start in an agent tab: [`start_in_tab`].
pub(crate) struct Tab {
/// What the confirmation dialog is titled with.
pub subject: String,
/// The tab's name, with its prefix.
pub name: String,
/// The command line the tab shows and records.
pub command: String,
/// What the confirmation dialog says the command does.
pub detail: String,
pub cwd: PathBuf,
pub env: Vec<(String, String)>,
pub execution: Execution,
/// Added to the result.
pub extra: Map<String, Value>,
}
/// The rest of `run_command`: asks the user, starts `tab` in the Run tool window and waits as
/// the `timeout` and `pattern` arguments say. Refused while the tab's command runs.
pub(crate) async fn start_in_tab(call: &Call, tab: Tab, default_timeout_ms: usize) -> IdeResult<Output> {
let name = tab.name.clone();
let deadline = deadline(call, default_timeout_ms)?;
let ready = pattern(call)?;
let host = call.host();
let runs = &host.mcp_agent_runs;
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
call.confirm(&tab.subject, Some(tab.detail)).await?;
let shown_cwd = call.display(&tab.cwd);
let target = tab.execution.target();
let run = runs
.prepare(call.root(), call.window(), &name, &tab.command, &shown_cwd, tab.execution)
.map_err(|r| busy(&r))?;
let request = ide_core::event::McpUiRequest::AgentRun {
name: name.clone(),
command: tab.command,
cwd: tab.cwd.into(),
env: tab.env.into_iter().collect(),
target,
};
if let Err(e) = call.ask(request).await {
let error = run.start_error();
runs.abandon(&run);
return Err(match error {
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
None => e,
});
}
if let Some(error) = run.start_error() {
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
}
let from = run.process_offset();
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
let mut extra = output_view(call, &run, from)?;
extra.insert("waitEnded".into(), end.as_str().into());
extra.extend(tab.extra);
result(&run, extra)
}
pub fn run_command() -> Tool {
Tool::new(
"run_command",
@@ -154,13 +216,6 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
None => call.root().to_path_buf(),
};
let env = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
let deadline = deadline(&call, RUN_TIMEOUT_MS)?;
let ready = pattern(&call)?;
let host = call.host();
let runs = &host.mcp_agent_runs;
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
let shown_cwd = call.display(&cwd);
let mut detail = format!(
"{command}\n\nTab: {name}\nWorking directory: {}",
@@ -169,30 +224,17 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
for (key, value) in env.iter().flatten() {
detail.push_str(&format!("\n{key}={value}"));
}
call.confirm(&name, Some(detail)).await?;
let run = runs.prepare(call.root(), call.window(), &name, &command, &shown_cwd).map_err(|r| busy(&r))?;
let request = ide_core::event::McpUiRequest::AgentRun {
name: name.clone(),
command: command.clone(),
cwd: cwd.into(),
env: env.unwrap_or_default().into_iter().collect(),
let tab = Tab {
subject: name.clone(),
name,
command,
detail,
cwd,
env: env.unwrap_or_default(),
execution: Execution::Host,
extra: Map::new(),
};
if let Err(e) = call.ask(request).await {
let error = run.start_error();
runs.abandon(&run);
return Err(match error {
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
None => e,
});
}
if let Some(error) = run.start_error() {
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
}
let from = run.process_offset();
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
let mut extra = output_view(&call, &run, from)?;
extra.insert("waitEnded".into(), end.as_str().into());
result(&run, extra)
start_in_tab(&call, tab, RUN_TIMEOUT_MS).await
},
)
.write()
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
//! Run configurations, builds and agent commands; every start asks the user first.
pub(crate) mod agent;
mod agent_tools;
pub(crate) mod agent_tools;
mod build;
pub(crate) mod configs;
mod output;
+38 -2
Переглянути файл
@@ -6,8 +6,9 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer,
DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget,
RegistryAuth,
};
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -97,6 +98,41 @@ pub async fn docker_container_op(
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
/// The containers (running or not) that carry every `label` (`key` or `key=value`).
pub(crate) async fn containers_with_labels(
host: &Host,
endpoint: DockerEndpoint,
labels: Vec<String>,
) -> IdeResult<Vec<DockerContainer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::containers(&endpoint, &labels)).await
}
/// The last `tail` lines of a container's log, without following it.
pub(crate) async fn log_tail(
host: &Host,
endpoint: DockerEndpoint,
id: String,
tail: u32,
timestamps: bool,
cancel: CancellationToken,
) -> IdeResult<Vec<DockerLogLine>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || {
let lines = std::sync::Mutex::new(Vec::new());
ide_docker::logs(&endpoint, &id, tail, false, timestamps, &cancel, &|batch| {
lines.lock().unwrap_or_else(|e| e.into_inner()).extend(batch)
})?;
Ok(lines.into_inner().unwrap_or_else(|e| e.into_inner()))
})
.await
}
pub(crate) async fn stop_containers(host: &Host, endpoint: DockerEndpoint, ids: Vec<String>) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, ContainerOp::Stop)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
+3 -5
Переглянути файл
@@ -326,13 +326,11 @@ pub async fn run_start(
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
let _ = on_output.send(chunk);
});
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let operation = config.extras.params.get("plugin.operation").cloned();
let mut config = config;
let agent = match host.project(window) {
Ok(project) => host.mcp_agent_runs.launch(&project.root, window, &mut config),
Err(_) => None,
};
let project = host.project(window)?;
let agent = host.mcp_agent_runs.launch(&project.root, window, &mut config)?;
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let on_output = match &agent {
Some(agent) => agent.wrap_output(on_output),
None => on_output,
+53 -1
Переглянути файл
@@ -115,6 +115,23 @@ pub struct Project {
pub light: bool,
}
/// Selects the same managed Vue executable for Volar and the vtsls companion plugin.
fn configure_vue_release(settings: &mut ide_core::settings::Settings, project_root: &Path, app_data: &Path) {
let name = ide_tools::vue::SERVER;
if settings.tool_path(name).is_some()
|| settings.language_servers.get(name).is_some_and(|entry| !entry.command.trim().is_empty())
{
return;
}
let release = ide_tools::vue::release(Some(project_root), &settings.tool_downloads.vue_language_server_version);
if release != "latest" {
let path = ide_tools::vue::managed_command(app_data, release);
settings
.tools
.insert(name.into(), ide_core::settings::ToolSettings { path: path.to_string_lossy().into_owned() });
}
}
impl Host {
pub fn open_project(&self, window: &str, root: &Path) -> IdeResult<Arc<Project>> {
let started = std::time::Instant::now();
@@ -241,12 +258,15 @@ impl Host {
let member = ide_workspace::workspace::Workspace::load(&root).ok().flatten().and_then(|w| {
w.projects.into_iter().filter(|p| server_root.starts_with(p)).max_by_key(|p| p.components().count())
});
let effective = member
let mut effective = member
.as_ref()
.map(|p| SettingsStore::load(&config_dir, Some(p)).effective())
.unwrap_or_else(|| settings.effective());
let window_root = &root;
let root = member.as_ref().unwrap_or(window_root);
if matches!(cfg.name.as_str(), "vue-language-server" | "vtsls" | "typescript-language-server") {
configure_vue_release(&mut effective, root, &data_dir);
}
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
@@ -2834,6 +2854,38 @@ fn notify_transfer(sink: &SharedSink, what: &str, path: &Path, result: IdeResult
});
}
#[cfg(test)]
mod vue_release_tests {
use super::*;
#[test]
fn vue_release_configures_the_managed_command_and_respects_explicit_settings() {
let project = tempfile::tempdir().unwrap();
let root = project.path();
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^2.7.16"}}"#).unwrap();
let app_data = root.join("data");
let mut settings = ide_core::settings::Settings::default();
configure_vue_release(&mut settings, root, &app_data);
let name = ide_tools::vue::SERVER;
assert_eq!(
ide_sdk::apply::tool_command(root, &settings, name),
Some(ide_tools::vue::managed_command(&app_data, "3.0.x")),
);
let mut settings = ide_core::settings::Settings::default();
settings.tool_downloads.vue_language_server_version = "3.1.2".into();
configure_vue_release(&mut settings, root, &app_data);
assert_eq!(
ide_sdk::apply::tool_command(root, &settings, name),
Some(ide_tools::vue::managed_command(&app_data, "3.1.2")),
);
settings.tools.get_mut(name).unwrap().path = "custom-vue".into();
configure_vue_release(&mut settings, root, &app_data);
assert_eq!(ide_sdk::apply::tool_command(root, &settings, name), Some(root.join("custom-vue")));
}
}
#[cfg(test)]
mod maven_linkage_tests {
#[test]
+259 -5
Переглянути файл
@@ -19,6 +19,10 @@ struct Harness {
}
impl Harness {
fn new() -> Self {
Self::for_host(true)
}
fn for_host(local_desktop: bool) -> Self {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
@@ -29,14 +33,15 @@ impl Harness {
std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
let host = Host::new(HostConfig {
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
}));
});
let host = Arc::new(if local_desktop { host.with_local_desktop() } else { host });
host.open_project("main", &root).unwrap();
Self { host, root, tmp, events }
}
@@ -1120,11 +1125,13 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest {
id,
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
} if !handled.contains(id) => Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone())),
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env, target },
} if !handled.contains(id) => {
Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone(), target.clone()))
}
_ => None,
});
let Some((id, name, command, cwd, env)) = request else {
let Some((id, name, command, cwd, env, target)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
@@ -1144,6 +1151,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
extras: Default::default(),
};
config.extras.params.insert(ide_host::mcp::AGENT_PARAM.into(), name);
config.extras.params.insert(ide_host::mcp::TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
config.extras.target = Some(String::new());
out.lock().unwrap().push(config.clone());
let result =
@@ -2516,3 +2524,249 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
.unwrap_err();
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
}
const DEV_CONTAINER_TOOLS: [&str; 5] =
["devcontainer_status", "devcontainer_logs", "devcontainer_up", "devcontainer_exec", "devcontainer_stop"];
fn dev_container_tools(tools: Vec<ide_mcp::Tool>) -> Vec<String> {
let mut names: Vec<String> = tools.into_iter().map(|t| t.name).filter(|n| n.starts_with("devcontainer_")).collect();
names.sort();
names
}
#[tokio::test(flavor = "multi_thread")]
async fn server_hosts_neither_list_nor_dispatch_dev_container_tools() {
let h = Harness::for_host(false);
h.trust().await;
let registry = Registry::new(h.host.clone());
let tools = registry.tools(&h.root).unwrap();
assert!(tools.iter().any(|t| t.name == "run_command"));
assert!(dev_container_tools(tools).is_empty());
assert!(dev_container_tools(registry.tools_without_project()).is_empty());
for name in DEV_CONTAINER_TOOLS {
assert_eq!(h.error(name, json!({})).await, format!("unknown tool: {name}"));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_untrusted_project_lists_only_the_read_only_dev_container_tools() {
let h = Harness::new();
let registry = Registry::new(h.host.clone());
assert!(!h.host.project("main").unwrap().is_trusted());
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), ["devcontainer_logs", "devcontainer_status"]);
// A write tool called all the same is refused before it asks or runs anything.
for tool in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
let refused = h.error(tool, json!({"name": "x", "command": "true"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.", "{tool}");
}
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
h.trust().await;
let mut all = DEV_CONTAINER_TOOLS.map(str::to_owned).to_vec();
all.sort();
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), all);
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_arguments_are_checked_before_docker_is_asked() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
std::fs::write(h.root.join(".devcontainer/devcontainer.json"), "{}").unwrap();
std::fs::write(h.tmp.path().join("devcontainer.json"), "{}").unwrap();
let error = |tool: &'static str, args: Value| {
let h = &h;
async move { h.error(tool, args).await }
};
for tail in [0, -3, 5001] {
let e = error("devcontainer_logs", json!({"tail": tail})).await;
assert_eq!(e, "tail must be between 1 and 5000", "{tail}");
}
assert_eq!(error("devcontainer_logs", json!({"tail": "x"})).await, "tail must be an integer");
// `config` is a devcontainer file of the project.
let outside = h.tmp.path().join("devcontainer.json");
let e = error("devcontainer_status", json!({"config": outside})).await;
assert!(e.contains("outside the project"), "{e}");
let e = error("devcontainer_status", json!({"config": "src/a.txt"})).await;
assert_eq!(e, "config must be a devcontainer.json or .devcontainer.json file");
let e = error("devcontainer_status", json!({"config": ".devcontainer/other/devcontainer.json"})).await;
assert!(e.contains("does not exist") || e.contains("no existing parent"), "{e}");
let e = error("devcontainer_up", json!({"config": "../devcontainer.json"})).await;
assert!(e.contains("outside the project"), "{e}");
for timeout in [0, -1] {
let e = error("devcontainer_up", json!({"timeout": timeout})).await;
assert_eq!(e, "timeout must be positive", "{timeout}");
}
// `noCache` belongs to a rebuild; refused before anything is asked.
let e = error("devcontainer_up", json!({"noCache": true})).await;
assert_eq!(e, "noCache needs rebuild: true");
let e = error("devcontainer_up", json!({"rebuild": true, "timeout": 0})).await;
assert_eq!(e, "timeout must be positive");
// `exec` arguments.
let e = error("devcontainer_exec", json!({"name": "t", "command": " "})).await;
assert_eq!(e, "command must not be empty");
for name in ["1A", "A-B", "", "A B", "A=B"] {
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {name: "1"}})).await;
assert!(e.contains("is not a valid variable name"), "{name}: {e}");
}
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {"A": 1}})).await;
assert_eq!(e, "envs must contain strings");
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": ["A=1"]})).await;
assert_eq!(e, "envs must be an object");
// Without a window it is refused like `run_command`.
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let e = h.call_at(&inventory, "devcontainer_exec", json!({"name": "t", "command": "true"})).await.unwrap_err();
assert!(e.starts_with("devcontainer_exec needs the project open in a window"), "{e}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_configs_cannot_escape_the_project_through_symlinks() {
let h = Harness::new();
h.trust().await;
let outside = h.tmp.path().join("devcontainer.json");
std::fs::write(&outside, "{}").unwrap();
std::fs::create_dir(h.root.join(".devcontainer")).unwrap();
for name in [".devcontainer/devcontainer.json", ".devcontainer.json"] {
let link = h.root.join(name);
std::os::unix::fs::symlink(&outside, &link).unwrap();
for (tool, args) in [
("devcontainer_status", json!({})),
("devcontainer_status", json!({"config": name})),
("devcontainer_up", json!({})),
("devcontainer_exec", json!({"name": "t", "command": "true"})),
] {
let error = h.error(tool, args).await;
assert!(error.contains("path is outside the project"), "{tool} ({name}): {error}");
}
std::fs::remove_file(link).unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_with_only_named_configurations_says_to_pass_one() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer/py")).unwrap();
std::fs::write(h.root.join(".devcontainer/py/devcontainer.json"), "{}").unwrap();
for (tool, args) in [("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.contains("pass `config` with one of .devcontainer/py/devcontainer.json"), "{tool}: {e}");
}
}
/// Runs `docker` with `args`, returning its trimmed output (None when it failed).
fn docker_output(docker: &Path, args: &[&str]) -> Option<String> {
let out = std::process::Command::new(docker).args(args).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
/// Removes the test containers (never any other) when dropped, also after a panic.
struct TestContainers(PathBuf, Vec<String>);
impl Drop for TestContainers {
fn drop(&mut self) {
for name in &self.1 {
assert!(name.starts_with("oi-mcpdc-test-"));
let _ = std::process::Command::new(&self.0).args(["rm", "-f", name]).output();
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_tools_work_on_the_containers_of_the_project_only() {
let ep = ide_docker::DockerEndpoint::Default;
let ready = tokio::task::spawn_blocking(move || {
matches!(ide_docker::availability(&ep), ide_docker::DockerAvailability::Ready { .. })
&& ide_docker::endpoint_is_local(&ide_docker::DockerEndpoint::Default).unwrap_or(false)
})
.await
.unwrap();
let docker = ide_docker::docker_executable();
let Some(docker) = docker.filter(|_| ready) else {
eprintln!("skipped: no local Docker daemon is ready");
return;
};
if docker_output(&docker, &["image", "inspect", "--format", "{{.Id}}", "alpine:latest"]).is_none() {
eprintln!("skipped: the image alpine:latest is not present locally (it is not pulled here)");
return;
}
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
let config = h.root.join(".devcontainer/devcontainer.json");
std::fs::write(
&config,
r#"{ // comment
"image": "alpine:latest", "forwardPorts": [3000, "db:5432"] }"#,
)
.unwrap();
let pid = std::process::id();
let (a, b) = (format!("oi-mcpdc-test-{pid}-a"), format!("oi-mcpdc-test-{pid}-b"));
let _remove = TestContainers(docker.clone(), vec![a.clone(), b.clone()]);
let folder_label = format!("devcontainer.local_folder={}", h.root.display());
let config_label = format!("devcontainer.config_file={}", config.display());
let run = |name: &str, labels: &[&str]| {
let mut args = vec!["run", "-d", "--init", "--name", name];
for label in labels {
args.extend(["--label", label]);
}
args.extend(["alpine:latest", "sleep", "300"]);
docker_output(&docker, &args).unwrap_or_else(|| panic!("cannot start {name}"))
};
let id_a = run(&a, &[&folder_label, &config_label]);
let id_b = run(&b, &[&folder_label]);
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["docker"], "ready", "{status}");
assert_eq!(
(status["dockerLocal"].as_bool(), status["configFile"].as_str()),
(Some(true), Some(".devcontainer/devcontainer.json"))
);
assert_eq!(status["configFiles"], json!([".devcontainer/devcontainer.json"]));
assert_eq!(status["forwardPorts"], json!([3000, "db:5432"]));
let containers = status["containers"].as_array().unwrap();
assert_eq!(containers.len(), 1, "only the labelled container: {status}");
assert_eq!((containers[0]["id"].as_str(), containers[0]["name"].as_str()), (Some(id_a.as_str()), Some(a.as_str())));
assert_eq!((containers[0]["state"].as_str(), containers[0]["primary"].as_bool()), (Some("running"), Some(true)));
let logs = h.json("devcontainer_logs", json!({"tail": 5})).await;
assert_eq!(logs["containerId"], id_a.as_str());
assert!(logs["lines"].is_array());
let foreign = h.error("devcontainer_logs", json!({"containerId": id_b})).await;
assert_eq!(foreign, format!("container {id_b} does not belong to this project's dev container"));
let short = h.error("devcontainer_logs", json!({"containerId": &id_b[..12]})).await;
assert!(short.ends_with("does not belong to this project's dev container"), "{short}");
// Without the CLI the tools that need it say so, wherever the container is.
if status["cliInstalled"] == false {
for (tool, args) in
[("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.starts_with("The Dev Containers CLI is not installed"), "{tool}: {e}");
}
}
// A window open in the container keeps it from being stopped.
let held = h.host.dev_containers_attached.hold(&id_a);
let refused = h.error("devcontainer_stop", json!({})).await;
assert!(refused.contains("is open in a window"), "{refused}");
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("true"));
drop(held);
let stopped = h.json("devcontainer_stop", json!({})).await;
assert_eq!(stopped["stopped"], json!([id_a]));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("false"));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &b]).as_deref(), Some("true"));
assert_eq!(h.json("devcontainer_stop", json!({})).await["stopped"], json!([]), "nothing runs now");
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["containers"][0]["state"], "exited", "{status}");
}
+30 -2
Переглянути файл
@@ -95,6 +95,9 @@ const DART_SERVER: &str = "dart";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
/// An explicit Find Usages in Java (#7376): searching a large workspace's sources takes jdtls
/// longer than other requests, and the user cancels it from the Find tool window instead.
const USAGES_TIMEOUT: Duration = Duration::from_secs(300);
fn did_change_content(
sync: SyncKind,
@@ -376,12 +379,19 @@ fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}
const TIMED_OUT: &str = " timed out";
/// Whether `e` is a request that got no answer in time (see `rpc_err`).
fn is_timeout(e: &IdeError) -> bool {
e.kind == ErrorKind::Protocol && e.message.ends_with(TIMED_OUT)
}
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
match e {
RpcError::Cancelled => IdeError::cancelled(),
RpcError::Server { code, .. } if code == ide_jsonrpc::codes::CONTENT_MODIFIED => IdeError::cancelled(),
RpcError::Closed => IdeError::unavailable(format!("{server} is not running")),
RpcError::Timeout => IdeError::new(ErrorKind::Protocol, format!("{server}: {method} timed out")),
RpcError::Timeout => IdeError::new(ErrorKind::Protocol, format!("{server}: {method}{TIMED_OUT}")),
RpcError::Server { message, .. } => IdeError::new(ErrorKind::Protocol, format!("{server}: {message}")),
RpcError::Protocol(m) => IdeError::new(ErrorKind::Protocol, format!("{server}: {m}")),
}
@@ -2344,7 +2354,7 @@ impl LspManager {
"workspace/executeCommand",
json!({ "command": "openidea.java.usages", "arguments": arguments }),
Some(cancel),
LONG_TIMEOUT,
if project_wide { USAGES_TIMEOUT } else { LONG_TIMEOUT },
)
.await;
if let Err(e) = &result {
@@ -2456,6 +2466,11 @@ impl LspManager {
{
return Err(IdeError::cancelled());
}
// The standard references search the same sources and the dependencies too:
// after a search that ran out of time, it would only make the wait longer.
if is_timeout(&e) {
return Err(e);
}
if !self.java_usages_warned.swap(true, Ordering::Relaxed) {
tracing::warn!("Java usages extension failed; using standard references: {e}");
}
@@ -4904,6 +4919,19 @@ mod send_check {
}
}
#[cfg(test)]
mod timeout_tests {
use super::*;
#[test]
fn a_request_without_an_answer_in_time_is_a_timeout() {
assert!(is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Timeout)));
assert!(!is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Protocol("bad".into()))));
assert!(!is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Cancelled)));
assert!(!is_timeout(&IdeError::new(ErrorKind::Protocol, "jdtls: NoSuchMethodError")));
}
}
#[cfg(test)]
mod code_action_tests {
use super::source_actions_only;
+55 -1
Переглянути файл
@@ -905,7 +905,9 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node {
let mut start = 0;
while first < parts.len() {
let part = parts[first].string().expect("validated source text");
if !text[start..].starts_with(part) {
// Only whole lines are kept: a part without its newline (typing at the end of a line, or a
// source saved one character per element) is rewritten with the rest of its line.
if !part.ends_with('\n') || !text[start..].starts_with(part) {
break;
}
start += part.len();
@@ -918,6 +920,11 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node {
if end - start < part.len() || !text[start..end].ends_with(part) {
break;
}
// ...and only from the start of a line.
let at = end - part.len();
if at > 0 && !text[..at].ends_with('\n') {
break;
}
end -= part.len();
last -= 1;
}
@@ -993,3 +1000,50 @@ fn validate_output_node(node: &Node) -> IdeResult<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn typing_characters_preserves_source_lines() {
let mut source = Node::new(Value::Array(Vec::new()));
for text in ["a", "ab", "abc"] {
source = rewritten_source(Some(&source), text.to_string());
}
let mut actual = String::new();
source.write(&mut actual);
assert_eq!(actual, r#"["abc"]"#);
}
fn written(node: &Node) -> String {
let mut out = String::new();
node.write(&mut out);
out
}
#[test]
fn typing_keeps_one_element_per_line_and_the_untouched_lines() {
let mut source = Node::new(Value::Array(Vec::new()));
let code = "if True:\n print('hello')\nx = 1";
for end in 1..=code.len() {
source = rewritten_source(Some(&source), code[..end].to_string());
}
assert_eq!(written(&source), r#"["if True:\n"," print('hello')\n","x = 1"]"#);
// Typing at the end of the middle line leaves the other lines' elements as they were.
let edited = "if True:\n print('hello!')\nx = 1";
let source = rewritten_source(Some(&source), edited.to_string());
assert_eq!(written(&source), r#"["if True:\n"," print('hello!')\n","x = 1"]"#);
}
#[test]
fn a_source_saved_one_character_per_element_is_joined_into_lines_where_it_is_edited() {
let parts = "ab\ncd".chars().map(|c| Value::String(c.to_string())).collect();
let source = rewritten_source(Some(&Node::new(Value::Array(parts))), "ab\ncde".to_string());
assert_eq!(written(&source), r#"["ab\n","cde"]"#);
}
}
+5
Переглянути файл
@@ -20,6 +20,11 @@ impl Exec {
Self { docker, up, bin }
}
/// The id of the container.
pub fn container(&self) -> &str {
&self.up.container
}
/// The arguments of `docker` for one connection from the container to `<host>:<port>`.
fn connect_args(&self, host: &str, port: u16) -> Vec<String> {
let port = port.to_string();
+284 -2
Переглянути файл
@@ -1,7 +1,84 @@
//! Validated results of the Dev Containers CLI.
//! The Dev Containers CLI: `devcontainer up` and its validated result, and how a folder and
//! configuration are named to the CLI and to the labels it puts on the container.
use ide_core::{IdeError, IdeResult};
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::Deserialize;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
/// Building an image (and its features) can take a while on a first open.
pub const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
/// The label of a container naming the folder `devcontainer up` was given.
pub const FOLDER_LABEL: &str = "devcontainer.local_folder";
/// The label of a container naming the configuration file it was started from.
pub const CONFIG_LABEL: &str = "devcontainer.config_file";
/// The folder and configuration file the CLI is pointed at. The same values name the container
/// in its labels, which is how the project's container is found again: the folder as opened
/// (not canonicalised) and the configuration as `folder.join(config)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
folder: PathBuf,
config: Option<PathBuf>,
}
impl Target {
/// `config` is the configuration file itself; `None` leaves it to the CLI (the default one).
pub fn new(folder: impl Into<PathBuf>, config: Option<PathBuf>) -> Self {
// Native separators throughout, as the CLI's `path.resolve` writes the label on Windows.
Self { folder: folder.into(), config: config.map(|c| c.components().collect()) }
}
/// `config` relative to `folder`; blank means the default one.
pub fn relative(folder: &Path, config: &str) -> Self {
let config = config.trim();
Self::new(folder, (!config.is_empty()).then(|| folder.join(config)))
}
pub fn folder(&self) -> &Path {
&self.folder
}
pub fn config(&self) -> Option<&Path> {
self.config.as_deref()
}
/// `--workspace-folder <folder>` and, with a configuration, `--config <file>`.
pub fn args(&self) -> Vec<OsString> {
let mut args = vec![OsString::from("--workspace-folder"), self.folder.clone().into_os_string()];
if let Some(config) = &self.config {
args.extend([OsString::from("--config"), config.clone().into_os_string()]);
}
args
}
/// The value of [`FOLDER_LABEL`] the CLI puts on this folder's container.
pub fn folder_label(&self) -> String {
label_value(&self.folder.to_string_lossy())
}
/// The value of [`CONFIG_LABEL`], when the configuration is known.
pub fn config_label(&self) -> Option<String> {
self.config.as_deref().map(|c| label_value(&c.to_string_lossy()))
}
}
/// A path as the CLI writes it into a label: on Windows its drive letter is lower case
/// (`c:\work\app`), so a label is compared that way.
pub fn label_value(path: &str) -> String {
let mut chars = path.chars();
match (chars.next(), chars.next()) {
(Some(drive), Some(':')) if drive.is_ascii_alphabetic() => {
format!("{}{}", drive.to_ascii_lowercase(), &path[1..])
}
_ => path.to_owned(),
}
}
/// The container `devcontainer up` started, as it reported it.
#[derive(Debug, PartialEq, Eq)]
@@ -60,9 +137,103 @@ pub fn parse_up(stdout: &str) -> IdeResult<Up> {
}
}
/// The folders whose `devcontainer up` the MCP tools run now.
static BUSY: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Holds `folder` as having an `up` or rebuild of the MCP tools running; released on drop.
#[derive(Debug)]
pub struct Busy(PathBuf);
impl Busy {
/// Takes `folder`, or refuses when another start of it runs. Only the MCP tools take it:
/// Reopen in Container does not, as a retry must not be refused for the length of a build.
pub fn take(folder: &Path) -> IdeResult<Self> {
let mut busy = BUSY.lock();
if busy.iter().any(|f| f == folder) {
return Err(IdeError::unavailable(format!(
"devcontainer up is already running for {}; wait for it to finish",
folder.display()
)));
}
busy.push(folder.to_owned());
Ok(Self(folder.to_owned()))
}
}
impl Drop for Busy {
fn drop(&mut self) {
BUSY.lock().retain(|f| *f != self.0);
}
}
/// `devcontainer up` for `target`, with `extra_args` after the standard ones. Blocks until the
/// CLI exits, `timeout` passes or `cancel` fires (the CLI and what it started are then
/// stopped); its log lines go to `on_line`.
pub fn up(
cli: &Path,
docker: &Path,
target: &Target,
extra_args: &[&str],
timeout: Duration,
on_line: &mut dyn FnMut(&str),
cancel: &CancellationToken,
) -> IdeResult<Up> {
const TOOL: CliTool = CliTool::new("devcontainer", Decoding::Utf8Lossy);
let timed_out = || IdeError::unavailable("devcontainer up did not finish in time");
if timeout.is_zero() {
return Err(timed_out());
}
let mut cmd = Command::new(cli);
cmd.arg("up").args(target.args()).arg("--docker-path").arg(docker).args(extra_args);
// Cancelled by `cancel` and, at the deadline, by the watch below: also while the CLI has
// closed its pipes and runs on.
let stop = cancel.child_token();
let mut lines = TOOL.lines(cmd, &stop, CarriageReturn::Dropped)?;
let (finished, deadline) = std::sync::mpsc::channel::<()>();
let watch = stop.clone();
std::thread::spawn(move || {
// Dropping `finished` (the function returned) ends the watch.
if deadline.recv_timeout(timeout) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) {
watch.cancel();
}
});
let _finished = finished;
let (mut stdout, mut log) = (String::new(), Vec::new());
loop {
match lines.poll(&stop, Duration::from_millis(50)) {
Ok(Poll::Line(Stream::Stdout, line)) => {
stdout.push_str(&line);
stdout.push('\n');
}
Ok(Poll::Line(Stream::Stderr, line)) => {
on_line(&line);
if !line.trim().is_empty() {
keep_stderr_line(&mut log, line);
}
}
Ok(Poll::Closed | Poll::Timeout) => {}
Ok(Poll::Finished) => break,
Err(e) if cancel.is_cancelled() => return Err(e),
Err(_) => return Err(timed_out()),
}
}
let status = lines.finish(&stop).map_err(|e| if cancel.is_cancelled() { e } else { timed_out() })?;
let result = parse_up(&stdout);
if status.success() {
return result;
}
let error = result.err().unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}")));
Err(match log.join("\n") {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::time::Instant;
const ID: &str = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
@@ -99,4 +270,115 @@ mod tests {
}
assert!(is_user("1000:1000") && is_user("node") && is_user("dev.user"));
}
#[test]
fn the_folder_and_configuration_name_the_cli_arguments_and_the_labels() {
let target = Target::relative(Path::new("/work/my app"), " .devcontainer/py/devcontainer.json ");
let config: PathBuf = Path::new("/work/my app/.devcontainer/py/devcontainer.json").components().collect();
let expected: Vec<OsString> =
vec!["--workspace-folder".into(), "/work/my app".into(), "--config".into(), config.clone().into()];
assert_eq!(target.args(), expected);
assert_eq!(target.folder_label(), "/work/my app");
assert_eq!(target.config_label().unwrap(), config.to_string_lossy());
let default = Target::relative(Path::new("/work/app"), "");
assert_eq!(default.args(), ["--workspace-folder", "/work/app"]);
assert_eq!(default.config_label(), None);
}
#[cfg(windows)]
#[test]
fn a_windows_configuration_label_has_native_separators() {
let target = Target::relative(Path::new(r"C:\work\app"), ".devcontainer/py/devcontainer.json");
assert_eq!(target.config_label().unwrap(), r"c:\work\app\.devcontainer\py\devcontainer.json");
}
#[test]
fn a_windows_drive_letter_is_lower_case_in_a_label() {
assert_eq!(label_value(r"C:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value(r"c:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value("/Users/me/C:/app"), "/Users/me/C:/app");
assert_eq!(label_value("C"), "C");
assert_eq!(label_value(""), "");
}
#[cfg(unix)]
fn fake_cli(dir: &Path, script: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let cli = dir.join("devcontainer");
std::fs::write(&cli, format!("#!/bin/sh\n{script}\n")).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
cli
}
#[test]
fn a_folder_is_held_by_one_start_at_a_time() {
let folder = Path::new("/work/held");
let first = Busy::take(folder).unwrap();
assert!(Busy::take(folder).unwrap_err().message.contains("already running"));
let other = Busy::take(Path::new("/work/other")).unwrap();
drop(first);
drop(Busy::take(folder).unwrap());
drop(other);
}
#[cfg(unix)]
#[test]
fn up_stops_the_cli_on_cancel() {
let dir = tempfile::tempdir().unwrap();
let started = dir.path().join("started");
let cli = fake_cli(dir.path(), &format!("touch '{}'\nsleep 30 & wait", started.display()));
let target = Target::new(dir.path().join("app"), None);
let cancel = CancellationToken::new();
let slow = {
let (cancel, target) = (cancel.clone(), target.clone());
std::thread::spawn(move || up(&cli, Path::new("docker"), &target, &[], UP_TIMEOUT, &mut |_| {}, &cancel))
};
while !started.exists() {
std::thread::sleep(Duration::from_millis(10));
}
cancel.cancel();
assert_eq!(slow.join().unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_closed_its_pipes_and_runs_on() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "exec 1>&- 2>&-\nsleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(300),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_outlives_the_timeout() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "sleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(200),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
}
+2 -1
Переглянути файл
@@ -147,8 +147,9 @@ mod tests {
let root = tmp.path();
assert_eq!(xcode_build_root(root), None);
let dd = root.join("DerivedData/App-abc");
// Built as JSON, not by formatting: a Windows path's backslashes need escaping.
let config =
|kind: &str| format!(r#"{{"name":"xcode build server","kind":"{kind}","build_root":"{}"}}"#, dd.display());
|kind: &str| serde_json::json!({"name": "xcode build server", "kind": kind, "build_root": dd}).to_string();
std::fs::write(root.join("buildServer.json"), config("manual")).unwrap();
assert_eq!(xcode_build_root(root), None, "a hand-written .compile config");
std::fs::write(root.join("buildServer.json"), r#"{"name":"sourcekit-xcode-bsp","argv":["x"]}"#).unwrap();
+2 -1
Переглянути файл
@@ -430,7 +430,8 @@ fn apple_app_trees() {
);
let app = std::fs::read_to_string(dir.join("My App/My_AppApp.swift")).unwrap();
assert!(app.contains("struct My_AppApp: App"), "{app}");
let test = std::fs::read_to_string(dir.join("My AppTests/My AppTests.swift")).unwrap();
// A Windows checkout gives the generator's templates CRLF line endings.
let test = std::fs::read_to_string(dir.join("My AppTests/My AppTests.swift")).unwrap().replace("\r\n", "\n");
assert!(test.starts_with("import Testing\n@testable import My_App\n"), "{test}");
let pbxproj = std::fs::read_to_string(dir.join("My App.xcodeproj/project.pbxproj")).unwrap();
assert!(pbxproj.contains("PRODUCT_BUNDLE_IDENTIFIER = \"com.acme.My-App\";"), "{pbxproj}");
+49 -8
Переглянути файл
@@ -29,6 +29,7 @@ mod process;
pub mod registry;
pub mod server;
pub mod sources;
pub mod vue;
use ide_core::error::ErrorKind;
use ide_core::settings::ToolDownloadSettings;
@@ -502,6 +503,7 @@ pub struct Tools {
/// The project the tools are used for: tools that install into "the active runtime" (gems) run here,
/// so a version manager picks the project's Ruby.
work_dir: Option<PathBuf>,
vue_version: Option<String>,
/// Tools › Download sources: the mirror prefix and its fallback behaviour.
downloads: ToolDownloadSettings,
}
@@ -528,6 +530,7 @@ impl Tools {
runtime_env: BTreeMap::new(),
version_timeout: Duration::from_secs(4),
work_dir: None,
vue_version: None,
downloads: ToolDownloadSettings::default(),
}
}
@@ -778,9 +781,29 @@ impl Tools {
}
}
fn vue_release(&self) -> &str {
vue::release(self.work_dir.as_deref(), &self.downloads.vue_language_server_version)
}
fn for_tool(&self, spec: &ToolSpec) -> Self {
let mut tools = self.for_method(spec.method);
if spec.name == vue::SERVER && self.vue_version.is_none() {
let release = self.vue_release();
if release != "latest" {
tools.root = vue::managed_prefix(&tools.root, release);
tools.vue_version = Some(release.to_owned());
}
}
tools
}
fn install_key(&self, name: &str) -> String {
self.vue_version.as_ref().map_or_else(|| name.to_owned(), |release| format!("{name}@{release}"))
}
fn info_for(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).info_for_runtime(name, usage),
Some(spec) => self.for_tool(spec).info_for_runtime(name, usage),
None => self.info_for_runtime(name, usage),
}
}
@@ -896,6 +919,9 @@ impl Tools {
.or_else(|| self.query_version(spec, &path));
return (ToolStatus::Installed, Some(path), version);
}
if self.vue_version.is_some() {
return (ToolStatus::Missing, None, None);
}
match self.install_method(spec) {
Method::Rustup { .. } => {
let Some(path) = self.which(main) else { return (ToolStatus::Missing, None, None) };
@@ -1004,7 +1030,7 @@ impl Tools {
emit: Emit,
) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).install_for_runtime(name, langs, cancel, emit),
Some(spec) => self.for_tool(spec).install_for_runtime(name, langs, cancel, emit),
None => self.install_for_runtime(name, langs, cancel, emit),
}
}
@@ -1026,7 +1052,8 @@ impl Tools {
if let Some(reason) = self.unavailable_reason(spec) {
return Err(IdeError::unavailable(reason));
}
let slot = match install_slot(name, cancel) {
let install_key = self.install_key(name);
let slot = match install_slot(&install_key, cancel) {
Ok(slot) => slot,
Err(slot) => return join_install(&slot, cancel, emit),
};
@@ -1053,7 +1080,16 @@ impl Tools {
c.args(["component", "add", component]);
run_streamed(c, cancel, emit)?;
}
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
Method::Npm { packages } => {
if let Some(release) = &self.vue_version {
let primary = format!("{}@{release}", vue::PACKAGE);
let mut packages = packages.to_vec();
packages[0] = &primary;
self.install_npm(&packages, cancel, emit)?;
} else {
self.install_npm(packages, cancel, emit)?;
}
}
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
@@ -1081,7 +1117,7 @@ impl Tools {
});
Ok(info)
})();
release_install_slot(name, &slot);
release_install_slot(&install_key, &slot);
slot.finish(result.clone());
result
}
@@ -1720,6 +1756,10 @@ impl Tools {
let installed: Vec<(&ToolSpec, Method, String)> = TOOLS
.iter()
.filter_map(|spec| {
// Alternate Vue releases are version constraints, like pinned npm packages.
if spec.name == vue::SERVER && self.vue_release() != "latest" {
return None;
}
let method = self.install_method(spec);
Some((spec, method, self.installed_version(spec, method)?))
})
@@ -1801,7 +1841,7 @@ impl Tools {
/// Removes a tool the IDE installed.
pub fn uninstall(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).uninstall_for_runtime(name, langs),
Some(spec) => self.for_tool(spec).uninstall_for_runtime(name, langs),
None => self.uninstall_for_runtime(name, langs),
}
}
@@ -1809,10 +1849,11 @@ impl Tools {
fn uninstall_for_runtime(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| IdeError::not_found(format!("unknown tool `{name}`")))?;
// Uninstalling mid-install would tear down the directory under the running installer.
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(name)) {
let install_key = self.install_key(name);
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(&install_key)) {
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{name} is already being installed")));
}
let _guard = InstallGuard::acquire(&format!("uninstall-{name}"))?;
let _guard = InstallGuard::acquire(&format!("uninstall-{install_key}"))?;
let cancel = CancellationToken::new();
let quiet = |_: InstallEvent| {};
match self.install_method(spec) {
+46
Переглянути файл
@@ -642,6 +642,52 @@ exit 1"#,
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
}
#[cfg(unix)]
#[test]
fn vue_installs_the_selected_release_without_replacing_other_projects() {
let env = Env::new();
env.script(&env.sys, "node", "exit 0");
env.script(
&env.sys,
"npm",
r#"prefix=""; version=""
for arg in "$@"; do
[ "$previous" = "--prefix" ] && prefix="$arg"
case "$arg" in
@vue/language-server@3.0.x) version=3.0.8;;
@vue/language-server@3.1.2) version=3.1.2;;
@vue/language-server@latest) version=3.2.0;;
esac
previous="$arg"
done
[ -n "$version" ] || exit 1
/bin/mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@vue/language-server"
printf '{"version":"%s"}\n' "$version" > "$prefix/node_modules/@vue/language-server/package.json"
printf '#!/bin/sh\necho %s\n' "$version" > "$prefix/node_modules/.bin/vue-language-server"
/bin/chmod +x "$prefix/node_modules/.bin/vue-language-server""#,
);
let project = env._tmp.path().join("vue-two");
fs::create_dir(&project).unwrap();
fs::write(project.join("package.json"), r#"{"dependencies":{"vue":"^2.7.16"}}"#).unwrap();
let tools = env.tools();
let legacy = tools.clone().with_work_dir(Some(project));
let manual = legacy
.clone()
.with_downloads(ToolDownloadSettings { vue_language_server_version: "3.1.2".into(), ..Default::default() });
let install = |tools: &Tools| tools.install(vue::SERVER, &langs(), &CancellationToken::new(), &|_| {}).unwrap();
let stable_info = install(&tools);
let legacy_info = install(&legacy);
let manual_info = install(&manual);
assert_eq!(stable_info.version.as_deref(), Some("3.2.0"));
assert_eq!(legacy_info.version.as_deref(), Some("3.0.8"));
assert_eq!(manual_info.version.as_deref(), Some("3.1.2"));
let path = |release| vue::managed_command(env.root.parent().unwrap(), release);
assert_eq!(legacy_info.path.as_deref(), Some(path("3.0.x").as_path()));
assert_eq!(manual_info.path.as_deref(), Some(path("3.1.2").as_path()));
assert_eq!(tools.info_for(vue::SERVER, None).unwrap().version.as_deref(), Some("3.2.0"));
assert_eq!(legacy.info_for(vue::SERVER, None).unwrap().version.as_deref(), Some("3.0.8"));
}
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
/// Uninstalling one keeps the TypeScript another installed server still uses.
+110
Переглянути файл
@@ -0,0 +1,110 @@
//! Select and locate an isolated managed Vue language-server version.
use std::path::{Path, PathBuf};
pub const SERVER: &str = "vue-language-server";
pub(crate) const PACKAGE: &str = "@vue/language-server";
const LEGACY: &str = "3.0.x";
/// A chosen version wins over project detection. Invalid values are never given to npm.
pub fn release<'a>(project: Option<&Path>, preferred: &'a str) -> &'a str {
let preferred = preferred.trim();
if preferred == "latest" || preferred == LEGACY || exact_version(preferred) {
return preferred;
}
if project.and_then(uses_vue_two) == Some(true) { LEGACY } else { "latest" }
}
fn exact_version(value: &str) -> bool {
let (release, build) = value.split_once('+').map_or((value, None), |(a, b)| (a, Some(b)));
let (core, pre) = release.split_once('-').map_or((release, None), |(a, b)| (a, Some(b)));
let valid_suffix = |suffix: &str| {
suffix.split('.').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
};
core.split('.').count() == 3
&& core.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
&& pre.is_none_or(valid_suffix)
&& build.is_none_or(valid_suffix)
}
fn read_manifest(path: &Path) -> Option<serde_json::Value> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
fn uses_vue_two(project: &Path) -> Option<bool> {
let manifest = read_manifest(&project.join("package.json"))?;
let dependency = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]
.iter()
.find_map(|group| manifest[*group]["vue"].as_str())?;
let dependency = dependency.trim().strip_prefix("npm:vue@").unwrap_or(dependency.trim());
if !matches!(dependency, "" | "*" | "latest" | "workspace:*" | "workspace:^" | "workspace:~")
&& !["file:", "link:", "git:", "https:", "npm:"].iter().any(|&prefix| dependency.starts_with(prefix))
{
return Some(dependency.strip_prefix("workspace:").unwrap_or(dependency).split("||").all(vue_two_range));
}
// A package-manager alias or workspace range may only identify its version once installed.
let installed = read_manifest(&project.join("node_modules/vue/package.json"));
Some(installed.as_ref().and_then(|p| p["version"].as_str()).is_some_and(vue_two_range))
}
fn vue_two_range(value: &str) -> bool {
let value = value.trim();
let major_two = |version: &str| {
let version = version.trim().trim_start_matches(['=', '^', '~', 'v']).trim();
version == "2" || version.starts_with("2.")
};
if let Some((_, limit)) = value.split_once('<') {
let limit = limit.trim();
if let Some(inclusive) = limit.strip_prefix('=') {
if inclusive.split_whitespace().next().is_some_and(major_two) {
return true;
}
} else if matches!(limit.split_whitespace().next(), Some("3" | "3.0" | "3.0.0" | "3.0.0-0")) {
return true;
}
}
if let Some((minimum, maximum)) = value.split_once(" - ") {
return major_two(minimum) && major_two(maximum);
}
major_two(value)
}
/// Extra releases stay off the process PATH and keep their own paired TypeScript package.
pub(crate) fn managed_prefix(tools: &Path, release: &str) -> PathBuf {
tools.join("vue-language-server-versions").join(release)
}
pub fn managed_command(data: &Path, release: &str) -> PathBuf {
managed_prefix(&crate::tools_dir(data), release).join("node_modules/.bin").join(if cfg!(windows) {
"vue-language-server.cmd"
} else {
SERVER
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_release_and_overrides() {
let project = tempfile::tempdir().unwrap();
let root = project.path();
for (version, expected) in [
("^2.7.16", LEGACY),
(">=2.6 <3", LEGACY),
("<=2.7.x", LEGACY),
("~2", LEGACY),
("^3.4.0", "latest"),
("^2.7.16 || ^3.4.0", "latest"),
] {
std::fs::write(root.join("package.json"), serde_json::json!({"dependencies":{"vue":version}}).to_string())
.unwrap();
assert_eq!(release(Some(root), ""), expected);
assert_eq!(release(Some(root), "3.0.6"), "3.0.6");
assert_eq!(release(Some(root), "latest"), "latest");
assert_eq!(release(Some(root), "../unsafe"), expected);
}
assert_eq!(release(None, LEGACY), LEGACY);
}
}
+11 -4
Переглянути файл
@@ -3710,11 +3710,18 @@ fn blocked_restore_keeps_the_deletion_record_for_the_next_attempt() {
assert!(!fx.exists(".git/openidea-saved-deletions"));
}
/// A folder and file name whose 700 paths overflow one command line (32,000 chars on Windows,
/// 120,000 elsewhere), while each absolute path stays within Windows' 260-char `MAX_PATH`,
/// which Git for Windows enforces without `core.longpaths`.
fn overlong_names() -> (String, String) {
if cfg!(windows) { ("f".repeat(40), "n".repeat(60)) } else { ("f".repeat(100), "n".repeat(110)) }
}
#[test]
fn pull_keeps_more_deleted_new_files_than_one_command_line_holds_deleted() {
let (fx, bare) = Fixture::with_origin();
let folder = "f".repeat(100);
let paths: Vec<String> = (0..700).map(|i| format!("{folder}/{i:04}-{}.txt", "n".repeat(110))).collect();
let (folder, name) = overlong_names();
let paths: Vec<String> = (0..700).map(|i| format!("{folder}/{i:04}-{name}.txt")).collect();
for path in &paths {
fx.write(path, "new\n");
}
@@ -3763,8 +3770,8 @@ fn deleting_more_added_files_than_one_command_line_holds_drops_them_all() {
let fx = Fixture::new();
fx.write("base.txt", "base\n");
fx.commit_all("base");
let folder = "f".repeat(100);
let paths: Vec<PathBuf> = (0..700).map(|i| fx.path(&format!("{folder}/{i:04}-{}.txt", "n".repeat(110)))).collect();
let (folder, name) = overlong_names();
let paths: Vec<PathBuf> = (0..700).map(|i| fx.path(&format!("{folder}/{i:04}-{name}.txt"))).collect();
for path in &paths {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "new\n").unwrap();
+22 -3
Переглянути файл
@@ -135,6 +135,25 @@ As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print
Plugins can add more tools; they appear in the same list. A plugin tool marked as destructive asks for confirmation the same way.
## Dev containers
Five tools work on the project's [dev container](/en/guide/remote/containers) from the local desktop. `devcontainer_status` and `devcontainer_logs` only read Docker's state and are available for any local project. `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` need a trusted project and ask first, unless brave mode is on.
- `devcontainer_status` lists the project's `devcontainer.json` files and its containers with their state, image and ports, and says whether Docker and the Dev Containers CLI are ready.
- `devcontainer_logs` returns the last lines of a container's log (200 by default, at most 5000).
- `devcontainer_up` starts the container, building it if needed. With `rebuild: true` it removes the container and builds it again; `noCache` (only with `rebuild`) skips the build cache. It waits up to `timeout` milliseconds (30 minutes by default, and more than 0); the Dev Containers CLI is stopped when it passes.
- `devcontainer_exec` runs a command in the container, with the user and environment a terminal in the container has. It runs in a tab of the Run tool window like `run_command`, takes the same `name`, `timeout`, `pattern`, `maxLinesCount` and `truncateMode` arguments, plus `envs` and `config`, and is followed up with `wait_for_run`, `read_run_output` and `stop_run`. It needs a window.
- `devcontainer_stop` stops the container and the other containers of its Compose project. Nothing is removed.
**Which container.** The tools act on the container the Dev Containers CLI labels for the project folder and its `devcontainer.json`. `config` picks another `devcontainer.json` inside the project. For a Compose setup, `devcontainer_logs` and `devcontainer_stop` also cover the other containers of the same Compose project. Any other container is refused, including one named by `containerId`.
**Requirements.** The tools need Docker with a daemon on this computer and the Dev Containers CLI, which you install in **Settings › Languages & Frameworks › Language Servers**. Without them, `devcontainer_status` still answers and says what is missing; the other tools fail with that reason.
- `devcontainer_up` with `rebuild` and `devcontainer_stop` refuse a container that a window is opened in.
- A Run tab rerun uses the original `devcontainer_exec` container ID. To run the command in a replacement container, call `devcontainer_exec` again.
- Stopping the `devcontainer_exec` tab ends the CLI. A process it started in the container may keep running there, because Docker does not stop it when the client goes away.
- Background projects can use every dev container tool except `devcontainer_exec`.
## Background projects
By default the server answers only for projects open in a window. **Serve without a window** lets it also answer for a folder that has no window: the first tool call for a path inside it opens the project, and OpenIDEA unloads it again after it has been idle for a while. The setting is under **Background projects** on **Settings › Agents › IDE MCP Server**. It is off by default.
@@ -170,7 +189,7 @@ What trust decides: a trusted project works as one open in a window, with its la
A background project has no window, so some tools differ:
- `run_command`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `run_command`, `devcontainer_exec`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `get_file_problems` and `get_project_problems` report what a window shows. In a background project they answer with an error that points to `check_files`.
- `get_current_file` and `get_all_open_file_paths` also describe a window. In a background project they answer with an error that says the project needs a window.
- `execute_run_configuration`, `build_project`, `http_run_request` and destructive plugin tools ask in the project window you used last. The dialog has a line `Background project <folder name>` with the full path under it, and requests queue there. The dialog does not take keyboard focus: answer it with a click, or click into it first and then use the keys. If that window closes or loses trust, the request moves to another open project window. With no project window open, the call fails with "no project window is available". Brave mode runs these tools without asking, with or without a window.
@@ -178,13 +197,13 @@ A background project has no window, so some tools differ:
## Safety
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` ask in the project window you used last, and the dialog names the project.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command`, `http_run_request`, `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` and `devcontainer_exec` ask in the project window you used last, and the dialog names the project.
- Tools that write refuse paths outside the project.
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
## Remote development
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings.
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings. The [dev container tools](#dev-containers) run on the desktop for the local folder; a window opened in the container is a remote window, and its MCP server has no access to the desktop's Docker.
## Limits
+22 -3
Переглянути файл
@@ -134,6 +134,25 @@ stdio 配置大致如下(路径以你机器上的为准):
插件可以添加更多工具,它们会出现在同一个列表中。标记为破坏性操作的插件工具同样会先请求确认。
## 开发容器
五个工具在本地桌面端操作项目的[开发容器](/zh/guide/remote/containers)。`devcontainer_status` 和 `devcontainer_logs` 只读取 Docker 的状态,在所有本地项目中都可用。`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 需要项目已被信任,并且会先询问,勇敢模式下除外。
- `devcontainer_status` 列出项目的 `devcontainer.json` 文件和容器(含状态、镜像和端口),并说明 Docker 和 Dev Containers CLI 是否就绪。
- `devcontainer_logs` 返回容器日志的最后若干行(默认 200 行,最多 5000 行)。
- `devcontainer_up` 启动容器,需要时先构建。`rebuild: true` 会删除容器并重新构建;`noCache`(仅与 `rebuild` 一起使用)跳过构建缓存。它最多等待 `timeout` 毫秒(默认 30 分钟,且必须大于 0),超时后会停止 Dev Containers CLI。
- `devcontainer_exec` 在容器中执行命令,使用与容器内终端相同的用户和环境。它和 `run_command` 一样在运行工具窗口的标签页中运行,接受相同的 `name`、`timeout`、`pattern`、`maxLinesCount` 和 `truncateMode` 参数,另有 `envs` 和 `config`,之后用 `wait_for_run`、`read_run_output` 和 `stop_run` 跟进。此工具需要窗口。
- `devcontainer_stop` 停止容器,以及同一 Compose 项目中的其他容器。不会删除任何容器。
**操作哪个容器。** 这些工具操作 Dev Containers CLI 为项目文件夹及其 `devcontainer.json` 打上标签的那个容器。`config` 可以指定项目内的另一个 `devcontainer.json`。对于 Compose 配置,`devcontainer_logs` 和 `devcontainer_stop` 还涵盖同一 Compose 项目中的其他容器。其他任何容器都会被拒绝,包括用 `containerId` 指定的。
**前提条件。** 这些工具需要本机上有守护进程的 Docker,以及 Dev Containers CLI(在 **设置 › 语言和框架 › 语言服务器** 中安装)。缺少它们时,`devcontainer_status` 仍会返回结果并说明缺什么;其他工具会失败并给出原因。
- 带 `rebuild` 的 `devcontainer_up` 和 `devcontainer_stop` 会拒绝已有窗口打开的容器。
- 运行标签页重跑时使用 `devcontainer_exec` 原先的容器 ID。要在替换后的容器内运行命令,请再次调用 `devcontainer_exec`。
- 停止 `devcontainer_exec` 的标签页会结束 CLI。它在容器中启动的进程可能继续运行,因为客户端退出后 Docker 不会停止它。
- 后台项目可以使用除 `devcontainer_exec` 之外的所有开发容器工具。
## 后台项目
默认情况下,服务器只为在窗口中打开的项目提供服务。**无窗口时提供服务** 让它也能为没有窗口的文件夹提供服务:第一次针对其中某个路径的工具调用会打开该项目,空闲一段时间后 OpenIDEA 再把它卸载。这项设置在 **设置 › 智能体 › IDE MCP 服务器** 的 **后台项目** 下,默认关闭。
@@ -169,7 +188,7 @@ stdio 配置大致如下(路径以你机器上的为准):
后台项目没有窗口,所以有些工具不同:
- `run_command`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `run_command`、`devcontainer_exec`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `get_file_problems` 和 `get_project_problems` 报告的是窗口中显示的内容。在后台项目中,它们会返回一个错误,指向 `check_files`。
- `get_current_file` 和 `get_all_open_file_paths` 描述的同样是窗口。在后台项目中,它们会返回一个错误,说明该项目需要窗口。
- `execute_run_configuration`、`build_project`、`http_run_request` 和带破坏性标记的插件工具会在你最后使用的项目窗口中询问。对话框中有一行 `后台项目 <文件夹名>`,下面是完整路径,请求在这里排队。对话框不会获得键盘焦点:用鼠标点击它,或先点进对话框再用键盘操作。该窗口关闭或失去信任时,请求会转到另一个打开的项目窗口。没有打开任何项目窗口时,调用会失败,返回 `no project window is available`。勇敢模式下,这些工具无需询问即可运行,有没有窗口都一样。
@@ -177,13 +196,13 @@ stdio 配置大致如下(路径以你机器上的为准):
## 安全
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command`、`http_run_request`、`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 和 `devcontainer_exec` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- 会写入的工具拒绝项目之外的路径。
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
## 远程开发
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。[开发容器工具](#开发容器)在桌面端针对本地文件夹运行;在容器中打开的窗口是远程窗口,它的 MCP 服务器无法访问桌面端的 Docker。
## 限制
+8 -6
Переглянути файл
@@ -442,15 +442,13 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
await page.setViewportSize({ width: 1320, height: 860 });
await installAutomationDesktopHarness(page);
// Open Agents tool window and click the pinned Automations hub row
// Open Agents tool window and click the Automations header button
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.showToolWindow");
});
const hub = page.getByTestId("agents-automations-hub");
await expect(hub).toBeVisible();
await hub.getByRole("button", { name: /Automations/ }).click();
await page.getByRole("button", { name: "Agent Automations" }).click();
const editor = page.getByTestId("automations-editor");
await expect(editor).toBeVisible();
@@ -477,6 +475,7 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("Upcoming runs:");
await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeEnabled();
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByLabel("Stop After Runs (optional)").fill("25");
await dialog.getByRole("button", { name: "Create Automation" }).click();
await expect(dialog).toHaveCount(0);
@@ -516,7 +515,8 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
const exportedMd = await exportDialog.getByLabel("Exported Automation Markdown").inputValue();
await exportDialog.getByRole("button", { name: "Close" }).click();
await editor.getByRole("button", { name: "Import .automation.md" }).click();
await editor.getByRole("button", { name: "Options" }).click();
await page.getByRole("menuitem", { name: "Import .automation.md" }).click();
const importDialog = page.getByRole("dialog", { name: "Import .automation.md" });
await importDialog
.getByLabel("Automation Markdown")
@@ -570,6 +570,7 @@ test("supports SameTask rolling continuity, NeedsInput approval flow, and sideba
dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Rolling PR Labeler");
await dialog.getByLabel("Prompt Instructions").fill("NEEDS_APPROVAL label triaged PRs");
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByRole("button", { name: "Session Continuity" }).click();
await page.getByRole("option", { name: "Reuse rolling session" }).click();
await dialog.getByRole("button", { name: "Create Automation" }).click();
@@ -776,8 +777,9 @@ test("supports Weekly day picker, Local Autonomous warning, ChatOnly workspace,
await dialog.getByRole("button", { name: "Checkout Isolation" }).click();
await page.getByRole("option", { name: "Local checkout" }).click();
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByRole("button", { name: "Unattended Permissions" }).click();
await page.getByRole("option", { name: "Allow all (capped by your interactive approval setting)" }).click();
await page.getByRole("option", { name: /Allow all/ }).click();
await expect(dialog).toContainText(
"Warning: Autonomous mode on a local checkout can modify your working files directly.",
);
+127
Переглянути файл
@@ -0,0 +1,127 @@
import type { AgentPluginCatalog, AgentPluginState } from "../src/bindings";
import { expect, stubDesktop, test } from "./fixtures";
const makePlugin = (name: string, consentRequired: boolean): AgentPluginState => ({
plugin: {
id: name,
name,
displayName: name,
version: "26.1021.31345",
description: "A plugin with a long description explaining what it can do for the agent in this workspace.",
marketplace: "context-engineering-marketplace-with-a-long-name",
source: "claudeUser",
scope: "user",
formats: ["claude", "codex", "copilot"],
rootPath: "/Users/dev/.claude/plugins/cache/context-engineering-marketplace/agent-plugin",
defaultEnabled: false,
approxTokens: 2550,
capabilities: {
skillCount: 17,
mcpCount: 1,
ruleCount: 2,
subagentCount: 3,
commandCount: 0,
hookFiles: consentRequired ? ["hooks/a-very-long-lifecycle-hook-file-name.json"] : [],
requiresConsent: consentRequired,
},
valid: true,
},
enabled: !consentRequired,
origin: consentRequired ? "consent" : "none",
consentRequired,
});
test("agent plugin metadata stays clear of enable and review controls at narrow widths", async ({
workbench: page,
}) => {
const longName = "Context Engineering with an exceptionally long plugin display name";
const catalog: AgentPluginCatalog = {
plugins: [makePlugin(longName, true), makePlugin("Frontend Design", false)],
marketplaces: [
{
id: "official",
name: "claude-plugins-official",
source: "example/official",
scope: "user",
discovered: true,
},
{
id: "community",
name: "context-engineering-marketplace-with-a-long-name",
source: "example/community",
scope: "user",
discovered: true,
},
],
projectedSkills: 17,
projectedMcpServers: 1,
projectedRules: 2,
};
await stubDesktop(page);
await page.evaluate(async (catalog) => {
window.__ipc.handlers.agent_plugins_list = () => structuredClone(catalog);
window.__ipc.handlers.window_open_settings = () => {
throw { kind: "unavailable", message: "separate settings window disabled in browser test", detail: null };
};
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("file.settings", "agents.plugins");
}, catalog);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
const group = dialog.getByRole("region", { name: "Claude Code · User" });
const rows = group.getByRole("listitem");
await expect(rows).toHaveCount(2);
const review = rows.first().getByRole("button", { name: "Review & Enable…" });
await expect(review).toBeVisible();
for (const width of [1120, 780, 580, 520]) {
await page.setViewportSize({ width, height: 760 });
await expect(async () => {
const fit = await rows.evaluateAll((items) =>
items.every((row) => {
const expand = row.querySelector("button[aria-expanded]")!;
const action = expand.nextElementSibling!;
const bounds = row.getBoundingClientRect();
const a = expand.getBoundingClientRect();
const b = action.getBoundingClientRect();
const title = expand.querySelector("[title]")!.getBoundingClientRect();
return (
title.width > 0 &&
a.right <= bounds.right + 1 &&
b.right <= bounds.right + 1 &&
(a.right <= b.left + 1 || a.bottom <= b.top + 1) &&
expand.scrollWidth <= expand.clientWidth + 1
);
}),
);
expect(fit).toBe(true);
}).toPass();
if (process.env.SETTINGS_EVIDENCE)
await dialog.screenshot({
path: `${process.env.SETTINGS_EVIDENCE}/plugins-${width}.png`,
animations: "disabled",
});
}
await rows
.first()
.getByRole("button", { name: new RegExp(longName) })
.click();
await expect(rows.first().getByText(catalog.plugins[0]!.plugin.marketplace!)).toBeVisible();
await expect(rows.first().getByText(".claude-plugin · .codex-plugin · .plugin")).toBeVisible();
await expect(rows.first().getByText(catalog.plugins[0]!.plugin.description, { exact: true })).toBeVisible();
if (process.env.SETTINGS_EVIDENCE) {
await page.setViewportSize({ width: 1120, height: 760 });
await page.evaluate(async () => {
const themePath = "/src/workbench/theme.ts";
const { setTheme } = await import(/* @vite-ignore */ themePath);
await setTheme("dark");
});
await dialog.screenshot({
path: `${process.env.SETTINGS_EVIDENCE}/plugins-expanded-dark.png`,
animations: "disabled",
});
}
await review.click();
await expect(page.getByRole("dialog", { name: /Approve Plugin Capabilities/ })).toBeVisible();
});
+13
Переглянути файл
@@ -70,6 +70,19 @@ async function openHistory(page: Page) {
return stream;
}
// Selecting words in a long conversation must not move the reader away from the clicked text.
test("keeps the conversation position on double-click", async ({ page }) => {
const stream = await openHistory(page);
await stream.evaluate((el) => {
el.scrollTop = el.scrollHeight / 2;
});
const target = stream.locator("[class*='_conversationRow_']").filter({ hasText: "Reply 40" }).last();
await target.scrollIntoViewIfNeeded();
const before = await stream.evaluate((el) => el.scrollTop);
await target.getByText("Reply 40", { exact: true }).dblclick();
await expect.poll(() => stream.evaluate((el, top) => Math.abs(el.scrollTop - top), before)).toBeLessThanOrEqual(1);
});
for (const placement of ["editor", "toolWindow"] as const) {
test(`lets small upward wheel steps leave the end while replies stream in the ${placement}`, async ({ page }) => {
// Streams into an 80-turn conversation for several seconds: close to 30 s on CI runners.
+74
Переглянути файл
@@ -0,0 +1,74 @@
/**
* The Dependencies node under a .NET project in the Project view (#7429), from a stubbed
* workspace model; `src/features/dotnet/tree.test.ts` covers the tree contributions.
*/
import { expect, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
test("a project lists its packages, projects, frameworks and analyzers under Dependencies", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const storeModule = "/src/features/dotnet/store.ts";
const { useDotnet } = await import(/* @vite-ignore */ storeModule);
const project = (path: string, name: string, extra: object = {}) => ({
path,
name,
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
...extra,
});
useDotnet.setState({
model: {
projects: [
project("/dev/acme-api/App/App.csproj", "App", {
packages: [{ id: "Newtonsoft.Json", version: "13.0.3" }],
references: ["/dev/acme-api/Core/Core.csproj", "/dev/acme-api/Shared/Core.csproj"],
frameworkReferences: ["Microsoft.AspNetCore.App"],
analyzers: ["Microsoft.AspNetCore.Analyzers.dll"],
}),
project("/dev/acme-api/Core/Core.csproj", "Core"),
project("/dev/acme-api/Shared/Core.csproj", "Core"),
],
solutions: [
{
path: "/dev/acme-api/Acme.sln",
projects: ["/dev/acme-api/App/App.csproj", "/dev/acme-api/Core/Core.csproj"],
},
],
},
});
});
const tree = page.getByRole("tree", { name: "Project" });
await tree.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
const app = tree.getByRole("treeitem", { name: "App", exact: true });
await app.click();
await page.keyboard.press("ArrowRight");
await tree.getByRole("treeitem", { name: "Dependencies", exact: true }).click();
await page.keyboard.press("ArrowRight");
for (const group of ["Packages", "Projects", "Frameworks", "Analyzers"]) {
await tree.getByRole("treeitem", { name: group, exact: true }).click();
await page.keyboard.press("ArrowRight");
}
// The solution's Core plus each distinct reference with that same display name.
await expect(tree.getByRole("treeitem", { name: "Core", exact: true })).toHaveCount(3);
await expect(tree.getByRole("treeitem", { name: /Newtonsoft\.Json/ })).toContainText("13.0.3");
await expect(tree.getByRole("treeitem", { name: "Microsoft.AspNetCore.App", exact: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "Microsoft.AspNetCore.Analyzers.dll", exact: true })).toBeVisible();
// Core has no dependencies: no node.
await expect(tree.getByRole("treeitem", { name: "Dependencies" })).toHaveCount(1);
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b2-dependencies.png`, animations: "disabled" });
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab");
await expect(editorTabs).toHaveText(["App.csproj"]);
await tree.getByRole("treeitem", { name: /Newtonsoft\.Json/ }).dblclick();
await expect(editorTabs).toHaveText(["App.csproj"]);
});
+95
Переглянути файл
@@ -0,0 +1,95 @@
/**
* A stubbed `dotnet` process host for the NuGet window specs. No CLI runs: `window.__dotnetOut`
* (set by the spec) answers each argument list, and a thrown message becomes a non-zero exit.
* The real-CLI vitest tests (`src/features/dotnet/*.cli.test.ts`) are the evidence for what
* `dotnet` actually does; these specs check the UI and the exact commands it starts.
*/
import type { Locator, Page } from "@playwright/test";
import { stubDesktop } from "./fixtures";
declare global {
interface Window {
__runs: string[][];
__dotnetOut: (args: string[]) => string;
}
}
/** One project, `/dev/acme/src/App/App.csproj`, in the workspace rooted at `/dev/acme`. */
export const PROJECT = "/dev/acme/src/App/App.csproj";
export async function installDotnetHost(page: Page) {
await stubDesktop(page);
await page.evaluate(
async ({ project }) => {
window.__runs = [];
window.__dotnetOut = () => "";
let id = 100;
window.__ipc.handlers.run_start = (args) => {
const config = args.config as { args: string[] };
window.__runs.push(config.args);
const run = ++id;
setTimeout(() => {
let text: string;
let code = 0;
try {
text = window.__dotnetOut(config.args);
} catch (e) {
text = (e as Error).message;
code = 1;
}
window.__ipc.send(args.onOutput, { kind: "stdout", text });
window.__ipc.emit({ type: "runExited", run, code });
}, 20);
return { id: run, configId: "x", name: "dotnet", pid: 1, running: true, pty: false };
};
const dotnetStore = "/src/features/dotnet/store.ts";
const projectStore = "/src/platform/project.ts";
const { useDotnet } = await import(/* @vite-ignore */ dotnetStore);
const { useProject } = await import(/* @vite-ignore */ projectStore);
useProject.setState({ project: { ...useProject.getState().project, root: "/dev/acme" } });
useDotnet.setState({
model: {
projects: [
{
path: project,
name: "App",
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
},
],
solutions: [],
},
selected: project,
framework: "net9.0",
});
},
{ project: PROJECT },
);
}
export const dotnetRuns = (page: Page) => page.evaluate(() => window.__runs);
/** Opens the NuGet Packages tool window through its action. */
export async function openNuget(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("dotnet.packages");
});
}
const SHOTS = process.env.E2E_SHOTS;
/** With `E2E_SHOTS` set: a screenshot of the NuGet Packages window scrolled to `focus` (fixture data only). */
export async function shot(page: Page, name: string, focus: Locator) {
if (!SHOTS) return;
await focus.scrollIntoViewIfNeeded();
await page
.locator('section[aria-label="NuGet Packages"]')
.screenshot({ path: `${SHOTS}/${name}.png`, animations: "disabled" });
}
+70
Переглянути файл
@@ -0,0 +1,70 @@
/**
* Solution folders and solution items in the Project view (#7431), from a stubbed workspace model;
* `src/platform/dotnetSolutionFolders.test.ts` covers parsing `.sln` / `.slnx`.
*/
import { expect, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
test("nested solution folders hold projects and solution items that open in the editor", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const storeModule = "/src/features/dotnet/store.ts";
const { useDotnet } = await import(/* @vite-ignore */ storeModule);
const project = (path: string, name: string) => ({
path,
name,
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
});
useDotnet.setState({
model: {
projects: [
project("/dev/acme-api/src/libs/Core/Core.csproj", "Core"),
project("/dev/acme-api/App/App.csproj", "App"),
],
solutions: [
{
path: "/dev/acme-api/Acme.slnx",
projects: ["/dev/acme-api/src/libs/Core/Core.csproj", "/dev/acme-api/App/App.csproj"],
folders: [
{
path: ["src", "libs"],
files: ["/dev/acme-api/README.md"],
projects: ["/dev/acme-api/src/libs/Core/Core.csproj"],
},
{ path: ["src", "libs", "core"], files: [], projects: [] },
],
},
],
},
});
});
const tree = page.getByRole("tree", { name: "Project" });
await tree.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
for (const folder of ["src", "libs"]) {
const node = tree.getByRole("treeitem", { name: folder, exact: true }).first();
await node.click();
await page.keyboard.press("ArrowRight");
}
await expect(tree.getByRole("treeitem", { name: "core", exact: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "Core", exact: true })).toBeVisible();
// The project outside every folder stays at the solution's top level.
await expect(tree.getByRole("treeitem", { name: "App", exact: true })).toBeVisible();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b3-solution-folders.png`, animations: "disabled" });
// A solution item is a file node: it opens in the editor.
const item = tree.getByRole("treeitem", { name: "README.md", exact: true }).first();
await item.dblclick();
await expect(
page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "README.md" }),
).toBeVisible();
});
+12
Переглянути файл
@@ -44,6 +44,18 @@ test("Gradle keeps the local installation with Distribution and saves edits in p
await expect(distribution).toHaveText("Gradle wrapper");
await expect(installation).toHaveCount(0);
const fields = userHome.or(runUsing).or(distribution).or(jvm);
for (const width of [1120, 800, 520]) {
await page.setViewportSize({ width, height: 760 });
const edges = await fields.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
expect(edges).toHaveLength(4);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
await distribution.click();
await page.getByRole("option", { name: "Local installation", exact: true }).click();
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
+123
Переглянути файл
@@ -0,0 +1,123 @@
/**
* Central package management in the NuGet Packages window (#7427) over a stubbed `dotnet` host
* (`dotnetHost.ts`): the spec checks what the window shows and the exact commands it starts;
* `src/features/dotnet/central.cli.test.ts` runs the real CLI and shows what `dotnet add package`
* writes.
*/
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
import { dotnetRuns, installDotnetHost, openNuget, PROJECT, shot } from "./dotnetHost";
const PROPS = "/dev/acme/Directory.Packages.props";
/** `override`: the project carries `VersionOverride`, the props file keeps 1.0.0. */
async function stubCentral(page: Page, mode: "central" | "override") {
await installDotnetHost(page);
await page.evaluate(
({ mode, props }) => {
let current = "1.0.0";
const latest = "1.1.0";
const json = (value: unknown) => JSON.stringify(value);
window.__dotnetOut = (args) => {
if (args[0] === "msbuild") {
if (!args.some((a) => a.includes("ManagePackageVersionsCentrally")))
return json({ Properties: { MSBuildProjectName: "App", TargetFramework: "net9.0" }, Items: {} });
return json({
Properties: { ManagePackageVersionsCentrally: "true", CentralPackageTransitivePinningEnabled: "true" },
Items: {
PackageVersion: [
{
Identity: "Demo.Pkg",
Version: mode === "central" ? current : "1.0.0",
DefiningProjectFullPath: props,
},
{ Identity: "Child.Pkg", Version: "1.0.0", DefiningProjectFullPath: props },
],
PackageReference: [
{ Identity: "Demo.Pkg", ...(mode === "override" ? { VersionOverride: current } : {}) },
],
},
});
}
if (args[0] === "add") {
current = args[args.indexOf("--version") + 1]!;
return "ok\n";
}
if (args[0] === "list") {
const demo = { id: "Demo.Pkg", requestedVersion: current, resolvedVersion: current };
const framework = (extra: object) =>
json({ projects: [{ frameworks: [{ framework: "net9.0", ...extra }] }] });
if (args.includes("--outdated"))
return framework({ topLevelPackages: current === latest ? [] : [{ ...demo, latestVersion: latest }] });
return framework({
topLevelPackages: [demo],
transitivePackages: [{ id: "Child.Pkg", resolvedVersion: "1.0.0" }],
});
}
return "ok\n";
};
},
{ mode, props: PROPS },
);
await openNuget(page);
}
const row = (page: Page, id: string) => page.getByRole("listitem").filter({ hasText: id }).last();
test("a centrally managed project shows where versions are defined, marks a newer version and Update writes through dotnet add package", async ({
workbench: page,
}) => {
await stubCentral(page, "central");
await expect(page.getByRole("status")).toContainText("Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).toContainText("Defined in Directory.Packages.props");
await expect(row(page, "Child.Pkg")).toContainText("Pinned in Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).not.toContainText("Newer version");
await page.getByRole("button", { name: "Check for updates" }).click();
await expect(row(page, "Demo.Pkg")).toContainText("Newer version available: 1.1.0");
await shot(page, "d2-central", row(page, "Demo.Pkg"));
await row(page, "Demo.Pkg").getByRole("button", { name: "Update to 1.1.0" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["add", PROJECT, "package", "Demo.Pkg", "--version", "1.1.0"]);
// The window re-reads the props file and the outdated list afterwards.
await expect(row(page, "Demo.Pkg")).toContainText("1.1.0");
await expect(row(page, "Demo.Pkg")).toContainText("Defined in Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).not.toContainText("Newer version");
});
test("a VersionOverride in the project is shown as the project's, and Update rewrites it there", async ({
workbench: page,
}) => {
await stubCentral(page, "override");
await expect(row(page, "Demo.Pkg")).toContainText("Version override 1.0.0 in the project");
await expect(row(page, "Demo.Pkg")).not.toContainText("Defined in");
await page.getByRole("button", { name: "Check for updates" }).click();
await expect(row(page, "Demo.Pkg")).toContainText("Newer version available: 1.1.0");
await shot(page, "d2-override", row(page, "Demo.Pkg"));
await row(page, "Demo.Pkg").getByRole("button", { name: "Update to 1.1.0" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["add", PROJECT, "package", "Demo.Pkg", "--version", "1.1.0"]);
await expect(row(page, "Demo.Pkg")).toContainText("Version override 1.1.0 in the project");
});
test("without central management nothing is labelled as central", async ({ workbench: page }) => {
await stubCentral(page, "central");
await page.evaluate(() => {
const ok = window.__dotnetOut;
window.__dotnetOut = (args) =>
args[0] === "msbuild" && args.some((a) => a.includes("ManagePackageVersionsCentrally"))
? JSON.stringify({ Properties: { ManagePackageVersionsCentrally: "" }, Items: {} })
: ok(args);
});
await page.getByRole("button", { name: "Refresh packages" }).click();
await expect(row(page, "Demo.Pkg")).toBeVisible();
await page.evaluate(async () => {
const central = "/src/features/dotnet/central.ts";
const { refreshCentral } = await import(/* @vite-ignore */ central);
await refreshCentral();
});
await expect(page.getByText("Defined in")).toHaveCount(0);
await expect(page.getByText("Pinned in")).toHaveCount(0);
await expect(page.getByRole("status")).toHaveCount(0);
});
+134
Переглянути файл
@@ -0,0 +1,134 @@
/**
* Package sources in the NuGet Packages window (#7420) over a stubbed `dotnet` host
* (`dotnetHost.ts`): the spec checks what the window shows and the exact commands it starts;
* `src/features/dotnet/sources.cli.test.ts` runs the real CLI.
*/
import { expect, test } from "./fixtures";
import { dotnetRuns, installDotnetHost, openNuget, shot } from "./dotnetHost";
const CONFIG = "/dev/acme/NuGet.Config";
const USER_CONFIG = "/Users/dev/.nuget/NuGet/NuGet.Config";
async function stubSources(page: Parameters<typeof installDotnetHost>[0]) {
await installDotnetHost(page);
await page.evaluate(
({ config, userConfig }) => {
const sources = [
{ name: "local", url: "/dev/acme/feed", enabled: true },
{ name: "shared", url: "https://pkgs.example.com/v3/index.json", enabled: true },
// A password inside the URL: the window must not show it.
{ name: "private", url: "https://bob:[email protected]/v3/index.json", enabled: false },
];
window.__dotnetOut = (args) => {
const [, verb, , name] = args;
if (args[0] === "list") return '{"projects":[]}';
// Other windows of the NuGet view (central package state) ask MSBuild too.
if (args[0] === "msbuild") return '{"Properties":{},"Items":{}}';
if (args[1] === "config") return `${config}\n${userConfig}\n`;
if (verb === "list") {
const target = args.at(-1);
const listed =
target === config
? sources.filter((s) => s.name !== "shared")
: target === userConfig
? sources.filter((s) => s.name === "shared")
: sources;
return `Registered Sources:\n\n${listed
.map((s, i) => ` ${i + 1}. ${s.name} [${s.enabled ? "Enabled" : "Disabled"}]\n ${s.url}`)
.join("\n")}\n`;
}
if (verb === "add") sources.push({ name: args[args.indexOf("--name") + 1]!, url: args[3]!, enabled: true });
else if (verb === "remove")
sources.splice(
sources.findIndex((s) => s.name === name),
1,
);
else sources.find((s) => s.name === name)!.enabled = verb === "enable";
return "ok\n";
};
},
{ config: CONFIG, userConfig: USER_CONFIG },
);
await openNuget(page);
await page.getByText("Package sources", { exact: true }).click();
}
test("lists the effective sources, masks URL credentials and toggles a source in the workspace file", async ({
workbench: page,
}) => {
await stubSources(page);
const list = page.getByRole("list", { name: "Package sources" });
await expect(list.getByText(/local/)).toBeVisible();
await expect(list.getByText(/private.*Disabled/)).toBeVisible();
await expect(list).toContainText("https://***@pkgs.example.com");
await expect(page.getByText("s3cret-pw")).toHaveCount(0);
await expect(page.getByLabel("NuGet.Config file")).toHaveValue(CONFIG);
await expect(
list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }),
).toBeDisabled();
await shot(page, "d1-sources", list.getByText(/private/));
await list.getByRole("listitem").filter({ hasText: "private" }).getByRole("button", { name: "Enable" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "enable", "source", "private", "--configfile", CONFIG]);
await expect(list.getByText(/private.*Disabled/)).toHaveCount(0);
await list.getByRole("listitem").filter({ hasText: "local" }).getByRole("button", { name: "Disable" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "disable", "source", "local", "--configfile", CONFIG]);
await expect(list.getByText(/local.*Disabled/)).toBeVisible();
});
test("adds and removes a source; the user-wide file is a labelled, explicit choice", async ({ workbench: page }) => {
await stubSources(page);
await page.getByLabel("Source name").fill("team");
await page.getByLabel("Source URL or folder").fill("https://nuget.team.example/v3/index.json");
await page.getByRole("button", { name: "Add source" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual([
"nuget",
"add",
"source",
"https://nuget.team.example/v3/index.json",
"--name",
"team",
"--configfile",
CONFIG,
]);
const list = page.getByRole("list", { name: "Package sources" });
await expect(list.getByText(/team/)).toBeVisible();
// The user-wide file is last, labelled, and warns once picked.
await expect(page.getByRole("status")).toHaveCount(0);
await page.getByLabel("NuGet.Config file").selectOption(USER_CONFIG);
await expect(page.getByRole("status")).toContainText("every project");
await shot(page, "d1-user-wide", page.getByRole("status"));
await expect(
list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }),
).toBeEnabled();
await page.getByLabel("NuGet.Config file").selectOption(CONFIG);
await list.getByRole("listitem").filter({ hasText: "team" }).getByRole("button", { name: "Remove" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "remove", "source", "team", "--configfile", CONFIG]);
await expect(list.getByText(/team/)).toHaveCount(0);
});
test("a failing dotnet command shows its message and keeps the list", async ({ workbench: page }) => {
await stubSources(page);
await page.evaluate(() => {
const ok = window.__dotnetOut;
window.__dotnetOut = (args) => {
if (args[2] === "source" && args[1] === "remove") throw new Error("error: Unable to find a source named 'nope'.");
return ok(args);
};
});
await page
.getByRole("list", { name: "Package sources" })
.getByRole("listitem")
.first()
.getByRole("button", { name: "Remove" })
.click();
await expect(page.getByRole("alert")).toContainText("Unable to find a source");
await expect(page.getByRole("list", { name: "Package sources" }).getByRole("listitem")).toHaveCount(3);
});
+14 -6
Переглянути файл
@@ -1,6 +1,6 @@
import { expect, stubDesktop, test } from "./fixtures";
test("keeps the project switcher flat while grouping Welcome and Recent Projects without row overlap", async ({
test("keeps local and remote projects flat in all recent-project lists without row overlap", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 980, height: 740 });
@@ -111,7 +111,7 @@ test("keeps the project switcher flat while grouping Welcome and Recent Projects
await page.keyboard.press("Escape");
await expect(projectPopup).toBeHidden();
// 2. Recent Projects popup groups by host and never overlaps rows (grouped or 3-line search results).
// 2. Recent Projects popup is flat and never overlaps rows, including search results.
await page.evaluate(async () => {
const popupMod = "/src/features/welcome/RecentProjectsPopup.tsx";
const { showRecentProjectsPopup } = await import(/* @vite-ignore */ popupMod);
@@ -128,20 +128,28 @@ test("keeps the project switcher flat while grouping Welcome and Recent Projects
expect(boxes[i]!.y).toBeGreaterThanOrEqual(boxes[i - 1]!.y + boxes[i - 1]!.height - 0.5);
}
};
await expect(recentDialog.getByRole("option")).toHaveCount(6);
await expect(recentDialog.locator("[aria-expanded]")).toHaveCount(0);
await expect(recentDialog.locator("[data-remote-badge]")).toHaveCount(4);
await assertNoVerticalOverlap();
await recentDialog.getByRole("textbox", { name: "Search recent projects" }).fill("openidea_all");
await assertNoVerticalOverlap();
await page.keyboard.press("Escape");
await expect(recentDialog).toBeHidden();
// 3. Welcome › Projects folds and unfolds host groups.
// 3. Welcome › Projects keeps all projects in recency order without host headers.
await page.evaluate(async () => {
const projectMod = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectMod);
useProject.setState({ project: null, lightEdit: false });
});
const welcomeList = page.getByRole("listbox", { name: "Recent projects" });
await expect(welcomeList.getByRole("option")).toHaveCount(11);
await welcomeList.getByRole("option").first().click();
await expect(welcomeList.getByRole("option")).toHaveCount(9);
const welcomeRows = welcomeList.getByRole("option");
await expect(welcomeRows).toHaveCount(7);
await expect(welcomeList.locator("[aria-expanded]")).toHaveCount(0);
await expect(welcomeList.locator("[data-remote-badge]")).toHaveCount(4);
await expect(welcomeRows.nth(0)).toContainText("[email protected]:22:/home/coder/git/openidea_all");
await expect(welcomeRows.nth(1)).toContainText("dev-mbp1.local:/Users/dev/git/gocommon");
await expect(welcomeRows.nth(2)).toContainText("~/git/gocommon");
await expect(welcomeRows.nth(3)).toContainText("[email protected]:22:/home/coder/git/gocommon");
});
+63 -28
Переглянути файл
@@ -2,34 +2,39 @@ import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
/** Supply detected configurations without launching desktop processes. */
async function configure(page: Page, extra = 0) {
await page.evaluate(async (extra) => {
const storePath = "/src/features/run/store.ts";
const projectPath = "/src/platform/project.ts";
const { useRun } = await import(storePath);
const { useProject } = await import(projectPath);
localStorage.setItem(`openidea.services.runTypes:${useProject.getState().project.root}`, '["spring-boot","npm"]');
useRun.setState({
configs: [
["gateway", "spring-boot"],
["portal", "spring-boot"],
["web", "npm"],
["worker", "npm"],
...Array.from({ length: extra }, (_, i) => [`app-${i}`, "spring-boot"]),
].map(([id, kind]) => ({
id,
name: id,
kind,
command: kind,
args: [],
env: {},
cwd: null,
detected: true,
isTest: false,
debugAdapter: null,
})),
});
}, extra);
async function configure(page: Page, extra = 0, useDefaults = false) {
await page.evaluate(
async ({ extra, useDefaults }) => {
const storePath = "/src/features/run/store.ts";
const projectPath = "/src/platform/project.ts";
const { useRun } = await import(storePath);
const { useProject } = await import(projectPath);
const key = `openidea.services.runTypes:${useProject.getState().project.root}`;
if (useDefaults) localStorage.removeItem(key);
else localStorage.setItem(key, '["spring-boot","npm"]');
useRun.setState({
configs: [
["gateway", "spring-boot"],
["portal", "spring-boot"],
["web", "npm"],
["worker", "npm"],
...Array.from({ length: extra }, (_, i) => [`app-${i}`, "spring-boot"]),
].map(([id, kind]) => ({
id,
name: id,
kind,
command: kind,
args: [],
env: {},
cwd: null,
detected: true,
isTest: false,
debugAdapter: null,
})),
});
},
{ extra, useDefaults },
);
if (!(await page.getByRole("tree", { name: "Services", exact: true }).isVisible()))
await page.keyboard.press("Meta+8");
await expect(page.getByRole("tree", { name: "Services", exact: true })).toBeVisible();
@@ -48,6 +53,36 @@ async function move(page: Page, source: string, target: string) {
await page.mouse.up();
}
test("Services shows Spring Boot run configurations and their running ports by default", async ({
workbench: page,
}) => {
await configure(page, 0, true);
const tree = page.getByRole("tree", { name: "Services", exact: true });
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "gateway", "portal"]);
await page.evaluate(async () => {
const storePath = "/src/features/run/store.ts";
const { useRun } = (await import(/* @vite-ignore */ storePath)) as typeof import("../src/features/run/store");
const config = useRun.getState().configs.find((config) => config.id === "gateway")!;
useRun.setState({
sessions: [
{
id: "gateway-run",
config,
runId: null,
status: "running",
exitCode: null,
startedAt: Date.now(),
endedAt: null,
stdinClosed: true,
httpPort: 8080,
httpPath: "/api",
},
],
});
});
await expect(tree.getByRole("treeitem", { name: /gateway/ })).toContainText(":8080/api/");
});
test("Services favors details and stacks the panes when docked to the side", async ({ workbench: page }) => {
await configure(page);
const services = page.getByRole("region", { name: "Services", exact: true });
+42
Переглянути файл
@@ -275,6 +275,48 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
await expect(dialog.getByLabel("solargraph details")).toContainText("gem install solargraph");
});
test("Vue Language Server accepts a manual managed version in Settings", async ({ workbench: page }) => {
await page.evaluate(async () => {
const path = "/src/features/tools/backend.ts";
const { MemoryToolsBackend, sampleTools, setToolsBackend } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/features/tools/backend");
const sample = sampleTools().find((tool) => tool.name === "gopls")!;
setToolsBackend(
new MemoryToolsBackend([
{
...sample,
name: "vue-language-server",
displayName: "Vue Language Server",
command: "vue-language-server",
languages: ["Vue"],
installMethod: "npm",
},
]),
);
});
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Language Servers");
await dialog.getByRole("treeitem", { name: "Language Servers", exact: true }).click();
await dialog
.getByRole("list", { name: "Languages", exact: true })
.getByRole("button", { name: /^Vue\b/ })
.click();
await dialog.locator('[data-tool="vue-language-server"]').click();
const version = dialog.getByLabel(/Vue Language Server version/);
await expect(version).toBeEmpty();
await version.fill("../invalid");
await expect(version).toHaveAttribute("aria-invalid", "true");
await version.fill("3.0.8");
await expect(version).not.toHaveAttribute("aria-invalid", "true");
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
await expect(apply).toBeEnabled();
await apply.click();
await expect(apply).toBeDisabled();
await expect(version).toHaveValue("3.0.8");
});
test("font picker supports manual families and CJK fallback in browser development", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
+41
Переглянути файл
@@ -74,6 +74,47 @@ test("settings forms share control columns and keep font metrics on one row", as
}
});
test("toolchain, encoding and Subversion settings align field frames across sections", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const body = page.getByRole("dialog", { name: "Settings", exact: true }).locator("[class*='pageBody']");
for (const [id, title, count] of [
["languages.go", "Go", 2],
["languages.java", "Java", 4],
["languages.rust", "Rust", 4],
["languages.node", "JavaScript Runtime", 4],
["languages.php", "PHP", 4],
["build.maven", "Maven", 8],
["editor.fileEncodings", "File Encodings", 4],
["vcs.svn", "Subversion", 2],
] as const) {
await selectPage(page, id);
await expect(page.getByLabel("Breadcrumb").locator('[aria-current="page"]')).toHaveText(title);
if (id === "vcs.svn") {
await body.getByRole("checkbox", { name: "Use custom configuration directory" }).check();
await expect(body.getByRole("textbox", { name: /Configuration directory/ })).toBeEnabled();
}
const fields = body
.getByRole("button")
.and(body.locator("[aria-haspopup='listbox']"))
.or(body.getByRole("textbox"))
.or(body.getByRole("combobox"))
.and(body.locator(':not([aria-label="Thread count"])'));
await expect(fields).toHaveCount(count);
for (const width of [1200, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, body.getByRole("button", { name: "Browse…", exact: true })]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge, `${id} at ${width}px`).toEqual(edges[0]);
}
}
}
});
for (const locale of ["en", "zh"]) {
test(`${locale} forms fit narrow settings panes without horizontal scrolling`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
+23
Переглянути файл
@@ -117,6 +117,29 @@ test("Live Templates gives the editor the full settings pane width and keeps var
expect(await variables.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
});
test("Project settings aligns the visible fields and their browse buttons", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
const fields = dialog
.getByRole("button", { name: /^(Project SDK|Project language level|Language server JDK)$/ })
.or(dialog.getByRole("textbox", { name: "Compiler output" }));
const browse = dialog.getByRole("button", { name: "Browse…" });
await expect(fields).toHaveCount(4);
await expect(browse).toHaveCount(3);
for (const width of [1400, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, browse]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
}
});
test("Project Structure keeps every details pane usable in a compact window", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
+31
Переглянути файл
@@ -42,3 +42,34 @@ test("Welcome keeps project search and actions on one row at a narrow width", as
await expect(more).toBeFocused();
await expect(search).toHaveValue("tokio");
});
test("Welcome lists local and remote projects at the same level", async ({ workbench: page }) => {
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
useProject.setState({ project: null, lightEdit: false });
});
const list = page.getByRole("listbox", { name: "Recent projects" });
const rows = list.getByRole("option");
await expect(rows).toHaveCount(4);
await page.evaluate(async () => {
const recentPath = "/src/features/welcome/recent.ts";
const { useRecent } = await import(/* @vite-ignore */ recentPath);
useRecent.setState({
groups: [],
projects: [
{ name: "tty7", path: "ssh://macmini/Users/thomas/repo/tty7", branch: null, openedAtMs: 100 },
{ name: "OpenIDEA", path: "/Users/dev/dev/openidea", branch: null, openedAtMs: 90 },
{ name: "tty7", path: "/Users/dev/dev/tty7", branch: null, openedAtMs: 80 },
],
});
});
await expect(rows).toHaveCount(3);
await expect(rows.nth(0)).toContainText("macmini:/Users/thomas/repo/tty7");
await expect(rows.nth(1)).toContainText("OpenIDEA");
await expect(rows.nth(2)).toContainText("~/dev/tty7");
await expect(list.locator("[aria-expanded]")).toHaveCount(0);
await expect(list.locator("[data-remote-badge]")).toHaveCount(1);
const avatars = await rows.evaluateAll((els) => els.map((el) => el.firstElementChild!.getBoundingClientRect().x));
expect(avatars).toEqual([avatars[0], avatars[0], avatars[0]]);
});
+8
Переглянути файл
@@ -38,6 +38,8 @@ mod theme_frame;
#[cfg(target_os = "macos")]
mod titlebar;
mod updates;
#[cfg(any(windows, test))]
mod window_display;
mod window_groups;
#[cfg(any(windows, test))]
mod window_work_area;
@@ -295,6 +297,8 @@ pub fn run() {
}
tauri::WindowEvent::Focused(true) => {
application_focus::changed(window.app_handle(), true);
#[cfg(windows)]
window_display::remember(window);
if let Some(w) = window.try_state::<WindowsState>() {
w.focused(window.label());
}
@@ -302,6 +306,10 @@ pub fn run() {
tauri::WindowEvent::Focused(false) => application_focus::changed(window.app_handle(), false),
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => {
window_groups::frame_changed(window.app_handle(), window.label());
#[cfg(windows)]
if matches!(event, tauri::WindowEvent::Moved(_)) {
window_display::remember(window);
}
}
tauri::WindowEvent::Destroyed => {
// Also release a view that failed during startup, before the parent could watch it.
+25 -58
Переглянути файл
@@ -14,73 +14,39 @@ use crate::remote_wsl::{Probe, Tail, install_script, parse_probe, probe_script,
use ide_core::{IdeError, IdeResult};
use ide_jsonrpc::{Handler, Peer};
use ide_remote::container_tunnel::Exec;
use ide_remote::devcontainer::{Up, parse_up};
use ide_remote::devcontainer::{self, Target, UP_TIMEOUT, Up};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
/// Building an image (and its features) can take a while on a first open.
const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
fn cli(data_dir: &Path) -> IdeResult<PathBuf> {
ide_tools::Tools::new(data_dir)
.info("devcontainer", &[])
.ok()
.and_then(|t| t.path)
.map(ide_core::IpcPath::into_path_buf)
.ok_or_else(|| {
IdeError::unavailable(
"The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.",
)
})
}
/// `devcontainer up` for `folder` (with configuration `config`, relative to it; empty = the
/// default one). Its log goes to `tail` and the IDE log.
async fn up(cli: &Path, docker: &Path, folder: &Path, config: &str, tail: &Tail) -> IdeResult<Up> {
let mut cmd = tokio::process::Command::new(cli);
ide_core::process::prepare(cmd.as_std_mut());
cmd.arg("up").arg("--workspace-folder").arg(folder);
if !config.trim().is_empty() {
cmd.arg("--config").arg(folder.join(config.trim()));
}
cmd.arg("--docker-path")
.arg(docker)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot start devcontainer: {e}")))?;
let stderr = child.stderr.take();
let log = tail.clone();
let reader = tokio::spawn(async move {
let Some(stderr) = stderr else { return };
let mut lines = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
tracing::info!(target: "devcontainer", "{line}");
log.push(line);
}
});
let out = tokio::time::timeout(UP_TIMEOUT, child.wait_with_output())
.await
.map_err(|_| IdeError::unavailable("devcontainer up did not finish in time"))?
.map_err(|e| IdeError::unavailable(format!("devcontainer up failed: {e}")))?;
let _ = reader.await;
let result = parse_up(&String::from_utf8_lossy(&out.stdout));
if out.status.success() {
return result;
}
let error = result
.err()
.unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}", status = out.status)));
Err(match tail.text() {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
let (cli, docker, target, tail) =
(cli.to_owned(), docker.to_owned(), Target::relative(folder, config), tail.clone());
let cancel = ide_core::CancellationToken::new();
// This future dropped (the command was cancelled): the CLI stops with it. A superseded
// attempt is not dropped and runs on; Reopen in Container is not held to one start per folder.
let _stop = cancel.clone().drop_guard();
tokio::task::spawn_blocking(move || {
devcontainer::up(
&cli,
&docker,
&target,
&[],
UP_TIMEOUT,
&mut |line| {
tracing::info!(target: "devcontainer", "{line}");
tail.push(line.to_owned());
},
&cancel,
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// `docker exec [-i] -u <user> <container> sh -c <script> sh <args>…`.
@@ -214,8 +180,9 @@ pub(crate) async fn connect(
));
}
let data = state.host.local_data_dir.clone();
let cli =
tokio::task::spawn_blocking(move || cli(&data)).await.map_err(|e| IdeError::internal(e.to_string()))??;
let cli = tokio::task::spawn_blocking(move || ide_host::devcontainer::cli(&data))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let up = up(&cli, &docker, &local, config, tail).await?;
let bin = ensure_server(state, &docker, &up, progress).await?;
progress(RemoteStage::Starting, None);
+7
Переглянути файл
@@ -89,6 +89,8 @@ pub struct Connection {
session: Option<Arc<ide_ssh::Session>>,
/// How to reach a dev container's ports; `None` for SSH and WSL.
exec: Option<Arc<ide_remote::container_tunnel::Exec>>,
/// Marks a dev container's container as open in a window for as long as the connection lives.
_attached: Option<ide_host::devcontainer::AttachedContainer>,
/// Remote ports forwarded to this machine (Ports tool window), by host (`None`: the remote
/// host itself) and remote port.
forwards: Mutex<Vec<(ForwardKey, Forward)>>,
@@ -738,6 +740,7 @@ pub async fn remote_connect(
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
let mut attached = None;
let (peer, session, host, title_tag) = match &target {
RemoteTarget::Ssh { config: id } => {
let config = state.ssh.config(id)?;
@@ -774,6 +777,8 @@ pub async fn remote_connect(
let (peer, root, run) =
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
path = root;
// The MCP tools leave this container alone while a window is open in it.
attached = Some(state.host.dev_containers_attached.hold(run.container()));
exec = Some(Arc::new(run));
let name = std::path::Path::new(folder)
.file_name()
@@ -847,6 +852,7 @@ pub async fn remote_connect(
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
exec,
_attached: attached,
});
let _ = connection_slot.set(Arc::downgrade(&connection));
if let RemoteTarget::DevContainer { folder, config } = &target {
@@ -1615,6 +1621,7 @@ mod tests {
next_channel: std::sync::atomic::AtomicU64::new(1),
session: None,
exec: None,
_attached: None,
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
}
+1
Переглянути файл
@@ -112,6 +112,7 @@ impl AppState {
runtime,
project_environment: false,
})
.with_local_desktop()
.with_local_database_tunnels()
.with_subversion(true),
);
+135
Переглянути файл
@@ -0,0 +1,135 @@
//! The display the user last worked on, on Windows. The window-state plugin restores only the
//! maximized and full-screen flags there (`window_state_flags`), so without this every project
//! window that opens at launch, or after the last one closed, lands on the primary display.
use serde::{Deserialize, Serialize};
/// A display by its physical position and size in the virtual screen.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Display {
x: i32,
y: i32,
width: u32,
height: u32,
}
/// The connected display that is the saved one: same position and size. Displays rearranged or
/// resized since then are not matched, so the window opens on the primary display as before.
fn find(connected: &[Display], saved: Display) -> Option<usize> {
connected.iter().position(|d| *d == saved)
}
/// The top-left corner, in the display's logical pixels, that centres a window of `size` in a
/// work area at `origin` of `area` (both logical).
fn centred(origin: (f64, f64), area: (f64, f64), size: (f64, f64)) -> (f64, f64) {
(origin.0 + ((area.0 - size.0) / 2.0).max(0.0), origin.1 + ((area.1 - size.1) / 2.0).max(0.0))
}
#[cfg(windows)]
pub use native::{place, remember};
#[cfg(windows)]
mod native {
use super::{Display, centred, find};
use parking_lot::Mutex;
use std::path::PathBuf;
use tauri::{AppHandle, Manager, Monitor, Runtime, Window, utils::config::WindowConfig};
const FILE: &str = "last-display.json";
/// The saved display, read from disk once.
static SAVED: Mutex<Option<Option<Display>>> = Mutex::new(None);
fn display(monitor: &Monitor) -> Display {
let (position, size) = (monitor.position(), monitor.size());
Display { x: position.x, y: position.y, width: size.width, height: size.height }
}
fn file<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
ide_host::data_dirs::config_dir(&app.config().identifier).ok().map(|dir| dir.join(FILE))
}
fn saved<R: Runtime>(app: &AppHandle<R>) -> Option<Display> {
*SAVED.lock().get_or_insert_with(|| {
let text = std::fs::read_to_string(file(app)?).ok()?;
serde_json::from_str(&text).ok()
})
}
/// Records the display a project window is on, when it is focused or moved.
pub fn remember<R: Runtime>(window: &Window<R>) {
if crate::windows::auxiliary_parent(window.label()).is_some() {
return;
}
let Ok(Some(monitor)) = window.current_monitor() else { return };
let now = display(&monitor);
let app = window.app_handle();
if saved(app) == Some(now) {
return;
}
*SAVED.lock() = Some(Some(now));
let Some(path) = file(app) else { return };
if let Ok(text) = serde_json::to_string(&now)
&& let Err(e) = std::fs::write(&path, text)
{
tracing::debug!("cannot save {}: {e}", path.display());
}
}
/// Where a new project window opens: the saved display when it is still connected, else the
/// primary one. A window without a position of its own (not cascaded from another window) is
/// centred on it. Returns the display, whose work area sizes the window.
pub fn place<R: Runtime>(app: &AppHandle<R>, config: &mut WindowConfig) -> Option<Monitor> {
let primary = app.primary_monitor().ok().flatten();
if config.x.is_some() {
return primary;
}
let connected = app.available_monitors().unwrap_or_default();
let displays: Vec<Display> = connected.iter().map(display).collect();
let Some(monitor) = saved(app).and_then(|s| find(&displays, s)).map(|i| connected[i].clone()) else {
return primary;
};
if primary.as_ref().is_some_and(|p| display(p) == display(&monitor)) {
return primary;
}
let scale = monitor.scale_factor();
let area = monitor.work_area();
let origin = area.position.to_logical::<f64>(scale);
let size = area.size.to_logical::<f64>(scale);
let window = (config.width.min(size.width), config.height.min(size.height));
let (x, y) = centred((origin.x, origin.y), (size.width, size.height), window);
// tao places a logical position on the display it falls on, using that display's scale.
config.x = Some(x);
config.y = Some(y);
config.center = false;
Some(monitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
const PRIMARY: Display = Display { x: 0, y: 0, width: 2560, height: 1440 };
const SECOND: Display = Display { x: 2560, y: 0, width: 1920, height: 1080 };
#[test]
fn finds_the_saved_display_only_while_it_is_connected_unchanged() {
assert_eq!(find(&[PRIMARY, SECOND], SECOND), Some(1));
assert_eq!(find(&[PRIMARY], SECOND), None);
// Rearranged to the left of the primary display: not the saved one any more.
assert_eq!(find(&[PRIMARY, Display { x: -1920, ..SECOND }], SECOND), None);
}
#[test]
fn centres_in_the_work_area_and_keeps_a_larger_window_at_its_corner() {
assert_eq!(centred((2560.0, 0.0), (1920.0, 1040.0), (1440.0, 900.0)), (2800.0, 70.0));
assert_eq!(centred((2560.0, 0.0), (1280.0, 680.0), (1440.0, 900.0)), (2560.0, 0.0));
}
#[test]
fn the_saved_display_round_trips_through_json() {
let text = serde_json::to_string(&SECOND).unwrap();
assert_eq!(serde_json::from_str::<Display>(&text).unwrap(), SECOND);
}
}
+2 -2
Переглянути файл
@@ -1102,9 +1102,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
#[cfg(target_os = "linux")]
let show_after_build = crate::linux_window_state::prepare(app, &mut config);
// Windows opens a project window at the configured size (window-state restores only the
// maximized flag there), which Restore Down returns to.
// maximized flag there), which Restore Down returns to, on the display last worked on.
#[cfg(windows)]
if let Ok(Some(monitor)) = app.primary_monitor() {
if let Some(monitor) = crate::window_display::place(app, &mut config) {
let area = monitor.work_area().size.to_logical::<f64>(monitor.scale_factor());
let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0));
let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));
+10 -3
Переглянути файл
@@ -3421,7 +3421,9 @@ doneMs?: number | null;
/** Sent into a running turn rather than starting one. */
steered?: boolean;
/** Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn. */
recovery?: InterruptionReason | null } | { type: "agent"; text: string } |
recovery?: InterruptionReason | null;
/** One-based automatic retry number for this continuation. */
retryAttempt?: number | null } | { type: "agent"; text: string } |
/** A question that can be answered while the agent keeps working, or after the turn ends. */
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
/** The submitted answers, or `Skipped`; `None` while unanswered. */
@@ -11227,7 +11229,7 @@ export type InterfaceMember = {
};
/** Why an in-flight turn stopped before completing. */
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout";
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout" | "cursorCapacity";
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
export type InvalidateCachesOptions = {
@@ -12497,6 +12499,9 @@ export type MavenSettings = {
runTestsUsing?: MavenRunTestsUsing,
};
/** The execution target recorded with an MCP agent run. */
export type McpAgentRunTarget = { kind: "host" } | { kind: "container"; id: string };
/** What keeps an idle background project loaded. */
export type McpBackgroundHold =
/** A tool call is in flight. */
@@ -12820,7 +12825,7 @@ export type McpUiRequest = { type: "confirm"; client: string; tool: string; subj
* The project is served without a window: the request shows in another project's window,
* which names it and keeps the keyboard focus where it is.
*/
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown } |
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string }; target: McpAgentRunTarget } | { type: "runConfiguration"; config: unknown } |
/** Start a run configuration in Debug mode as the IDE's Debug action would. */
{ type: "debugConfiguration"; config: unknown } |
/**
@@ -17322,6 +17327,8 @@ export type ToolDownloadSettings = {
* crates.io). Off by default.
*/
configuredRegistriesOnly?: boolean,
/** The managed Vue Language Server release. Empty selects it from the project's Vue dependency. */
vueLanguageServerVersion?: string,
};
/** UI-facing state of one tool. */
+2 -2
Переглянути файл
@@ -260,7 +260,7 @@ class Scanner {
return end < 0 ? n : end + quotes;
}
if (!verbatim && quotes === 2) return j + 2;
for (j++; j < n; ) {
for (j++; j < n;) {
const c = s[j];
if (verbatim) {
if (c === '"') {
@@ -304,7 +304,7 @@ class Scanner {
const s = this.s,
n = this.n;
let depth = 0;
for (let i = start; i < n; ) {
for (let i = start; i < n;) {
const c = s[i];
if (this.startsString(i)) {
i = this.skipString(i);
+129 -17
Переглянути файл
@@ -1,17 +1,49 @@
/* Keep technical metadata from competing with the row's name and action. */
.row {
min-height: var(--h-row);
padding-block: 2px;
padding: var(--space-1-5) var(--space-2);
}
.expand {
align-items: flex-start;
min-width: 0;
}
.expand > svg {
margin-top: var(--space-0-5);
}
.titleRow {
display: flex;
align-items: baseline;
gap: var(--space-1-5);
min-width: 0;
}
.entryTitle {
flex-shrink: 0;
min-width: 0;
color: var(--fg-strong);
font-weight: 500;
overflow-wrap: anywhere;
}
.titleRow .entryTitle {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.version {
flex: none;
max-width: 40%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.subtitle {
flex: 1;
min-width: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
@@ -20,8 +52,81 @@
white-space: nowrap;
}
.scopeSelect {
min-width: 120px;
.statusRow {
display: flex;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
color: var(--warning);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.nativeHint {
display: flex;
align-items: center;
gap: var(--space-1);
}
.nativeHint > svg,
.nativeHint > img {
flex-shrink: 0;
}
.description {
color: var(--fg);
line-height: 1.45;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.groupTitle {
flex-shrink: 0;
max-width: calc(100% - 48px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.groupPath {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rowControls {
justify-content: flex-end;
}
@container settings-content (max-width: 360px) {
.reviewRow {
flex-wrap: wrap;
}
.reviewRow .expand {
flex-basis: 100%;
}
.version {
display: none;
}
.groupToggle {
flex-wrap: wrap;
}
.groupPath {
flex-basis: 100%;
padding-left: var(--space-4);
}
.searchRow {
flex-wrap: wrap;
}
.searchRow > :first-child {
flex-basis: 100%;
}
}
.controls {
@@ -36,7 +141,7 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
@@ -54,7 +159,8 @@
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1) var(--space-3);
min-width: 0;
}
.summaryTitle {
@@ -66,12 +172,15 @@
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-app);
padding: 0;
border: 0;
background: none;
color: var(--link);
font-size: var(--fs-tiny);
font-size: var(--fs-small);
text-align: left;
min-width: 0;
max-width: 100%;
overflow-wrap: anywhere;
cursor: pointer;
}
@@ -98,14 +207,17 @@
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 7px;
border-radius: var(--radius-small);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-tiny);
min-width: 0;
max-width: 100%;
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.marketplaceChip > span:not(:first-child) {
overflow-wrap: anywhere;
min-width: 0;
}
.dialogBody {
display: flex;
flex-direction: column;
+105 -61
Переглянути файл
@@ -213,38 +213,38 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
<div className={styles.summaryBox}>
<div className={styles.summaryHeader}>
<div className={styles.summaryPills}>
<span className={styles.summaryTitle}>
<T>Active Bundle Projection</T>
</span>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", SKILLS_PAGE)}
>
{formatMessage(tx("{count} skills → Skills"), { count: catalog.projectedSkills })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MCP_PAGE)}
>
{formatMessage(tx("{count} MCP servers → MCP Connections"), { count: catalog.projectedMcpServers })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MEMORY_PAGE)}
>
{formatMessage(tx("{count} rules → Memory"), { count: catalog.projectedRules })}
</button>
</div>
<span className={styles.summaryTitle}>
<T>Active Bundle Projection</T>
</span>
{backend.addMarketplace && (
<Button size="small" onClick={() => setMarketplacesOpen(true)}>
{formatMessage(tx("Marketplaces ({count})…"), { count: catalog.marketplaces.length })}
</Button>
)}
</div>
<div className={styles.summaryPills}>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", SKILLS_PAGE)}
>
{formatMessage(tx("{count} skills → Skills"), { count: catalog.projectedSkills })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MCP_PAGE)}
>
{formatMessage(tx("{count} MCP servers → MCP Connections"), { count: catalog.projectedMcpServers })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MEMORY_PAGE)}
>
{formatMessage(tx("{count} rules → Memory"), { count: catalog.projectedRules })}
</button>
</div>
{catalog.marketplaces.length > 0 && (
<div className={styles.marketplaceRow}>
@@ -289,7 +289,7 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
/>
</div>
<div className={page.searchRow}>
<div className={clsx(page.searchRow, styles.searchRow)}>
<SearchField
className={page.search}
value={query}
@@ -322,14 +322,16 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
<div className={page.sectionBar}>
<button
type="button"
className={page.sectionToggle}
className={clsx(page.sectionToggle, styles.groupToggle)}
aria-expanded={!isCollapsed}
onClick={() => setCollapsed((prev) => ({ ...prev, [key]: !prev[key] }))}
>
<Icon name={isCollapsed ? "chevron-right" : "chevron-down"} size={14} className={page.chevron} />
<span className={page.sectionTitle}>{title}</span>
<span className={clsx(page.sectionTitle, styles.groupTitle)}>{title}</span>
<span className={page.badge}>{items.length}</span>
<span className={page.sectionHint}>{pluginGroupPath(source, scope)}</span>
<span className={clsx(page.sectionHint, styles.groupPath)} title={pluginGroupPath(source, scope)}>
{pluginGroupPath(source, scope)}
</span>
</button>
</div>
@@ -438,41 +440,55 @@ function PluginCard({
const { plugin } = state;
const summary = componentSummary(state, tx);
const group = PLUGIN_SOURCE_GROUPS[plugin.source];
const details = [summary, plugin.approxTokens > 0 ? `~${plugin.approxTokens}t` : ""].filter(Boolean).join(" · ");
const subtitle = [details, plugin.description].filter(Boolean).join(" · ");
const needsReview = state.consentRequired && !state.enabled;
return (
<div role="listitem" className={page.card}>
<div className={clsx(page.cardHeader, styles.row)}>
<button type="button" className={page.cardExpandBtn} aria-expanded={isExpanded} onClick={onToggleExpand}>
<div className={clsx(page.cardHeader, styles.row, needsReview && styles.reviewRow)}>
<button
type="button"
className={clsx(page.cardExpandBtn, styles.expand)}
aria-expanded={isExpanded}
onClick={onToggleExpand}
>
<Icon name={isExpanded ? "chevron-down" : "chevron-right"} size={13} className={page.chevron} />
<span className={styles.entryTitle}>{plugin.displayName}</span>
{plugin.version && <span className={page.tag}>v{plugin.version}</span>}
{plugin.marketplace && <span className={page.tag}>{plugin.marketplace}</span>}
{plugin.formats.map((f) => (
<span key={f} className={page.tag}>
{pluginFormatLabel(f)}
<span className={page.cardMain}>
<span className={styles.titleRow}>
<span className={styles.entryTitle} title={plugin.displayName}>
{plugin.displayName}
</span>
{plugin.version && (
<span className={styles.version} title={plugin.version}>
v{plugin.version}
</span>
)}
</span>
))}
{summary && <span className={page.tag}>{summary}</span>}
{plugin.approxTokens > 0 && <span className={page.tag}>~{plugin.approxTokens}t</span>}
{plugin.description && (
<span className={styles.subtitle} title={plugin.description}>
{plugin.description}
</span>
)}
{state.origin === "trust" && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Untrusted workspace</T>
</span>
)}
{state.consentRequired && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Approval required</T>
</span>
)}
{subtitle && (
<span className={styles.subtitle} title={subtitle}>
{subtitle}
</span>
)}
{(state.origin === "trust" || state.consentRequired) && (
<span className={styles.statusRow}>
{state.origin === "trust" && (
<span>
<T>Untrusted workspace</T>
</span>
)}
{state.consentRequired && (
<span>
<T>Approval required</T>
</span>
)}
</span>
)}
</span>
</button>
<div className={styles.controls}>
{state.consentRequired && !state.enabled ? (
<div className={clsx(styles.controls, styles.rowControls)}>
{needsReview ? (
<Button
size="small"
disabled={busy || (state.origin === "trust" && !hasTrustedProject)}
@@ -493,7 +509,34 @@ function PluginCard({
{isExpanded && (
<div className={page.cardDrawer}>
{plugin.description && <span className={styles.description}>{plugin.description}</span>}
{details && <span className={styles.hint}>{details}</span>}
<div className={page.metaGrid}>
{plugin.version && (
<>
<span className={page.metaLabel}>
<T>Version</T>
</span>
<span className={page.metaValue}>{plugin.version}</span>
</>
)}
{plugin.marketplace && (
<>
<span className={page.metaLabel}>
<T>Marketplace</T>
</span>
<span className={page.metaValue}>{plugin.marketplace}</span>
</>
)}
{plugin.formats.length > 0 && (
<>
<span className={page.metaLabel}>
<T>Format</T>
</span>
<span className={page.metaValue}>{plugin.formats.map(pluginFormatLabel).join(" · ")}</span>
</>
)}
<span className={page.metaLabel}>
<T>Scope</T>
</span>
@@ -558,7 +601,7 @@ function PluginCard({
</button>
)}
{(plugin.capabilities.hookFiles?.length ?? 0) > 0 && (
<span className={page.tag}>{(plugin.capabilities.hookFiles ?? []).join(", ")}</span>
<span className={page.metaValue}>{(plugin.capabilities.hookFiles ?? []).join(", ")}</span>
)}
</span>
@@ -573,8 +616,9 @@ function PluginCard({
</div>
{group.agent && (
<span className={styles.hint}>
<Icon name={providerIcon(group.agent)} size={12} /> {tx(group.label)} reads this bundle natively.
<span className={clsx(styles.hint, styles.nativeHint)}>
<Icon name={providerIcon(group.agent)} size={12} />
<span>{tx(group.label)} reads this bundle natively.</span>
</span>
)}
+7 -46
Переглянути файл
@@ -62,13 +62,7 @@ import { setFocusedTaskList } from "./taskListFocus";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
import {
automatedTaskVisible,
openAutomationDialog,
openAutomations,
useAutomations,
useAutomationsSync,
} from "./automationsModel";
import { automatedTaskVisible, useAutomations, useAutomationsSync } from "./automationsModel";
import styles from "./Agents.module.css";
import autoStyles from "./Automations.module.css";
import { basename, useProject } from "@/platform/project";
@@ -76,10 +70,15 @@ import { useTx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
export function AgentsHeaderActions() {
const host = useAutomations((s) => s.snapshot.host);
const hasAttention = host.unreadRuns > 0 || host.needsInputRuns > 0;
return (
<>
<IconButton icon="plus" action="agents.newTask" />
<IconButton icon="clock" action="agents.automations" />
<span className={autoStyles.headerBadgeWrap}>
<IconButton icon="clock" action="agents.automations" />
{hasAttention && <span className={autoStyles.headerBadgeDot} aria-hidden="true" />}
</span>
<IconButton icon="settings" action="agents.mcpServers" />
</>
);
@@ -179,8 +178,6 @@ export function AgentsView() {
const providers = useAgents((s) => s.providers);
const docked = useAgents((s) => s.docked);
const homeOpen = useAgents((s) => s.homeOpen);
const automationHost = useAutomations((s) => s.snapshot.host);
const automationCount = useAutomations((s) => s.snapshot.automations.length);
const automatedRunFilter = useAutomations((s) => s.automatedRunFilter);
const inline = docked !== null || homeOpen;
const historyRef = useRef<HTMLButtonElement>(null);
@@ -535,42 +532,6 @@ export function AgentsView() {
setFocusedTaskList(null);
}}
>
<div className={autoStyles.hubBar} data-testid="agents-automations-hub">
<button
type="button"
className={autoStyles.hubBtn}
onClick={() => {
setHistoryOpen(false);
openAutomations();
}}
>
<Icon name="clock" size={14} />
<span>
<T>Automations</T>
</span>
<span className={autoStyles.hubMeta}>
{automationHost.activeSchedules > 0 ? (
<span>
{automationHost.activeSchedules === 1 ? tx("1 active") : tx`${automationHost.activeSchedules} active`}
</span>
) : automationCount > 0 ? (
<span>{automationCount}</span>
) : null}
{automationHost.unreadRuns > 0 && (
<span className={clsx(autoStyles.tag, autoStyles.tagUnread)}>{automationHost.unreadRuns}</span>
)}
</span>
</button>
<IconButton
icon="plus"
size="small"
title="New Automation"
onClick={() => {
setHistoryOpen(false);
openAutomationDialog();
}}
/>
</div>
{tasks.size > 0 && (
<SearchField
className={styles.taskSearch}
+223 -168
Переглянути файл
@@ -49,9 +49,21 @@ const SCHEDULE_KIND_OPTIONS: ReadonlyArray<SelectOption<TriggerKind>> = [
];
const PERMISSION_OPTIONS: ReadonlyArray<SelectOption<AutomationPermissionMode>> = [
{ value: "assisted", label: "Accept edits (edit workspace files without asking; ask before commands)" },
{ value: "allowAll", label: "Allow all (capped by your interactive approval setting)" },
{ value: "default", label: "Ask for approval (ask before edits and commands)" },
{
value: "assisted",
label: "Accept edits",
detail: "Edit workspace files without asking; ask before commands",
},
{
value: "allowAll",
label: "Allow all",
detail: "Capped by your interactive approval setting",
},
{
value: "default",
label: "Ask for approval",
detail: "Ask before edits and commands",
},
];
const CONTINUITY_OPTIONS: ReadonlyArray<SelectOption<AutomationContinuity>> = [
@@ -178,6 +190,18 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
const [disableAfterStr, setDisableAfterStr] = useState(() =>
editing?.disableAfterMs ? toDatetimeLocalValue(editing.disableAfterMs).slice(0, 10) : "",
);
// Expand Advanced automatically when editing a schedule with non-default advanced options.
const [advancedOpen, setAdvancedOpen] = useState(() =>
Boolean(
editing &&
(editing.permissions !== "assisted" ||
editing.continuity !== "newTask" ||
editing.misfirePolicy != null ||
editing.maxRuns != null ||
editing.disableAfterMs != null ||
(editing.workspace.kind === "project" && !editing.workspace.autoCleanWorktree)),
),
);
const [fetchedBranches, setFetchedBranches] = useState<{ root: string; list: Branch[] }>({ root: "", list: [] });
const [previewState, setPreviewState] = useState<{ runs: number[]; error: string | null }>({
@@ -249,12 +273,15 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
const previewError = currentTrigger.kind === "manual" ? null : previewState.error;
const selectedProvider = providers.find((p) => p.id === providerId) ?? providers[0];
// Exclude interactive permission/approval controls here so they don't conflict with Unattended Permissions.
const providerConfig = useMemo(
() =>
(selectedProvider?.config ?? []).map((opt) => ({
...opt,
current: configMap[opt.id] ?? opt.current,
})),
(selectedProvider?.config ?? [])
.filter((opt) => opt.category !== "permissions" && opt.category !== "approval" && opt.category !== "mode")
.map((opt) => ({
...opt,
current: configMap[opt.id] ?? opt.current,
})),
[selectedProvider, configMap],
);
@@ -275,6 +302,9 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
[branches, tx],
);
const permissionSummary = tx(PERMISSION_OPTIONS.find((o) => o.value === permissions)?.label ?? "Accept edits");
const continuitySummary = continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session");
const toggleWeekday = (day: number) => {
setWeeklyDays((cur) =>
cur.includes(day) ? (cur.length > 1 ? cur.filter((d) => d !== day) : cur) : [...cur, day].sort(),
@@ -343,7 +373,7 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
open={dialog.open}
onClose={closeAutomationDialog}
title={editing ? tx("Edit Automation") : tx("New Automation")}
width={620}
width={560}
maxHeight={760}
resizable="both"
footerStart={<Checkbox checked={enabled} onChange={setEnabled} label="Active schedule" />}
@@ -395,107 +425,25 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
<label className={styles.fieldLabel} htmlFor="automation-prompt-input">
<T>Prompt Instructions</T>
</label>
<textarea
id="automation-prompt-input"
className={styles.promptTextarea}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={tx("Describe what the agent should inspect, verify, or report on each run…")}
/>
<div className={styles.pickerBar}>
<ConfigPickers
config={providerConfig}
onChange={(id, val) => setConfigMap((prev) => ({ ...prev, [id]: val }))}
<div className={styles.promptBox}>
<textarea
id="automation-prompt-input"
className={styles.promptTextarea}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={tx("Describe what the agent should inspect, verify, or report on each run…")}
/>
<McpPicker provider={providerId} overrides={mcpOverrides} onChange={setMcpOverrides} />
<SkillsPicker provider={providerId} overrides={skillOverrides} onChange={setSkillOverrides} />
<MemoryPicker provider={providerId} overrides={memoryOverrides} onChange={setMemoryOverrides} />
</div>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Workspace Target</T>
</span>
<Select
aria-label={tx("Workspace Target")}
value={workspaceMode}
options={[
...(projectRoot ? [{ value: "project", label: tx("Project workspace") }] : []),
{ value: "chatOnly", label: tx("No workspace (chat only)") },
]}
onChange={(v) => setWorkspaceMode(v as "project" | "chatOnly")}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Session Continuity</T>
</span>
<Select
aria-label={tx("Session Continuity")}
value={continuity}
options={CONTINUITY_OPTIONS}
onChange={(v) => setContinuity(v)}
/>
</div>
</div>
{workspaceMode === "project" && projectRoot && (
<div className={styles.fieldRow}>
{workspaceProjects.length > 1 ? (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Repository</T>
</span>
<Select
aria-label={tx("Repository")}
value={projectRoot}
options={workspaceProjects.map((p) => ({ value: p, label: basename(p) }))}
onChange={setProjectRoot}
/>
</div>
) : null}
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Checkout Isolation</T>
</span>
<Select
aria-label={tx("Checkout Isolation")}
value={isolation}
options={[
{ value: "worktree", label: tx("Isolated Git worktree (Recommended)") },
{ value: "local", label: tx("Local checkout") },
]}
onChange={(v) => setIsolation(v as Isolation)}
<div className={styles.promptBar}>
<ConfigPickers
config={providerConfig}
onChange={(id, val) => setConfigMap((prev) => ({ ...prev, [id]: val }))}
/>
<McpPicker provider={providerId} overrides={mcpOverrides} onChange={setMcpOverrides} />
<SkillsPicker provider={providerId} overrides={skillOverrides} onChange={setSkillOverrides} />
<MemoryPicker provider={providerId} overrides={memoryOverrides} onChange={setMemoryOverrides} />
</div>
{isolation === "worktree" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Base Branch</T>
</span>
<Select
aria-label={tx("Base Branch")}
value={baseBranch}
options={branchOptions}
onChange={setBaseBranch}
/>
</div>
)}
</div>
)}
{workspaceMode === "project" && isolation === "worktree" && continuity === "newTask" && (
<Checkbox
checked={autoCleanWorktree}
onChange={setAutoCleanWorktree}
label="Auto-delete temporary worktree when the run makes zero file changes"
/>
)}
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
@@ -604,15 +552,15 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
)}
{triggerKind !== "manual" && (
<div className={styles.previewBox} data-testid="automation-schedule-preview">
<div className={styles.previewLine} data-testid="automation-schedule-preview">
{previewError ? (
<span style={{ color: "var(--danger)" }}>{previewError}</span>
<span className={styles.previewError}>{previewError}</span>
) : previewRuns.length > 0 ? (
<>
<strong>
<span className={styles.previewLabel}>
<T>Upcoming runs:</T>
</strong>
<span>{previewRuns.map((ms) => formatShortTimestamp(ms)).join(" · ")}</span>
</span>
<span>{previewRuns.map((ms) => formatShortTimestamp(ms)).join(" · ")}</span>
</>
) : (
<span>
@@ -622,76 +570,183 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
</div>
)}
<div className={styles.fieldRow}>
<div className={styles.workspaceRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Unattended Permissions</T>
<T>Workspace Target</T>
</span>
<Select
aria-label={tx("Unattended Permissions")}
value={permissions}
options={PERMISSION_OPTIONS}
onChange={(v) => setPermissions(v)}
aria-label={tx("Workspace Target")}
value={workspaceMode}
options={[
...(projectRoot ? [{ value: "project", label: tx("Project workspace") }] : []),
{ value: "chatOnly", label: tx("No workspace (chat only)") },
]}
onChange={(v) => setWorkspaceMode(v as "project" | "chatOnly")}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Missed Schedule Policy</T>
</span>
<Select
aria-label={tx("Missed Schedule Policy")}
value={misfirePolicy}
options={MISFIRE_OPTIONS}
onChange={setMisfirePolicy}
/>
</div>
{workspaceMode === "project" && projectRoot && workspaceProjects.length > 1 && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Repository</T>
</span>
<Select
aria-label={tx("Repository")}
value={projectRoot}
options={workspaceProjects.map((p) => ({ value: p, label: basename(p) }))}
onChange={setProjectRoot}
/>
</div>
)}
{workspaceMode === "project" && projectRoot && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Checkout Isolation</T>
</span>
<Select
aria-label={tx("Checkout Isolation")}
value={isolation}
options={[
{ value: "worktree", label: tx("Isolated Git worktree"), detail: tx("Recommended") },
{ value: "local", label: tx("Local checkout") },
]}
onChange={(v) => setIsolation(v as Isolation)}
/>
</div>
)}
{workspaceMode === "project" && projectRoot && isolation === "worktree" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Base Branch</T>
</span>
<Select
aria-label={tx("Base Branch")}
value={baseBranch}
options={branchOptions}
onChange={setBaseBranch}
/>
</div>
)}
</div>
{agentSettings.newTaskApprovals === "ask" && permissions !== "default" && (
<div className={styles.fieldHint}>
<T>
Your interactive New Tasks setting is Asking for approval, so scheduled turns are capped to ask before
edits and commands.
</T>
</div>
)}
<div className={styles.advancedSection}>
<button
type="button"
className={styles.advancedToggle}
aria-expanded={advancedOpen}
onClick={() => setAdvancedOpen((v) => !v)}
>
<span className={styles.advancedTitle}>
<Icon name={advancedOpen ? "chevron-down" : "chevron-right"} size={13} />
<T>Advanced</T>
</span>
{!advancedOpen && (
<span className={styles.advancedSummary}>
{permissionSummary} · {continuitySummary}
</span>
)}
</button>
{permissions === "allowAll" && workspaceMode === "project" && isolation === "local" && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
<T>
Warning: Autonomous mode on a local checkout can modify your working files directly. Prefer an isolated
Git worktree.
</T>
</div>
)}
{advancedOpen && (
<div className={styles.advancedBody}>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Unattended Permissions</T>
</span>
<Select
aria-label={tx("Unattended Permissions")}
value={permissions}
options={PERMISSION_OPTIONS}
onChange={(v) => setPermissions(v)}
/>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-max-runs-input">
<T>Stop After Runs (optional)</T>
</label>
<Input
id="automation-max-runs-input"
type="number"
min={1}
value={maxRunsStr}
onChange={(e) => setMaxRunsStr(e.target.value)}
placeholder="50"
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Session Continuity</T>
</span>
<Select
aria-label={tx("Session Continuity")}
value={continuity}
options={CONTINUITY_OPTIONS}
onChange={(v) => setContinuity(v)}
/>
</div>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-disable-after-input">
<T>Disable After Date (optional)</T>
</label>
<Input
id="automation-disable-after-input"
type="date"
value={disableAfterStr}
onChange={(e) => setDisableAfterStr(e.target.value)}
/>
</div>
{agentSettings.newTaskApprovals === "ask" && permissions !== "default" && (
<div className={styles.fieldHint}>
<T>
Your interactive New Tasks setting is Asking for approval, so scheduled turns are capped to ask
before edits and commands.
</T>
</div>
)}
{permissions === "allowAll" && workspaceMode === "project" && isolation === "local" && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
<T>
Warning: Autonomous mode on a local checkout can modify your working files directly. Prefer an
isolated Git worktree.
</T>
</div>
)}
{workspaceMode === "project" && isolation === "worktree" && continuity === "newTask" && (
<Checkbox
checked={autoCleanWorktree}
onChange={setAutoCleanWorktree}
label="Auto-delete temporary worktree when the run makes zero file changes"
/>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Missed Schedule Policy</T>
</span>
<Select
aria-label={tx("Missed Schedule Policy")}
value={misfirePolicy}
options={MISFIRE_OPTIONS}
onChange={setMisfirePolicy}
/>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-max-runs-input">
<T>Stop After Runs (optional)</T>
</label>
<Input
id="automation-max-runs-input"
type="number"
min={1}
value={maxRunsStr}
onChange={(e) => setMaxRunsStr(e.target.value)}
placeholder="50"
/>
</div>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-disable-after-input">
<T>Disable After Date (optional)</T>
</label>
<Input
id="automation-disable-after-input"
type="date"
value={disableAfterStr}
onChange={(e) => setDisableAfterStr(e.target.value)}
/>
</div>
</div>
</div>
)}
</div>
</div>
</Dialog>
+272 -148
Переглянути файл
@@ -1,61 +1,67 @@
/* Agent Automations editor tab, creation dialog, and status widgets (Islands style). */
.editor {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
background: var(--bg-app);
overflow-y: auto;
background: var(--bg-editor);
color: var(--fg);
font-size: var(--fs-ui);
}
.column {
display: flex;
flex-direction: column;
flex: 1;
width: 100%;
max-width: 820px;
margin: 0 auto;
padding: 20px 28px 24px;
box-sizing: border-box;
min-height: 0;
}
.header {
display: flex;
align-items: center;
align-items: flex-start;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 12px 18px 10px;
border-bottom: 1px solid var(--border);
background: var(--bg-elev);
gap: var(--space-3);
padding-bottom: 14px;
}
.headerMain {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.headerTitle {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
margin: 0;
font-size: 14px;
font-size: 16px;
font-weight: 600;
letter-spacing: -0.01em;
line-height: 1.3;
color: var(--fg-strong);
}
.headerActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
flex-shrink: 0;
gap: var(--space-1);
}
.hostPill {
.hostMeta {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 22px;
padding: 0 8px;
border-radius: var(--radius-small);
background: var(--bg-floating-toolbar);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
white-space: nowrap;
flex-wrap: wrap;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
.statusDot {
@@ -78,35 +84,42 @@
background: var(--danger);
}
.tabBar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 14px;
border-bottom: 1px solid var(--border);
background: var(--bg-elev);
gap: var(--space-2);
}
.filterRow {
/* Compact navigation tabs and inline search/filter on one hairline row. */
.navRow {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 10px 18px 6px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.navControls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
margin-left: auto;
}
.searchWrap {
flex: 1;
min-width: 180px;
max-width: 360px;
width: 220px;
max-width: 100%;
min-width: 150px;
}
.filterRight {
display: flex;
.tabBadge {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
justify-content: center;
min-width: 16px;
height: 16px;
padding: 0 3px;
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-variant-numeric: tabular-nums;
line-height: 1;
}
.bannerWarn {
@@ -114,10 +127,10 @@
align-items: center;
justify-content: space-between;
gap: var(--space-2);
margin: 10px 18px 0;
margin-bottom: 12px;
padding: 8px 12px;
border-radius: var(--radius-control);
background: var(--bg-floating-toolbar);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--warning);
color: var(--fg-strong);
font-size: var(--fs-small);
@@ -132,19 +145,19 @@
.body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 8px 18px 20px;
display: flex;
flex-direction: column;
gap: var(--space-2);
gap: var(--space-3);
padding: 16px 0 20px;
min-height: 0;
}
/* Framed list with hairline dividers, matching Settings > Agents > Skills. */
.listFrame {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
background: var(--bg-editor);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
@@ -167,7 +180,7 @@
.rowFocused {
background: var(--bg-hover);
box-shadow: inset 2px 0 0 var(--link);
box-shadow: inset 2px 0 0 var(--accent);
}
.rowLeft {
@@ -201,6 +214,12 @@
text-overflow: ellipsis;
}
.rowSchedule {
color: var(--fg-secondary);
font-size: var(--fs-small);
white-space: nowrap;
}
.rowPrompt {
color: var(--fg-muted);
font-size: var(--fs-small);
@@ -215,7 +234,7 @@
flex-wrap: wrap;
gap: var(--space-1-5);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
color: var(--fg-subtle);
}
.tag {
@@ -225,7 +244,7 @@
height: 18px;
padding: 0 6px;
border-radius: var(--radius-small);
background: var(--bg-floating-toolbar);
background: var(--bg-elev);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
white-space: nowrap;
@@ -236,7 +255,7 @@
}
.tagUnread {
background: var(--link);
background: var(--accent);
color: #fff;
font-weight: 600;
}
@@ -262,15 +281,18 @@
flex-shrink: 0;
}
.emptyCard {
/* Open, cardless empty state with a single-column hairline template list. */
.emptySection {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-3);
padding: 18px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
padding-top: 4px;
}
.emptyHeader {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.emptyTitle {
@@ -284,40 +306,42 @@
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.45;
max-width: 620px;
line-height: 1.5;
max-width: 600px;
}
.templatesGrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: var(--space-2);
width: 100%;
}
.templateBtn {
.templateRow {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-1);
align-items: center;
justify-content: space-between;
gap: var(--space-3);
width: 100%;
padding: 10px 12px;
border-radius: var(--radius-control);
border: none;
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
border: 0;
background: transparent;
color: var(--fg);
font: inherit;
text-align: left;
cursor: pointer;
}
.templateBtn:hover {
.templateRow + .templateRow {
box-shadow: inset 0 1px 0 var(--border);
}
.templateRow:hover {
background: var(--bg-hover);
}
.templateMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.templateTitle {
font-weight: 600;
font-size: var(--fs-small);
font-weight: 500;
font-size: var(--fs-ui);
color: var(--fg-strong);
}
@@ -326,12 +350,28 @@
color: var(--fg-muted);
}
/* Dialog form */
.templatePlus {
flex-shrink: 0;
color: var(--fg-muted);
}
.footerBar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding-top: 12px;
border-top: 1px solid var(--border);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
/* Dialog form (aligned to Dialog's 16px titlebar / footer insets). */
.dialogForm {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 4px 0;
padding: 4px 16px 12px;
font-size: var(--fs-ui);
}
@@ -339,58 +379,109 @@
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.fieldRow {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
}
.workspaceRow {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: var(--space-2);
}
.fieldLabel {
font-size: var(--fs-small);
font-weight: 600;
color: var(--fg-strong);
font-weight: 500;
color: var(--fg-secondary);
}
.fieldHint {
font-size: var(--fs-tiny);
color: var(--fg-muted);
line-height: 1.4;
line-height: 1.45;
}
/* Unified prompt surface matching the HomeEditor composer frame. */
.promptBox {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-app));
box-shadow: inset 0 0 0 1px var(--border-button);
transition: box-shadow var(--dur-fast) var(--ease);
}
.promptBox:focus-within {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.promptTextarea {
width: 100%;
min-height: 92px;
padding: 8px 10px;
border-radius: var(--radius-control);
border: 1px solid var(--border);
background: var(--bg-app);
min-height: 84px;
padding: 8px 10px 6px;
border: 0;
background: transparent;
color: var(--fg-strong);
font-family: var(--font-ui, inherit);
font-size: var(--fs-ui);
line-height: 1.45;
line-height: 1.5;
resize: vertical;
box-sizing: border-box;
}
.promptTextarea:focus {
outline: none;
border-color: var(--link);
}
.pickerBar {
.promptTextarea::placeholder {
color: var(--fg-faint);
}
/* Standalone monospace textarea used in Import / Export markdown dialogs. */
.codeTextarea {
width: 100%;
min-height: 168px;
padding: 8px 10px;
border: 0;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-app));
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-small);
line-height: 1.5;
resize: vertical;
box-sizing: border-box;
}
.codeTextarea:focus {
outline: none;
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.promptBar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1);
padding: 4px 6px;
border-top: 1px solid var(--border);
}
.weekdayRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1);
}
.dayBtn {
@@ -398,30 +489,87 @@
min-width: 34px;
padding: 0 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border-button);
background: var(--bg-field, var(--bg-app));
color: var(--fg-secondary);
font-size: var(--fs-tiny);
cursor: pointer;
}
.dayBtn:hover {
background: var(--bg-hover);
}
.dayBtnActive {
border-color: var(--link);
background: var(--bg-hover);
box-shadow: inset 0 0 0 1px var(--accent);
background: var(--bg-selected);
color: var(--fg-strong);
font-weight: 600;
font-weight: 500;
}
.previewBox {
.previewLine {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: var(--space-1);
font-size: var(--fs-tiny);
color: var(--fg-muted);
line-height: 1.4;
}
.previewLabel {
color: var(--fg-secondary);
font-weight: 500;
}
.previewError {
color: var(--danger);
}
.advancedSection {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
padding: 7px 10px;
border-radius: var(--radius-control);
background: var(--bg-floating-toolbar);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-tiny);
border-top: 1px solid var(--border);
padding-top: 8px;
}
.advancedToggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
width: 100%;
padding: 4px 2px;
border-radius: var(--radius-small);
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 500;
text-align: left;
}
.advancedToggle:hover {
color: var(--fg-strong);
}
.advancedTitle {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
.advancedSummary {
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-weight: 400;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.advancedBody {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding-top: 10px;
}
.errorBox {
@@ -436,45 +584,21 @@
font-size: var(--fs-small);
}
/* Sidebar hub row */
.hubBar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-1-5);
padding: 4px 8px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.hubBtn {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex: 1;
min-width: 0;
padding: 3px 6px;
border: none;
border-radius: var(--radius-small);
background: none;
color: var(--fg-strong);
font: inherit;
font-size: var(--fs-small);
text-align: left;
cursor: pointer;
}
.hubBtn:hover {
background: var(--bg-hover);
}
.hubMeta {
margin-left: auto;
/* Sidebar tool window header badge dot for unread/attention runs. */
.headerBadgeWrap {
position: relative;
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
.headerBadgeDot {
position: absolute;
top: 4px;
right: 4px;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
pointer-events: none;
}
/* Session provenance banner & schedule strip */
+405 -378
Переглянути файл
@@ -293,6 +293,35 @@ export function AutomationsEditor({
}
};
const { host } = snapshot;
const projectActiveSchedules = useMemo(
() => snapshot.automations.filter((a) => a.enabled && a.trigger.kind !== "manual").length,
[snapshot.automations],
);
const headerMoreMenu = (): MenuItem[] => [
{
kind: "item",
id: "import",
label: "Import .automation.md",
icon: "download",
disabled: untrustedProject,
run: () => setImportOpen(true),
},
...(projectActiveSchedules > 0
? [
{
kind: "item" as const,
id: "pause-all",
label: "Pause All",
icon: "pause",
disabled: untrustedProject,
run: () => void handlePauseAll(),
},
]
: []),
];
const automationMenu = (auto: AgentAutomation_Serialize): MenuItem[] => [
{
kind: "item",
@@ -340,394 +369,394 @@ export function AutomationsEditor({
},
];
const { host } = snapshot;
const projectActiveSchedules = useMemo(
() => snapshot.automations.filter((a) => a.enabled && a.trigger.kind !== "manual").length,
[snapshot.automations],
);
return (
<div className={styles.editor} data-testid="automations-editor">
<div className={styles.header}>
<div className={styles.headerMain}>
<h2 className={styles.headerTitle}>
<Icon name="clock" size={16} />
<T>Agent Automations</T>
</h2>
<span className={styles.hostPill} data-testid="scheduler-host-pill">
<span
className={clsx(styles.statusDot, host.activeSchedules > 0 && styles.statusDotOn)}
aria-hidden="true"
/>
<Icon name={host.remote ? "remote" : "server"} size={12} />
<span>{host.remote ? tx("Remote Daemon") : tx("Local Host")}</span>
<span>·</span>
<span>
{host.activeSchedules === 1 ? tx("1 active schedule") : tx`${host.activeSchedules} active schedules`}
</span>
{host.bootServiceRegistered && (
<>
<span>·</span>
<span>
<T>Auto-starts on login</T>
</span>
</>
)}
</span>
</div>
<div className={styles.headerActions}>
<Button size="small" icon="download" disabled={untrustedProject} onClick={() => setImportOpen(true)}>
<T>Import .automation.md</T>
</Button>
{projectActiveSchedules > 0 && (
<Button size="small" icon="pause" disabled={untrustedProject} onClick={() => void handlePauseAll()}>
<T>Pause All</T>
</Button>
)}
<IconButton
icon="settings"
title="Automation Settings"
onClick={() => void executeAction("file.settings", AUTOMATIONS_PAGE)}
/>
<Button
variant="primary"
size="small"
icon="plus"
disabled={untrustedProject}
onClick={() => openAutomationDialog()}
>
<T>New Automation</T>
</Button>
</div>
</div>
{loadError && (
<div className={styles.errorBox} style={{ margin: "10px 18px 0" }} role="alert">
<Icon name="error" size={14} />
<span>{loadError}</span>
</div>
)}
{host.bootServiceError && (
<div className={styles.errorBox} style={{ margin: "10px 18px 0" }} role="alert">
<Icon name="warning" size={14} />
<span>{host.bootServiceError}</span>
</div>
)}
{untrustedProject && (
<div className={styles.bannerWarn} role="status">
<div className={styles.bannerLeft}>
<Icon name="warning" size={14} />
<span>
<T>This project is untrusted. Workspace automations stay paused until you trust the project.</T>
<div className={styles.column}>
<header className={styles.header}>
<div className={styles.headerMain}>
<h2 className={styles.headerTitle}>
<T>Agent Automations</T>
</h2>
<span className={styles.hostMeta} data-testid="scheduler-host-pill">
<span
className={clsx(styles.statusDot, host.activeSchedules > 0 && styles.statusDotOn)}
aria-hidden="true"
/>
{host.remote && <Icon name="remote" size={12} />}
<span>{host.remote ? tx("Remote Daemon") : tx("Local Host")}</span>
<span>·</span>
<span>
{host.activeSchedules === 1 ? tx("1 active schedule") : tx`${host.activeSchedules} active schedules`}
</span>
{host.bootServiceRegistered && (
<>
<span>·</span>
<span>
<T>Auto-starts on login</T>
</span>
</>
)}
</span>
</div>
</div>
)}
<div className={styles.tabBar}>
<Tabs
activeId={activeTab}
onSelect={(id) => setAutomationsTab(id as "schedules" | "runs")}
items={[
{
id: "schedules",
label: <T>Schedules</T>,
text: "Schedules",
trailing: snapshot.automations.length ? <span>{snapshot.automations.length}</span> : undefined,
},
{
id: "runs",
label: <T>Run History</T>,
text: "Run History",
trailing:
host.unreadRuns > 0 ? (
<span className={clsx(styles.tag, styles.tagUnread)}>{host.unreadRuns}</span>
) : snapshot.runs.length ? (
<span>{snapshot.runs.length}</span>
<div className={styles.headerActions}>
<Button
variant="primary"
size="small"
icon="plus"
disabled={untrustedProject}
onClick={() => openAutomationDialog()}
>
<T>New Automation</T>
</Button>
<IconButton
icon="settings"
title="Automation Settings"
onClick={() => void executeAction("file.settings", AUTOMATIONS_PAGE)}
/>
<IconButton icon="more" title="Options" onClick={(e) => showContextMenu(e, headerMoreMenu())} />
</div>
</header>
{loadError && (
<div className={styles.errorBox} style={{ marginBottom: 12 }} role="alert">
<Icon name="error" size={14} />
<span>{loadError}</span>
</div>
)}
{host.bootServiceError && (
<div className={styles.errorBox} style={{ marginBottom: 12 }} role="alert">
<Icon name="warning" size={14} />
<span>{host.bootServiceError}</span>
</div>
)}
{untrustedProject && (
<div className={styles.bannerWarn} role="status">
<div className={styles.bannerLeft}>
<Icon name="warning" size={14} />
<span>
<T>This project is untrusted. Workspace automations stay paused until you trust the project.</T>
</span>
</div>
</div>
)}
<div className={styles.navRow}>
<Tabs
variant="compact"
activeId={activeTab}
onSelect={(id) => setAutomationsTab(id as "schedules" | "runs")}
items={[
{
id: "schedules",
label: <T>Schedules</T>,
text: "Schedules",
trailing: snapshot.automations.length ? (
<span className={styles.tabBadge}>{snapshot.automations.length}</span>
) : undefined,
},
]}
/>
</div>
<div className={styles.filterRow}>
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
clearable
placeholder={tx("Filter automations and runs")}
aria-label={tx("Filter automations and runs")}
},
{
id: "runs",
label: <T>Run History</T>,
text: "Run History",
trailing:
host.unreadRuns > 0 ? (
<span className={clsx(styles.tag, styles.tagUnread)}>{host.unreadRuns}</span>
) : snapshot.runs.length ? (
<span className={styles.tabBadge}>{snapshot.runs.length}</span>
) : undefined,
},
]}
/>
<div className={styles.navControls}>
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
clearable
placeholder={tx("Filter automations and runs")}
aria-label={tx("Filter automations and runs")}
/>
</div>
{activeTab === "runs" && (
<>
<Select
variant="ghost"
aria-label={tx("Run filter")}
value={runFilter}
options={[
{ value: "all", label: tx("All runs") },
{ value: "unread", label: tx("Unread only") },
{ value: "needsInput", label: tx("Waiting for input") },
]}
onChange={(v) => setRunFilter(v as "all" | "unread" | "needsInput")}
/>
{host.unreadRuns > 0 && (
<Button size="small" icon="check" onClick={() => void handleMarkAllRead()}>
<T>Mark All as Read</T>
</Button>
)}
</>
)}
</div>
</div>
{activeTab === "schedules" ? (
<div className={styles.filterRight}>
<div className={styles.body}>
{activeTab === "schedules" ? (
filteredAutomations.length === 0 ? (
<div className={styles.emptySection}>
<div className={styles.emptyHeader}>
<h3 className={styles.emptyTitle}>
{query ? <T>No matching automations</T> : <T>Automate recurring agent workflows</T>}
</h3>
{!query && (
<p className={styles.emptyDesc}>
<T>
Schedules run directly on your local host or remote daemon—even when editor windows are closed
or after an OS reboot—using isolated Git worktrees so your working tree stays clean.
</T>
</p>
)}
</div>
{!query && (
<div className={styles.listFrame}>
{STARTER_TEMPLATES.map((tpl) => (
<button
key={tpl.name}
type="button"
className={styles.templateRow}
onClick={() => openAutomationDialog({ prefillName: tpl.name, prefillPrompt: tpl.prompt })}
>
<span className={styles.templateMain}>
<span className={styles.templateTitle}>{tx(tpl.name)}</span>
<span className={styles.templateSub}>{tx(tpl.sub)}</span>
</span>
<Icon name="plus" size={14} className={styles.templatePlus} />
</button>
))}
</div>
)}
</div>
) : (
<div className={styles.listFrame}>
{filteredAutomations.map((auto) => (
<div
key={auto.id}
data-testid={`automation-row-${auto.id}`}
className={clsx(styles.row, focusAutomationId === auto.id && styles.rowFocused)}
onContextMenu={(e) => showContextMenu(e, automationMenu(auto))}
>
<div className={styles.rowLeft}>
<span
className={clsx(styles.statusDot, auto.enabled && styles.statusDotOn)}
style={{ marginTop: 6 }}
title={auto.enabled ? tx("Active") : tx("Paused")}
/>
<Icon name={providerIcon(auto.provider)} size={16} label={providerName(auto.provider)} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>{auto.name}</span>
<span className={styles.rowSchedule}>{describeTrigger(auto.trigger, tx)}</span>
{!auto.enabled && (
<span className={styles.tag}>
<T>Paused</T>
</span>
)}
{auto.unreadRuns > 0 && (
<span className={clsx(styles.tag, styles.tagUnread)}>
{auto.unreadRuns === 1 ? tx("1 unread") : tx`${auto.unreadRuns} unread`}
</span>
)}
</div>
<div className={styles.rowPrompt}>{auto.prompt.text}</div>
{auto.pausedReason && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
{auto.pausedReason}
</div>
)}
<div className={styles.rowMeta}>
<span>{providerName(auto.provider)}</span>
<span>·</span>
<span>
{auto.workspace.kind === "chatOnly"
? tx("Chat only")
: auto.workspace.isolation === "worktree"
? `${basename(auto.workspace.root)} · ${tx("Worktree")}`
: `${basename(auto.workspace.root)} · ${tx("Local checkout")}`}
</span>
<span>·</span>
<span>{auto.continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session")}</span>
{auto.enabled && auto.nextRunMs ? (
<>
<span>·</span>
<span>
<T>Next:</T> {formatShortTimestamp(auto.nextRunMs)}
</span>
</>
) : null}
{auto.maxRuns ? (
<>
<span>·</span>
<span>
{auto.runCount}/{auto.maxRuns} <T>runs</T>
</span>
</>
) : null}
</div>
</div>
</div>
<div className={styles.rowActions}>
<Button
size="small"
icon="run"
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleRunNow(auto)}
>
<T>Run Now</T>
</Button>
<IconButton
icon={auto.enabled ? "pause" : "resume"}
title={auto.enabled ? "Pause Schedule" : "Resume Schedule"}
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleToggleEnabled(auto)}
/>
<IconButton
icon="edit"
title="Edit Automation"
disabled={untrustedProject}
onClick={() => openAutomationDialog({ editing: auto })}
/>
<IconButton
icon="more"
title="More Actions"
disabled={untrustedProject}
onClick={(e) => showContextMenu(e, automationMenu(auto))}
/>
</div>
</div>
))}
</div>
)
) : filteredRuns.length === 0 ? (
<div className={styles.emptySection}>
<div className={styles.emptyHeader}>
<h3 className={styles.emptyTitle}>
<T>No automation runs yet</T>
</h3>
<p className={styles.emptyDesc}>
<T>
Scheduled and manual runs appear here with diff summaries, approval badges, and one-click session
transcripts.
</T>
</p>
</div>
</div>
) : (
<div className={styles.listFrame}>
{filteredRuns.map((run) => (
<div
key={run.id}
data-testid={`automation-run-${run.id}`}
className={styles.row}
onClick={() => void handleOpenRun(run)}
>
<div className={styles.rowLeft}>
<RunStatusGlyph status={run.status} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>
{run.automationName} <span className={styles.mono}>#{run.runNumber}</span>
</span>
{run.status === "needsInput" && (
<span className={clsx(styles.tag, styles.tagWarn)}>
<Icon name="warning" size={11} />
<T>Needs approval</T>
</span>
)}
{run.unread && (
<span className={clsx(styles.tag, styles.tagUnread)}>
<T>Unread</T>
</span>
)}
{run.origin.kind === "scheduled" && run.origin.catchUp && (
<span className={styles.tag}>
<T>Catch-up</T>
</span>
)}
</div>
{run.error && (
<div className={styles.rowPrompt} style={{ color: "var(--danger)" }}>
{run.error}
</div>
)}
<div className={styles.rowMeta}>
<span>{formatShortTimestamp(run.startedMs)}</span>
<span>·</span>
<span>{run.origin.kind === "manual" ? tx("Manual run") : tx("Scheduled run")}</span>
{run.branch && (
<>
<span>·</span>
<span className={styles.mono}>{run.branch}</span>
</>
)}
{(run.added > 0 || run.removed > 0) && (
<>
<span>·</span>
<span className={styles.diffAdded}>+{run.added}</span>
<span className={styles.diffRemoved}>-{run.removed}</span>
</>
)}
{run.worktreeCleaned && (
<>
<span>·</span>
<span>
<T>Zero-diff worktree cleaned</T>
</span>
</>
)}
</div>
</div>
</div>
<div className={styles.rowActions} onClick={(e) => e.stopPropagation()}>
{run.unread && (
<IconButton
icon="check"
title="Mark as Read"
onClick={() => void backend.markRead(run.id, null).then(() => refreshAutomations(backend))}
/>
)}
{run.taskId && (
<Button size="small" onClick={() => void handleOpenRun(run)}>
<T>Open Session</T>
</Button>
)}
</div>
</div>
))}
{snapshot.runsNextCursor != null && (
<div className={styles.row} style={{ justifyContent: "center" }}>
<Button size="small" onClick={() => void loadMoreRuns(backend)}>
<T>Show more</T>
</Button>
</div>
)}
</div>
)}
</div>
{activeTab === "schedules" && (
<div className={styles.footerBar}>
<Checkbox
checked={autoStartEnabled}
onChange={(v) => void handleToggleAutoStart(v)}
label="Keep automations running when OpenIDEA is closed"
/>
</div>
) : (
<div className={styles.filterRight}>
<Select
aria-label={tx("Run filter")}
value={runFilter}
options={[
{ value: "all", label: tx("All runs") },
{ value: "unread", label: tx("Unread only") },
{ value: "needsInput", label: tx("Waiting for input") },
]}
onChange={(v) => setRunFilter(v as "all" | "unread" | "needsInput")}
/>
{host.unreadRuns > 0 && (
<Button size="small" icon="check" onClick={() => void handleMarkAllRead()}>
<T>Mark All as Read</T>
</Button>
)}
</div>
)}
</div>
<div className={styles.body}>
{activeTab === "schedules" ? (
filteredAutomations.length === 0 ? (
<div className={styles.emptyCard}>
<h3 className={styles.emptyTitle}>
{query ? <T>No matching automations</T> : <T>Automate recurring agent workflows</T>}
</h3>
{!query && (
<>
<p className={styles.emptyDesc}>
<T>
Schedules run directly on your local host or remote daemon—even when editor windows are closed or
after an OS reboot—using isolated Git worktrees so your working tree stays clean.
</T>
</p>
<div className={styles.templatesGrid}>
{STARTER_TEMPLATES.map((tpl) => (
<button
key={tpl.name}
type="button"
className={styles.templateBtn}
onClick={() => openAutomationDialog({ prefillName: tpl.name, prefillPrompt: tpl.prompt })}
>
<span className={styles.templateTitle}>{tx(tpl.name)}</span>
<span className={styles.templateSub}>{tx(tpl.sub)}</span>
</button>
))}
</div>
</>
)}
</div>
) : (
<div className={styles.listFrame}>
{filteredAutomations.map((auto) => (
<div
key={auto.id}
data-testid={`automation-row-${auto.id}`}
className={clsx(styles.row, focusAutomationId === auto.id && styles.rowFocused)}
onContextMenu={(e) => showContextMenu(e, automationMenu(auto))}
>
<div className={styles.rowLeft}>
<span
className={clsx(styles.statusDot, auto.enabled && styles.statusDotOn)}
style={{ marginTop: 6 }}
title={auto.enabled ? tx("Active") : tx("Paused")}
/>
<Icon name={providerIcon(auto.provider)} size={16} label={providerName(auto.provider)} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>{auto.name}</span>
<span className={styles.tag}>{describeTrigger(auto.trigger, tx)}</span>
{!auto.enabled && (
<span className={styles.tag}>
<T>Paused</T>
</span>
)}
{auto.unreadRuns > 0 && (
<span className={clsx(styles.tag, styles.tagUnread)}>
{auto.unreadRuns === 1 ? tx("1 unread") : tx`${auto.unreadRuns} unread`}
</span>
)}
</div>
<div className={styles.rowPrompt}>{auto.prompt.text}</div>
{auto.pausedReason && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
{auto.pausedReason}
</div>
)}
<div className={styles.rowMeta}>
<span>{providerName(auto.provider)}</span>
<span>·</span>
<span>
{auto.workspace.kind === "chatOnly"
? tx("Chat only")
: auto.workspace.isolation === "worktree"
? `${basename(auto.workspace.root)} · ${tx("Worktree")}`
: `${basename(auto.workspace.root)} · ${tx("Local checkout")}`}
</span>
<span>·</span>
<span>{auto.continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session")}</span>
{auto.enabled && auto.nextRunMs ? (
<>
<span>·</span>
<span>
<T>Next:</T> {formatShortTimestamp(auto.nextRunMs)}
</span>
</>
) : null}
{auto.maxRuns ? (
<>
<span>·</span>
<span>
{auto.runCount}/{auto.maxRuns} <T>runs</T>
</span>
</>
) : null}
</div>
</div>
</div>
<div className={styles.rowActions}>
<Button
size="small"
icon="run"
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleRunNow(auto)}
>
<T>Run Now</T>
</Button>
<IconButton
icon={auto.enabled ? "pause" : "resume"}
title={auto.enabled ? "Pause Schedule" : "Resume Schedule"}
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleToggleEnabled(auto)}
/>
<IconButton
icon="edit"
title="Edit Automation"
disabled={untrustedProject}
onClick={() => openAutomationDialog({ editing: auto })}
/>
<IconButton
icon="more"
title="More Actions"
disabled={untrustedProject}
onClick={(e) => showContextMenu(e, automationMenu(auto))}
/>
</div>
</div>
))}
</div>
)
) : filteredRuns.length === 0 ? (
<div className={styles.emptyCard}>
<h3 className={styles.emptyTitle}>
<T>No automation runs yet</T>
</h3>
<p className={styles.emptyDesc}>
<T>
Scheduled and manual runs appear here with diff summaries, approval badges, and one-click session
transcripts.
</T>
</p>
</div>
) : (
<div className={styles.listFrame}>
{filteredRuns.map((run) => (
<div
key={run.id}
data-testid={`automation-run-${run.id}`}
className={styles.row}
onClick={() => void handleOpenRun(run)}
style={{ cursor: run.taskId ? "pointer" : "default" }}
>
<div className={styles.rowLeft}>
<RunStatusGlyph status={run.status} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>
{run.automationName} <span className={styles.mono}>#{run.runNumber}</span>
</span>
{run.status === "needsInput" && (
<span className={clsx(styles.tag, styles.tagWarn)}>
<Icon name="warning" size={11} />
<T>Needs approval</T>
</span>
)}
{run.unread && (
<span className={clsx(styles.tag, styles.tagUnread)}>
<T>Unread</T>
</span>
)}
{run.origin.kind === "scheduled" && run.origin.catchUp && (
<span className={styles.tag}>
<T>Catch-up</T>
</span>
)}
</div>
{run.error && (
<div className={styles.rowPrompt} style={{ color: "var(--danger)" }}>
{run.error}
</div>
)}
<div className={styles.rowMeta}>
<span>{formatShortTimestamp(run.startedMs)}</span>
<span>·</span>
<span>{run.origin.kind === "manual" ? tx("Manual run") : tx("Scheduled run")}</span>
{run.branch && (
<>
<span>·</span>
<span className={styles.mono}>{run.branch}</span>
</>
)}
{(run.added > 0 || run.removed > 0) && (
<>
<span>·</span>
<span className={styles.diffAdded}>+{run.added}</span>
<span className={styles.diffRemoved}>-{run.removed}</span>
</>
)}
{run.worktreeCleaned && (
<>
<span>·</span>
<span>
<T>Zero-diff worktree cleaned</T>
</span>
</>
)}
</div>
</div>
</div>
<div className={styles.rowActions} onClick={(e) => e.stopPropagation()}>
{run.unread && (
<IconButton
icon="check"
title="Mark as Read"
onClick={() => void backend.markRead(run.id, null).then(() => refreshAutomations(backend))}
/>
)}
{run.taskId && (
<Button size="small" onClick={() => void handleOpenRun(run)}>
<T>Open Session</T>
</Button>
)}
</div>
</div>
))}
{snapshot.runsNextCursor != null && (
<div className={styles.row} style={{ justifyContent: "center" }}>
<Button size="small" onClick={() => void loadMoreRuns(backend)}>
<T>Show more</T>
</Button>
</div>
)}
</div>
)}
</div>
@@ -770,8 +799,7 @@ export function AutomationsEditor({
</span>
<textarea
aria-label={tx("Automation Markdown")}
className={styles.promptTextarea}
style={{ minHeight: 160, fontFamily: "var(--font-mono)" }}
className={styles.codeTextarea}
value={importText}
onChange={(e) => setImportText(e.target.value)}
placeholder={
@@ -802,8 +830,7 @@ export function AutomationsEditor({
<textarea
readOnly
aria-label={tx("Exported Automation Markdown")}
className={styles.promptTextarea}
style={{ minHeight: 180, fontFamily: "var(--font-mono)" }}
className={styles.codeTextarea}
value={exportState?.markdown ?? ""}
/>
</div>
+62
Переглянути файл
@@ -32,6 +32,7 @@ import { isRemoteWindow } from "@/platform/remote";
import { isMacHost, registerKeyClaim } from "@/platform/keymap";
import { isVirtualUri } from "@/platform/virtualDocs";
import { copySourceOf } from "@/platform/clipboardSource";
import { readClipboardText } from "@/platform/clipboard";
import { blobLink, blobPathCandidates, isRemoteOf, markdownLink, pastedUrl } from "./composerLinks";
import {
EDITOR_TAB_MIME,
@@ -53,6 +54,7 @@ import {
listNavigate,
fileIconName,
registerDropTarget,
showContextMenu,
} from "@/ui";
import {
IMAGE_EXTENSIONS,
@@ -295,6 +297,7 @@ export function Composer(props: ComposerProps) {
// Late-bound handlers: the editor is created once per draft, the props change every render.
const onKeyDownRef = useRef<(e: KeyboardEvent, view: EditorView) => boolean>(() => false);
const onPasteRef = useRef<(e: ClipboardEvent, view: EditorView) => boolean>(() => false);
const onContextMenuRef = useRef<(e: MouseEvent, view: EditorView) => boolean>(() => false);
const onUpdateRef = useRef<(u: ViewUpdate) => void>(() => {});
useLayoutEffect(() => {
@@ -319,6 +322,7 @@ export function Composer(props: ComposerProps) {
EditorView.domEventHandlers({
keydown: (e, v) => onKeyDownRef.current(e, v),
paste: (e, v) => onPasteRef.current(e, v),
contextmenu: (e, v) => onContextMenuRef.current(e, v),
}),
),
referenceExtensions(),
@@ -1106,6 +1110,63 @@ export function Composer(props: ComposerProps) {
return false;
};
// Menu actions have no native paste event, so use the same transformations explicitly.
const onContextMenu = (e: MouseEvent, view: EditorView): boolean => {
const hasSelection = !view.state.selection.main.empty;
showContextMenu(e, [
...(hasSelection
? [
{
label: "Cut",
icon: "cut",
run: () => {
view.focus();
document.execCommand("cut");
},
},
{
label: "Copy",
icon: "copy",
run: () => {
view.focus();
document.execCommand("copy");
},
},
]
: []),
{
label: "Paste",
icon: "paste",
run: () =>
void (async () => {
try {
const plain = await readClipboardText();
if (!view.dom.isConnected) return;
if (plain) {
if (
!pasteCopied(plain, view) &&
!pasteLink(plain, view) &&
!pastePath(plain, view) &&
!pasteLong(plain, view)
) {
view.dispatch(view.state.replaceSelection(plain), { userEvent: "input.paste", scrollIntoView: true });
}
view.focus();
} else if (isTauri()) {
await pasteClipboardImage();
} else {
view.focus();
document.execCommand("paste");
}
} catch (error) {
notifications().notify({ level: "error", title: tx("Cannot paste"), body: String(error) });
}
})(),
},
]);
return true;
};
// Files dropped from the OS onto the box: images are inlined when they can be, other files
// referenced, or attached by path when outside the project.
useEffect(() => {
@@ -1284,6 +1345,7 @@ export function Composer(props: ComposerProps) {
useLayoutEffect(() => {
onUpdateRef.current = onUpdate;
onPasteRef.current = onPaste;
onContextMenuRef.current = onContextMenu;
onKeyDownRef.current = onKeyDown;
});
+21 -1
Переглянути файл
@@ -6,7 +6,7 @@ import { trackEditorCopies } from "./references";
import userEvent from "@testing-library/user-event";
import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting";
import chipStyles from "./ReferenceChip.module.css";
import { FILES_DRAG, dragSession } from "@/ui";
import { FILES_DRAG, dragSession, useContextMenuStore } from "@/ui";
import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
@@ -97,6 +97,26 @@ beforeEach(() => {
);
});
// Menu paste must take the same path conversion as a keyboard paste.
it("pastes a project path from the context menu", async () => {
const box = renderComposer();
vi.stubGlobal("navigator", { ...navigator, clipboard: { readText: vi.fn().mockResolvedValue("/p/src/a.ts:3-5") } });
try {
fireEvent.contextMenu(box);
const item = useContextMenuStore
.getState()
.menu?.items.find((entry) => "label" in entry && entry.label === "Paste");
expect(item && "run" in item && item.run).toBeTruthy();
await act(async () => {
if (item && "run" in item) item.run?.();
});
expect(textOf(box)).toContain("@src/a.ts:3-5");
} finally {
vi.unstubAllGlobals();
useContextMenuStore.setState({ menu: null });
}
});
describe("Composer dropped paths", () => {
function drop(box: HTMLElement, payload: string) {
const restore = document.elementFromPoint;
+4
Переглянути файл
@@ -233,6 +233,8 @@ export function interruptionBannerText(reason: InterruptionReason, wasWaitingFor
return "Interrupted when the OpenIDEA backend stopped.";
case "unexpectedExit":
return "Interrupted when OpenIDEA exited unexpectedly.";
case "cursorCapacity":
return "Cursor is still at capacity. Automatic retries have stopped.";
case "networkTimeout":
return "Paused after the network retry window expired.";
}
@@ -252,6 +254,8 @@ export function recoveryDividerLabel(reason: InterruptionReason): string {
return "Resumed after backend stop";
case "unexpectedExit":
return "Resumed after unexpected exit";
case "cursorCapacity":
return "Retry after Cursor capacity limit";
case "networkTimeout":
return "Resumed after network drop";
}
+33
Переглянути файл
@@ -386,6 +386,39 @@ describe("inline Interrupted banner, Waiting for network banner, and RecoveryTur
await vi.waitFor(() => expect(backend.cancel).toHaveBeenCalledWith("n1"));
});
it("shows the retry number during backoff and offers Retry once Cursor is still at capacity", async () => {
const task = makeTask("cursor-retry", {
provider: "cursor",
status: "running",
retry: { attempt: 2, maxRetries: 3, retryAtMs: Date.now() + 15_000, error: null },
});
const view = render(<WorkingRow task={task} entries={[]} subagent={null} />);
expect(screen.getByText(/retrying in .*s \(attempt 2\/3\)/)).toBeVisible();
const paused = {
...task,
status: "ready" as const,
retry: null,
interrupted: { reason: "cursorCapacity" as const, atMs: Date.now() },
};
useAgents.setState({ tasks: new Map([[paused.id, paused]]) });
view.rerender(
<SessionComposer
task={paused}
focusRequest={0}
focusRoot={{ current: null }}
entries={[]}
head={null}
changes={null}
commits={[]}
onOpenChanges={() => {}}
onOpenSubagent={() => {}}
/>,
);
expect(screen.getByText("Cursor is still at capacity. Automatic retries have stopped.")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith(paused.id));
});
it("renders synthetic recovery User entries as a compact separator pill instead of a chat bubble", () => {
const t = makeTask("m1");
const drafts = { current: new Map() };
+2 -2
Переглянути файл
@@ -122,7 +122,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
<span className={styles.bannerMeta}>{age(intr.atMs ?? 0)}</span>
</span>
<div className={styles.bannerActions}>
<RecoveryWindowPicker task={task} />
{intr.reason !== "cursorCapacity" && <RecoveryWindowPicker task={task} />}
<Button
size="small"
variant="primary"
@@ -141,7 +141,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
.finally(() => setResuming(false));
}}
>
<T>Resume</T>
{intr.reason === "cursorCapacity" ? <T>Retry</T> : <T>Resume</T>}
</Button>
<IconButton
icon="close"
+3 -2
Переглянути файл
@@ -36,11 +36,12 @@ describe("clampSelectionToRow", () => {
expect(selection.toString()).toBe("Last");
});
it("collapses a selection made entirely outside the row", () => {
it("leaves a selection moved entirely outside the row in place", () => {
const { reply, next } = conversation();
const selection = document.getSelection()!;
selection.setBaseAndExtent(next, 0, next, 4);
clampSelectionToRow(selection, reply);
expect(selection.isCollapsed).toBe(true);
expect(selection.toString()).toBe("Next");
expect(selection.anchorNode).toBe(next);
});
});
+3 -5
Переглянути файл
@@ -13,11 +13,9 @@ export function clampSelectionToRow(selection: Selection | null, row: Element) {
const first = texts[0];
const last = texts.at(-1);
if (!first || !last) return;
if (!startInside && !endInside) {
// The whole selection went past the row: none of the row's text is in it.
selection.collapse(last, last.length);
return;
}
// A deferred multi-click handler can run after the selection moved elsewhere. Moving it
// back to this row would also make the browser scroll to the stale selection.
if (!startInside && !endInside) return;
const [startNode, startOffset] = startInside ? [range.startContainer, range.startOffset] : [first, 0];
const [endNode, endOffset] = endInside ? [range.endContainer, range.endOffset] : [last, last.length];
const backward = selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset;
+2 -1
Переглянути файл
@@ -352,12 +352,13 @@ function UserMessage({
const [editWidth, setEditWidth] = useState<number | null>(null);
const bubbleRef = useRef<HTMLDivElement>(null);
if (entry.recovery) {
const attempt = entry.retryAttempt;
return (
<div className={styles.recoveryDivider} role="separator">
<span className={styles.recoveryRule} aria-hidden="true" />
<span className={styles.recoveryPill}>
<Icon name="agent-resume" size={12} />
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
<span>{attempt != null ? tx`Retry ${attempt}` : tx(recoveryDividerLabel(entry.recovery))}</span>
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
</span>
<span className={styles.recoveryRule} aria-hidden="true" />
+19 -2
Переглянути файл
@@ -2,6 +2,7 @@ import type { AgentEntry, AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { Icon, IconButton, Spinner, T } from "@/ui";
import { AnsiStream, spanStyle } from "@/ui/ansi";
import clsx from "clsx";
import { memo, useLayoutEffect } from "react";
import { AgentReply } from "../AgentReply";
@@ -108,6 +109,16 @@ export function pathInTitle(title: string, path: string): { from: number; to: nu
return { from, to: at + name.length + (end < 0 ? rest.length : end) };
}
function ToolOutput({ text }: { text: string }) {
if (!text.includes("\x1b")) return text;
return new AnsiStream().parse(text).map((span, index) => (
// oxlint-disable-next-line react/no-array-index-key -- ANSI spans follow their order in the output.
<span key={index} style={spanStyle(span)}>
{span.text}
</span>
));
}
export const ToolEntry = memo(function ToolEntry({
task,
entry,
@@ -240,10 +251,16 @@ export const ToolEntry = memo(function ToolEntry({
<pre className={styles.terminalCommand}>
<span className={styles.prompt}>$</span> {commandText}
</pre>
{run?.output && <pre className={styles.terminalOutput}>{run.output}</pre>}
{run?.output && (
<pre className={styles.terminalOutput}>
<ToolOutput text={run.output} />
</pre>
)}
</div>
) : (
<pre className={styles.output}>{entry.output}</pre>
<pre className={styles.output}>
<ToolOutput text={entry.output} />
</pre>
)}
</Fold>
</div>
+10
Переглянути файл
@@ -1272,6 +1272,16 @@ describe("scrolling", () => {
});
describe("tool calls", () => {
it.each(["pnpm dev:app", null])("renders ANSI diagnostics with command %s", (command) => {
const output = "\x1b[1m\x1b[33mwarning\x1b[0m: 未使用的字段\n\x1b[94m12 |\x1b[0m authors";
const entry = tool("cargo", { kind: "execute", status: "running", command, output });
useAgents.setState({ entries: new Map([["A", [entry]]]) });
render(<SessionEditor input={input("A")} />);
const warning = screen.getByText("warning");
expect(warning.style.color).toBe("var(--ansi-yellow)");
expect(warning.closest("pre")?.textContent).toBe("warning: 未使用的字段\n12 | authors");
});
it.each(["pending", "running"] as const)("keeps %s tools in their run, named on its summary", async (status) => {
backend.entries.set("A", [tool("done one"), tool("done two"), tool("live", { status, output: "Reading files…" })]);
useAgents.setState({ entries: new Map(backend.entries) });
+4
Переглянути файл
@@ -49,3 +49,7 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.view .inline {
flex-direction: row;
align-items: center;
}
+77 -17
Переглянути файл
@@ -7,9 +7,13 @@ import { useEffect, useState } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { Button, Input } from "@/ui";
import { compareVersions, useCentral } from "./central";
import { ensureDotnetModel, useDotnet } from "./store";
import { SourcesPanel } from "./SourcesPanel";
import styles from "./Nuget.module.css";
const baseName = (path: string) => path.replace(/\\/g, "/").split("/").pop() ?? path;
export function NugetView() {
const s = useDotnet();
const tx = useTx();
@@ -17,20 +21,66 @@ export function NugetView() {
const results = new Map<string, string[]>();
for (const p of s.found) results.set(p.id, [...new Set([...(results.get(p.id) ?? []), p.version])]);
const project = s.model.projects.find((p) => p.path === s.selected);
const central = useCentral();
const matches =
central.project === s.selected && central.framework === s.framework && central.configuration === s.configuration;
const info = matches ? central.info : null;
const working = s.busy || central.busy;
const knownLatest = (p: { id: string; version: string }) => {
const latest = matches ? central.latest[p.id.toLowerCase()] : undefined;
return latest && compareVersions(latest, p.version) > 0 ? latest : undefined;
};
const note = (p: { id: string; version: string; transitive?: boolean }) => {
const key = p.id.toLowerCase();
const override = info?.overrides[key];
const file = baseName(info?.versions[key]?.file ?? "");
const latest = knownLatest(p);
return [
override ? tx`Version override ${override} in the project` : "",
!override && file ? (p.transitive ? tx`Pinned in ${file}` : tx`Defined in ${file}`) : "",
latest ? tx`Newer version available: ${latest}` : "",
]
.filter(Boolean)
.join(" · ");
};
const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg);
// The workspace scan used to run when the standalone .NET window opened; without it the
// window shows no project to manage packages for.
useEffect(() => {
void ensureDotnetModel();
}, []);
// Where versions live (Directory.Packages.props, VersionOverride) follows the selected project.
useEffect(() => {
if (s.selected) void executeAction("dotnet.centralRefresh");
}, [s.selected, s.framework, s.configuration]);
return (
<div className={styles.view}>
<div className={styles.toolbar}>
<Button disabled={s.busy} onClick={() => action("packages")}>
{tx("Refresh packages")}
</Button>
{s.busy && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
<Button disabled={working || !project} onClick={() => action("checkUpdates")}>
{tx("Check for updates")}
</Button>
<label className={styles.inline}>
<input
type="checkbox"
checked={central.prerelease}
disabled={working}
onChange={(e) => useCentral.setState({ prerelease: e.target.checked })}
/>
{tx("Include prereleases")}
</label>
{working && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
</div>
{matches && central.error && (
<div role="alert" className={styles.error}>
{central.error}
</div>
)}
{info?.enabled && (
<div role="status">{tx("Central package management is on: versions are set in Directory.Packages.props.")}</div>
)}
{s.error && (
<div role="alert" className={styles.error}>
{s.error}
@@ -54,6 +104,7 @@ export function NugetView() {
</label>
{project && (
<>
<SourcesPanel project={project.path} />
<form
className={styles.toolbar}
onSubmit={(e) => {
@@ -97,23 +148,32 @@ export function NugetView() {
})}
</ul>
<ul className={styles.list}>
{s.packages.map((p) => (
<li key={`${p.id}:${p.version}`}>
<span>
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
</span>
{!p.transitive && (
<>
<Button disabled={s.busy} onClick={() => action("search", { query: p.id, exact: true })}>
{tx("Versions")}
{s.packages.map((p) => {
const latest = knownLatest(p);
return (
<li key={`${p.id}:${p.version}`}>
<span>
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
{note(p) && ` · ${note(p)}`}
</span>
{latest && !p.transitive && (project?.frameworks.length ?? 0) <= 1 && (
<Button disabled={working} onClick={() => action("packageChange", { id: p.id, version: latest })}>
{tx`Update to ${latest}`}
</Button>
<Button disabled={s.busy} onClick={() => action("packageChange", { id: p.id, version: null })}>
{tx("Remove")}
</Button>
</>
)}
</li>
))}
)}
{!p.transitive && (
<>
<Button disabled={s.busy} onClick={() => action("search", { query: p.id, exact: true })}>
{tx("Versions")}
</Button>
<Button disabled={s.busy} onClick={() => action("packageChange", { id: p.id, version: null })}>
{tx("Remove")}
</Button>
</>
)}
</li>
);
})}
</ul>
</>
)}
+65
Переглянути файл
@@ -0,0 +1,65 @@
import { afterEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import * as actions from "@/platform/actions";
import * as dotnet from "@/platform/dotnet";
import { useProject } from "@/platform/project";
import { resetSources, useSources } from "./sources";
import { SourcesPanel } from "./SourcesPanel";
import { resetDotnet, useDotnet } from "./store";
afterEach(() => {
cleanup();
resetSources();
resetDotnet();
useProject.setState({ project: null });
vi.restoreAllMocks();
});
function show() {
const run = vi.spyOn(actions, "executeAction").mockResolvedValue(undefined as never);
useProject.setState({ project: { root: "/w" } as never });
useDotnet.setState({
selected: "/w/App.csproj",
model: { projects: [{ path: "/w/App.csproj" } as never], solutions: [] },
});
vi.spyOn(dotnet, "dotnet").mockResolvedValue("");
useSources.setState({
project: "/w/App.csproj",
sources: [
{ name: "local", url: "/feed", enabled: true },
{ name: "priv", url: "https://***@h.example/i.json", enabled: false },
],
configs: [
{ path: "/w/NuGet.Config", scope: "workspace", exists: true },
{ path: "/home/u/NuGet.Config", scope: "user", exists: true },
],
target: "/w/NuGet.Config",
targetNames: ["local", "priv"],
});
render(<SourcesPanel project="/w/App.csproj" />);
return run;
}
it("shows state and masked URLs, and toggles and removes by name", () => {
const run = show();
expect(screen.getByText(/priv.*https:\/\/\*\*\*@h\.example/)).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Disable" }));
fireEvent.click(screen.getByRole("button", { name: "Enable" }));
fireEvent.click(screen.getAllByRole("button", { name: "Remove" })[0]!);
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "disable", name: "local" });
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "enable", name: "priv" });
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "remove", name: "local" });
});
it("warns before the user-wide file is the write target and adds a source", async () => {
const run = show();
expect(screen.queryByRole("status")).toBeNull();
fireEvent.change(screen.getByLabelText("NuGet.Config file"), { target: { value: "/home/u/NuGet.Config" } });
expect(screen.getByRole("status").textContent).toMatch(/every project/);
fireEvent.change(screen.getByLabelText("Source name"), { target: { value: "n" } });
fireEvent.change(screen.getByLabelText("Source URL or folder"), { target: { value: "/f" } });
const add = screen.getByRole<HTMLButtonElement>("button", { name: "Add source" });
await waitFor(() => expect(add.disabled).toBe(false));
fireEvent.click(add);
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "add", name: "n", url: "/f" });
});
+85
Переглянути файл
@@ -0,0 +1,85 @@
/** Package sources of the selected project's NuGet.Config hierarchy (#7420). */
import { useEffect, useState } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { Button, Input } from "@/ui";
import { selectSourceConfig, useSources } from "./sources";
import styles from "./Nuget.module.css";
export function SourcesPanel({ project }: { project: string }) {
const s = useSources();
const tx = useTx();
const [name, setName] = useState("");
const [url, setUrl] = useState("");
const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg);
useEffect(() => {
action("sources");
}, [project]);
const target = s.configs.find((c) => c.path === s.target);
return (
<details>
<summary>{tx("Package sources")}</summary>
{s.error && (
<div role="alert" className={styles.error}>
{s.error}
</div>
)}
<ul className={styles.list} aria-label={tx("Package sources")}>
{s.sources.map((p) => (
<li key={p.name}>
<span>
{p.name} {p.enabled ? "" : tx("Disabled")} {p.url}
</span>
<Button
disabled={s.busy || !s.targetNames.includes(p.name)}
onClick={() => action("sourceChange", { op: p.enabled ? "disable" : "enable", name: p.name })}
>
{p.enabled ? tx("Disable") : tx("Enable")}
</Button>
<Button
disabled={s.busy || !s.targetNames.includes(p.name)}
onClick={() => action("sourceChange", { op: "remove", name: p.name })}
>
{tx("Remove")}
</Button>
</li>
))}
</ul>
{s.sources.some((source) => !s.targetNames.includes(source.name)) && (
<p>{tx("Choose the NuGet.Config file that defines this source to change it.")}</p>
)}
<label>
{tx("Write changes to")}
<select
aria-label={tx("NuGet.Config file")}
value={s.target}
disabled={s.busy}
onChange={(e) => void selectSourceConfig(e.target.value)}
>
{s.configs.map((c) => (
<option key={c.path} value={c.path}>
{c.scope === "user" ? tx`User-wide: ${c.path}` : c.path}
</option>
))}
</select>
</label>
{target?.scope === "user" && <div role="status">{tx("This file applies to every project of this user.")}</div>}
<form
className={styles.toolbar}
onSubmit={(e) => {
e.preventDefault();
action("sourceChange", { op: "add", name, url });
setName("");
setUrl("");
}}
>
<Input aria-label={tx("Source name")} value={name} onChange={(e) => setName(e.target.value)} />
<Input aria-label={tx("Source URL or folder")} value={url} onChange={(e) => setUrl(e.target.value)} />
<Button type="submit" disabled={s.busy || !name.trim() || !url.trim()}>
{tx("Add source")}
</Button>
</form>
<div>{tx("Credentials are handled by dotnet and its credential providers; the IDE does not store them.")}</div>
</details>
);
}
+150
Переглянути файл
@@ -0,0 +1,150 @@
// @vitest-environment node
/** Central package management against the real `dotnet` CLI (SDK 10 and 11) and a local folder feed. */
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import { checkUpdates, refreshCentral, resetCentral, useCentral } from "./central";
import { type Sandbox, cliSdks, sandbox } from "./cliTestkit";
import { changePackage, resetDotnet, useDotnet } from "./store";
// Each test packs or restores with the real CLI, slower on a loaded machine.
vi.setConfig({ testTimeout: 240_000 });
const sdks = cliSdks();
it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => {
expect(process.env.CI).toBeFalsy();
});
const PROPS = (versions: string, extra = "") =>
`<Project><PropertyGroup><ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>${extra}</PropertyGroup><ItemGroup>${versions}</ItemGroup></Project>`;
describe.each(sdks)("central package management with SDK %s", (sdk) => {
let sb: Sandbox;
let app: string;
let csproj: string;
const props = () => join(sb.root, "Directory.Packages.props");
/** A workspace whose only source is the local feed; the project lives two folders below the props file. */
const workspace = (ref: string, central: string | null, feedPackages = true) => {
const feed = join(sb.root, "feed");
if (feedPackages) {
sb.pack(feed, "Demo.Pkg", ["1.0.0", "1.1.0", "2.0.0-beta.1"]);
sb.pack(feed, "Child.Pkg", ["1.0.0", "1.1.0"]);
sb.pack(feed, "Parent.Pkg", ["1.0.0"], [["Child.Pkg", "1.0.0"]]);
}
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /></packageSources></configuration>`,
);
if (central) writeFileSync(props(), central);
app = join(sb.root, "src", "app");
mkdirSync(app, { recursive: true });
csproj = join(app, "App.csproj");
writeFileSync(
csproj,
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${sb.major}.0</TargetFramework></PropertyGroup><ItemGroup>${ref}</ItemGroup></Project>`,
);
sb.ok(["restore", csproj], app);
// The store's `dotnet()` runs the real CLI in the sandbox; project evaluation is not under test here.
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd));
vi.spyOn(platform, "evaluateProject").mockResolvedValue({
path: csproj,
frameworks: [`net${sb.major}.0`],
} as never);
useDotnet.setState({ selected: csproj, model: { projects: [{ path: csproj } as never], solutions: [] } });
};
beforeEach(() => {
sb = sandbox(sdk);
});
afterEach(() => {
sb.dispose();
resetCentral();
resetDotnet();
vi.restoreAllMocks();
});
it("finds Directory.Packages.props in a parent folder, shows the newer version and Update writes the props file", async () => {
workspace(
`<PackageReference Include="Demo.Pkg" />`,
PROPS(`<PackageVersion Include="Demo.Pkg" Version="1.0.0" />`),
);
await refreshCentral();
const { info } = useCentral.getState();
expect(useCentral.getState().error).toBe("");
expect(info!.enabled).toBe(true);
expect(info!.versions["demo.pkg"]).toEqual({ version: "1.0.0", file: props() });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "1.1.0" });
await changePackage("Demo.Pkg", "1.1.0");
expect(useDotnet.getState().error).toBe("");
expect(readFileSync(props(), "utf8")).toContain('Version="1.1.0"');
expect(readFileSync(csproj, "utf8")).not.toMatch(/Version=/);
await checkUpdates();
expect(useCentral.getState().latest).toEqual({});
}, 240_000);
it("a VersionOverride stays in the project and Update rewrites it there, not the props file", async () => {
workspace(
`<PackageReference Include="Demo.Pkg" VersionOverride="1.0.0" />`,
PROPS(
`<PackageVersion Include="Demo.Pkg" Version="1.0.0" />`,
`<CentralPackageVersionOverrideEnabled>true</CentralPackageVersionOverrideEnabled>`,
),
);
await refreshCentral();
expect(useCentral.getState().info!.overrides).toEqual({ "demo.pkg": "1.0.0" });
await checkUpdates();
expect(useCentral.getState().latest["demo.pkg"]).toBe("1.1.0");
await changePackage("Demo.Pkg", "1.1.0");
expect(readFileSync(csproj, "utf8")).toContain('VersionOverride="1.1.0"');
expect(readFileSync(props(), "utf8")).toContain('Version="1.0.0"');
}, 240_000);
it("without central management the version stays in the project and nothing is marked as central", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.0.0" />`, null);
await refreshCentral();
expect(useCentral.getState().info).toMatchObject({ enabled: false, versions: {}, overrides: {} });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "1.1.0" });
await changePackage("Demo.Pkg", "1.1.0");
expect(readFileSync(csproj, "utf8")).toContain('Version="1.1.0"');
}, 240_000);
it("prereleases count only when asked, and a prerelease in use is compared with its newer releases", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.1.0" />`, null);
await checkUpdates();
expect(useCentral.getState().latest).toEqual({});
useCentral.setState({ prerelease: true });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "2.0.0-beta.1" });
}, 240_000);
it("transitive pinning: a PackageVersion for an unreferenced package pins the transitive one", async () => {
workspace(
`<PackageReference Include="Parent.Pkg" />`,
PROPS(
`<PackageVersion Include="Parent.Pkg" Version="1.0.0" /><PackageVersion Include="Child.Pkg" Version="1.1.0" />`,
`<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>`,
),
);
await refreshCentral();
const { info } = useCentral.getState();
expect(info!.pinning).toBe(true);
expect(info!.versions["child.pkg"]!.file).toBe(props());
const listed = sb.ok(["list", csproj, "package", "--include-transitive", "--format", "json"], app);
expect(listed).toMatch(/"id":\s*"Child.Pkg"[^}]*"resolvedVersion":\s*"1\.1\.0"/);
}, 240_000);
it("reports the CLI error for a malformed project and keeps the previous state", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.0.0" />`, null);
await refreshCentral();
writeFileSync(csproj, "<Project Sdk=");
await refreshCentral();
expect(useCentral.getState().error).not.toBe("");
expect(useCentral.getState().busy).toBe(false);
}, 240_000);
});
+138
Переглянути файл
@@ -0,0 +1,138 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import {
cancelCentral,
checkUpdates,
compareVersions,
parseCentral,
parseOutdated,
refreshCentral,
resetCentral,
useCentral,
} from "./central";
import { resetDotnet, useDotnet } from "./store";
afterEach(() => {
resetCentral();
resetDotnet();
vi.restoreAllMocks();
});
describe("central package state", () => {
it("reports where each PackageVersion is defined and any VersionOverride", () => {
const info = parseCentral({
Properties: { ManagePackageVersionsCentrally: "true", CentralPackageTransitivePinningEnabled: "True" },
Items: {
PackageVersion: [
{ Identity: "Demo.Pkg", Version: "1.0.0", DefiningProjectFullPath: "/r/Directory.Packages.props" },
],
PackageReference: [{ Identity: "Other", VersionOverride: "2.0.0" }, { Identity: "Demo.Pkg" }],
},
});
expect(info).toEqual({
enabled: true,
pinning: true,
versions: { "demo.pkg": { version: "1.0.0", file: "/r/Directory.Packages.props" } },
overrides: { other: "2.0.0" },
});
});
it("ignores the items when central management is off", () => {
const info = parseCentral({
Properties: { ManagePackageVersionsCentrally: "" },
Items: { PackageVersion: [{ Identity: "X", Version: "1" }] },
});
expect(info.enabled).toBe(false);
expect(info.versions).toEqual({});
});
});
describe("outdated packages", () => {
it("keeps the newest latest version across target frameworks and skips current packages", () => {
const latest = parseOutdated({
projects: [
{
frameworks: [
{
topLevelPackages: [
{ id: "A", resolvedVersion: "1.0.0", latestVersion: "1.2.0" },
{ id: "B", resolvedVersion: "2.0.0", latestVersion: "2.0.0" },
],
},
{
topLevelPackages: [{ id: "A", resolvedVersion: "1.0.0", latestVersion: "1.10.0" }],
transitivePackages: [{ id: "T", resolvedVersion: "1", latestVersion: "1.1" }],
},
],
},
],
});
expect(latest).toEqual({ a: "1.10.0", t: "1.1" });
});
it("orders versions by SemVer precedence", () => {
expect(compareVersions("1.10.0", "1.2.0")).toBeGreaterThan(0);
expect(compareVersions("2.0.0", "2.0.0-beta.1")).toBeGreaterThan(0);
expect(compareVersions("2.0.0-beta.10", "2.0.0-beta.2")).toBeGreaterThan(0);
expect(compareVersions("2.0.0-beta", "2.0.0-beta.1")).toBeLessThan(0);
expect(compareVersions("1.0", "1.0.0")).toBe(0);
expect(compareVersions("1.0.0+a", "1.0.0+b")).toBe(0);
});
});
describe("running", () => {
const select = () =>
useDotnet.setState({
selected: "/r/App.csproj",
model: { projects: [{ path: "/r/App.csproj" } as never], solutions: [] },
});
it("surfaces a CLI failure and clears busy", async () => {
select();
vi.spyOn(platform, "dotnet").mockRejectedValue(new Error("MSB4025: The project file could not be loaded"));
await refreshCentral();
expect(useCentral.getState().error).toMatch(/MSB4025/);
expect(useCentral.getState().busy).toBe(false);
});
it("drops a result that arrives after cancellation or a workspace switch", async () => {
select();
let done!: (s: string) => void;
vi.spyOn(platform, "dotnet").mockImplementation(() => new Promise((r) => (done = r)));
const first = checkUpdates();
cancelCentral();
done('{"projects":[]}');
await first;
expect(useCentral.getState().checked).toBe(false);
const second = checkUpdates();
resetCentral();
done('{"projects":[]}');
await second;
expect(useCentral.getState().checked).toBe(false);
expect(useCentral.getState().busy).toBe(false);
});
it("checks versions while the newly opened tool window loads metadata", async () => {
select();
let finish!: (value: string) => void;
vi.spyOn(platform, "dotnet").mockImplementation((args) =>
args[0] === "list"
? new Promise((resolve) => {
finish = resolve;
})
: Promise.resolve('{"Properties":{"ManagePackageVersionsCentrally":"true"}}'),
);
const checking = checkUpdates();
await refreshCentral();
expect(useCentral.getState().info?.enabled).toBe(true);
expect(useCentral.getState().busy).toBe(true);
finish('{"projects":[]}');
await checking;
expect(useCentral.getState().checked).toBe(true);
});
it("passes --include-prerelease only when asked", async () => {
select();
const run = vi.spyOn(platform, "dotnet").mockResolvedValue('{"projects":[]}');
await checkUpdates();
expect(run.mock.calls[0]![0]).not.toContain("--include-prerelease");
useCentral.setState({ prerelease: true });
await checkUpdates();
expect(run.mock.calls[1]![0]).toContain("--include-prerelease");
});
});
+198
Переглянути файл
@@ -0,0 +1,198 @@
import { create } from "zustand";
import { dotnet, jsonOutput } from "@/platform/dotnet";
import { dirname, useProject } from "@/platform/project";
import { selectedProject, useDotnet } from "./store";
export interface CentralInfo {
/** `ManagePackageVersionsCentrally` is on for the project. */
enabled: boolean;
/** `CentralPackageTransitivePinningEnabled`: a `PackageVersion` also pins transitive packages. */
pinning: boolean;
/** Where each `PackageVersion` is written: the file that defines it (`Directory.Packages.props` or an import). */
versions: Record<string, { version: string; file: string }>;
/** `VersionOverride` on a `PackageReference` in the project: the project, not the central file, owns the version. */
overrides: Record<string, string>;
}
interface State {
project: string;
framework: string;
configuration: string;
info: CentralInfo | null;
/** Latest version per package id from `dotnet list package --outdated`; absent when up to date or not checked. */
latest: Record<string, string>;
checked: boolean;
prerelease: boolean;
busy: boolean;
error: string;
}
const byId = <T>(): Record<string, T> => Object.create(null) as Record<string, T>;
const initial: State = {
project: "",
framework: "",
configuration: "",
info: null,
latest: byId<string>(),
checked: false,
prerelease: false,
busy: false,
error: "",
};
export const useCentral = create<State>(() => initial);
type Query = "metadata" | "updates";
const pending = new Map<Query, AbortController>();
export function resetCentral() {
cancelCentral();
pending.clear();
useCentral.setState(initial);
}
export function cancelCentral() {
for (const controller of pending.values()) controller.abort();
}
interface Item {
Identity: string;
Version?: string;
VersionOverride?: string;
DefiningProjectFullPath?: string;
}
interface MsbuildJson {
Properties?: Record<string, string>;
Items?: { PackageVersion?: Item[]; PackageReference?: Item[] };
}
/** `dotnet msbuild -getProperty -getItem`: the evaluated central state, with the file each version comes from. */
export function parseCentral(data: MsbuildJson): CentralInfo {
const on = (v?: string) => v?.toLowerCase() === "true";
const info: CentralInfo = {
enabled: on(data.Properties?.ManagePackageVersionsCentrally),
pinning: on(data.Properties?.CentralPackageTransitivePinningEnabled),
versions: byId<{ version: string; file: string }>(),
overrides: byId<string>(),
};
if (!info.enabled) return info;
for (const v of data.Items?.PackageVersion ?? [])
info.versions[v.Identity.toLowerCase()] = { version: v.Version ?? "", file: v.DefiningProjectFullPath ?? "" };
for (const r of data.Items?.PackageReference ?? [])
if (r.VersionOverride) info.overrides[r.Identity.toLowerCase()] = r.VersionOverride;
return info;
}
interface OutdatedJson {
projects?: Array<{
frameworks?: Array<{
topLevelPackages?: Array<{ id: string; latestVersion?: string; resolvedVersion?: string }>;
transitivePackages?: Array<{ id: string; latestVersion?: string; resolvedVersion?: string }>;
}>;
}>;
}
/** The newest `latestVersion` per package across the project's target frameworks. */
export function parseOutdated(data: OutdatedJson): Record<string, string> {
const latest = byId<string>();
for (const p of data.projects ?? [])
for (const f of p.frameworks ?? [])
for (const pkg of [...(f.topLevelPackages ?? []), ...(f.transitivePackages ?? [])])
if (pkg.latestVersion && pkg.resolvedVersion && compareVersions(pkg.latestVersion, pkg.resolvedVersion) > 0) {
const key = pkg.id.toLowerCase();
if (!latest[key] || compareVersions(pkg.latestVersion, latest[key]) > 0) latest[key] = pkg.latestVersion;
}
return latest;
}
/** SemVer precedence: numeric core, then a release outranks its prereleases. */
export function compareVersions(a: string, b: string): number {
const [coreA = "", preA] = a.split("+")[0]!.split(/-(.*)/s);
const [coreB = "", preB] = b.split("+")[0]!.split(/-(.*)/s);
const na = coreA.split(".").map(Number);
const nb = coreB.split(".").map(Number);
for (let i = 0; i < Math.max(na.length, nb.length); i++) {
const d = (na[i] ?? 0) - (nb[i] ?? 0);
if (d) return d;
}
if (preA === undefined || preB === undefined) return preA === preB ? 0 : preA === undefined ? 1 : -1;
const ia = preA.toLowerCase().split(".");
const ib = preB.toLowerCase().split(".");
for (let i = 0; i < Math.max(ia.length, ib.length); i++) {
const x = ia[i];
const y = ib[i];
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
const nx = /^\d+$/.test(x);
const ny = /^\d+$/.test(y);
if (nx && ny) {
if (Number(x) !== Number(y)) return Number(x) - Number(y);
} else if (nx !== ny) return nx ? -1 : 1;
else if (x !== y) return x < y ? -1 : 1;
}
return 0;
}
async function run(query: Query, work: (signal: AbortSignal, path: string) => Promise<Partial<State>>) {
const project = selectedProject();
if (!project) return;
const path = project.path;
const root = useProject.getState().project?.root;
const { framework, configuration } = useDotnet.getState();
const contextChanged = () => {
const current = useDotnet.getState();
return (
current.selected !== path ||
current.framework !== framework ||
current.configuration !== configuration ||
useProject.getState().project?.root !== root
);
};
pending.get(query)?.abort();
const abort = new AbortController();
pending.set(query, abort);
const stopIfChanged = () => {
if (contextChanged()) abort.abort();
};
const stopProject = useProject.subscribe(stopIfChanged);
const stopSelection = useDotnet.subscribe(stopIfChanged);
const previous = useCentral.getState();
const sameContext =
previous.project === path && previous.framework === framework && previous.configuration === configuration;
useCentral.setState(
sameContext
? { busy: true, error: "" }
: { ...initial, project: path, framework, configuration, busy: true, prerelease: previous.prerelease },
);
try {
const patch = await work(abort.signal, path);
if (pending.get(query) === abort && !abort.signal.aborted) useCentral.setState(patch);
} catch (e) {
if (pending.get(query) === abort && !abort.signal.aborted) useCentral.setState({ error: String(e) });
} finally {
stopProject();
stopSelection();
if (pending.get(query) === abort) {
pending.delete(query);
useCentral.setState({ busy: pending.size > 0 });
}
}
}
export function refreshCentral() {
const { framework, configuration } = useDotnet.getState();
return run("metadata", async (signal, path) => {
const out = await dotnet(
[
"msbuild",
path,
`-p:Configuration=${configuration}`,
...(framework ? [`-p:TargetFramework=${framework}`] : []),
"-getProperty:ManagePackageVersionsCentrally,CentralPackageTransitivePinningEnabled",
"-getItem:PackageVersion,PackageReference",
],
dirname(path),
signal,
);
return { info: parseCentral(jsonOutput<MsbuildJson>(out)) };
});
}
export function checkUpdates() {
return run("updates", async (signal, path) => {
const args = ["list", path, "package", "--outdated", "--format", "json"];
if (useCentral.getState().prerelease) args.push("--include-prerelease");
const out = await dotnet(args, dirname(path), signal);
return { latest: parseOutdated(jsonOutput<OutdatedJson>(out)), checked: true };
});
}
+102
Переглянути файл
@@ -0,0 +1,102 @@
/**
* Runs the real `dotnet` CLI for tests: an isolated HOME (so the user-wide NuGet.Config and
* the package cache are the test's own), one SDK picked per run through `global.json`, and a
* local folder feed packed on the fly so nothing reaches nuget.org.
*
* With `CI` set a missing SDK fails the run instead of skipping it, so a runner without .NET
* cannot pass these tests silently.
*/
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/** Installed SDK versions whose major version is one of `majors` (10 and 11 are the ones tested). */
export function cliSdks(majors: number[] = [10, 11]): string[] {
const out = spawnSync("dotnet", ["--list-sdks"], { encoding: "utf8" });
if (out.status !== 0) {
if (process.env.CI) throw new Error("dotnet is required in CI but was not found");
return [];
}
const versions = out.stdout
.split(/\r?\n/)
.map((l) => l.split(" ")[0]!)
.filter((v) => majors.includes(Number(v.split(".")[0])));
// One SDK per major: the newest installed one.
return majors.flatMap((m) => versions.filter((v) => v.startsWith(`${m}.`)).slice(-1));
}
export interface Sandbox {
/** Workspace root; its global.json pins the SDK. */
root: string;
/** The test's HOME: holds the user-wide NuGet.Config. */
home: string;
major: number;
run(args: string[], cwd?: string): { code: number; out: string };
/** Like `run` but throws on a non-zero exit, as the IDE's `dotnet()` does. */
ok(args: string[], cwd?: string): string;
/** Packs `id` at each version into `feed` (a local folder feed). */
pack(feed: string, id: string, versions: string[], deps?: Array<[id: string, version: string]>): void;
dispose(): void;
}
export function sandbox(sdk: string): Sandbox {
// realpath: the CLI prints resolved paths (macOS /var -> /private/var).
const base = realpathSync(mkdtempSync(join(tmpdir(), "oi-nuget-")));
const root = join(base, "ws");
const home = join(base, "home");
mkdirSync(root);
mkdirSync(home);
writeFileSync(join(root, "global.json"), JSON.stringify({ sdk: { version: sdk, rollForward: "disable" } }));
const major = Number(sdk.split(".")[0]);
const env = {
...process.env,
HOME: home,
USERPROFILE: home,
APPDATA: join(home, "AppData"),
DOTNET_CLI_HOME: home,
NUGET_PACKAGES: join(base, "packages"),
DOTNET_CLI_UI_LANGUAGE: "en",
DOTNET_NOLOGO: "1",
DOTNET_CLI_TELEMETRY_OPTOUT: "1",
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1",
MSBUILDDISABLENODEREUSE: "1",
};
const run = (args: string[], cwd = root) => {
const r = spawnSync("dotnet", args, { cwd, env, encoding: "utf8", timeout: 180_000 });
return { code: r.status ?? -1, out: `${r.stdout}${r.stderr}` };
};
const ok = (args: string[], cwd = root) => {
const r = run(args, cwd);
if (r.code !== 0) throw new Error(`dotnet ${args.join(" ")} exited with ${r.code}\n${r.out}`);
return r.out;
};
return {
root,
home,
major,
run,
ok,
pack(feed, id, versions, deps = []) {
const dir = join(base, `pack-${id}`);
mkdirSync(dir, { recursive: true });
mkdirSync(feed, { recursive: true });
writeFileSync(
join(dir, `${id}.csproj`),
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${major}.0</TargetFramework>` +
`<IncludeBuildOutput>false</IncludeBuildOutput><DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences><EnableDefaultItems>false</EnableDefaultItems><GenerateAssemblyInfo>false</GenerateAssemblyInfo><GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute><NoWarn>NU5128;NU5127</NoWarn>` +
`</PropertyGroup><ItemGroup><None Include="content.txt" Pack="true" PackagePath="content/" />` +
deps.map(([d, v]) => `<PackageReference Include="${d}" Version="${v}" />`).join("") +
`</ItemGroup></Project>`,
);
// Only the feed itself (for dependencies): the user's and the test's sources stay out of packing.
writeFileSync(
join(dir, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="feed" value="${feed}" /></packageSources></configuration>`,
);
writeFileSync(join(dir, "content.txt"), id);
for (const v of versions) ok(["pack", dir, "-p:PackageVersion=" + v, "-o", feed, "--nologo"], dir);
},
dispose: () => rmSync(base, { recursive: true, force: true }),
};
}
+72 -2
Переглянути файл
@@ -3,6 +3,7 @@ import { useProject } from "@/platform/project";
import { lazyComponent } from "@/ui";
import { registerMenuGroup, registerToolWindow, toolWindowService } from "@/workbench/contributions";
import {
useDotnet,
buildDotnet,
cancelDotnet,
changePackage,
@@ -10,11 +11,14 @@ import {
installTrx,
listPackages,
reloadDotnet,
ensureDotnetModel,
resetDotnet,
runTests,
searchPackages,
selectDotnet,
} from "./store";
import { cancelCentral, checkUpdates, refreshCentral, resetCentral, useCentral } from "./central";
import { cancelSources, changeSource, loadSources, resetSources, type SourceOperation } from "./sources";
import {
addProjectReference,
addProjectsToSolution,
@@ -54,6 +58,8 @@ export function activate() {
category: "Build",
run: () => {
cancelDotnet();
cancelSources();
cancelCentral();
cancelDotnetEdit();
},
},
@@ -142,7 +148,65 @@ export function activate() {
hidden: true,
run: ({ arg }) => {
const a = arg as { id: string; version: string | null };
return changePackage(a.id, a.version);
// A change can write Directory.Packages.props or the project: re-read where versions live.
const project = useDotnet.getState().selected;
const checked = useCentral.getState().project === project && useCentral.getState().checked;
return Promise.resolve(changePackage(a.id, a.version))
.then(() => (useDotnet.getState().selected === project ? refreshCentral() : undefined))
.then(() => (checked && useDotnet.getState().selected === project ? checkUpdates() : undefined));
},
},
{
id: "dotnet.centralRefresh",
title: "Refresh Central Package Management",
category: "Build",
hidden: true,
run: () => refreshCentral(),
},
{
id: "dotnet.checkUpdates",
title: "Check NuGet Package Updates",
category: "Build",
when: "projectOpen",
run: async () => {
toolWindowService().show(NUGET, true);
const root = useProject.getState().project?.root;
await ensureDotnetModel();
if (useProject.getState().project?.root === root) return checkUpdates();
},
},
{
id: "dotnet.sources",
title: "Refresh NuGet Package Sources",
category: "Build",
hidden: true,
run: () => loadSources(),
},
{
id: "dotnet.sourceChange",
title: "Change NuGet Package Source",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { op: SourceOperation; name: string; url?: string };
return changeSource(a.op, a.name, a.url);
},
},
{
id: "dotnet.sources",
title: "Refresh NuGet Package Sources",
category: "Build",
hidden: true,
run: () => loadSources(),
},
{
id: "dotnet.sourceChange",
title: "Change NuGet Package Source",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { op: SourceOperation; name: string; url?: string };
return changeSource(a.op, a.name, a.url);
},
},
{
@@ -170,7 +234,11 @@ export function activate() {
},
]),
useProject.subscribe((s, old) => {
if (s.project?.root !== old.project?.root) resetDotnet();
if (s.project?.root !== old.project?.root) {
resetDotnet();
resetSources();
resetCentral();
}
}),
// #5635: build / restore / clean act on the right-clicked solution or project.
registerMenuGroup({
@@ -193,6 +261,8 @@ export function activate() {
];
return () => {
resetDotnet();
resetSources();
resetCentral();
disposers.reverse().forEach((d) => d());
};
}
+159
Переглянути файл
@@ -0,0 +1,159 @@
// @vitest-environment node
/** Package sources against the real `dotnet` CLI (SDK 10 and 11) and a local folder feed. */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import { commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { cliSdks, type Sandbox, sandbox } from "./cliTestkit";
import {
changeSource,
configChoices,
loadSources,
parseConfigPaths,
parseSources,
resetSources,
useSources,
} from "./sources";
import { resetDotnet, useDotnet } from "./store";
// Each test packs or restores with the real CLI, slower on a loaded machine.
vi.setConfig({ testTimeout: 120_000 });
const sdks = cliSdks();
it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => {
expect(process.env.CI).toBeFalsy();
});
describe.each(sdks)("package sources with SDK %s", (sdk) => {
let sb: Sandbox;
let app: string;
beforeEach(() => {
sb = sandbox(sdk);
app = join(sb.root, "app");
mkdirSync(app);
writeFileSync(
join(app, "App.csproj"),
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${sb.major}.0</TargetFramework></PropertyGroup></Project>`,
);
});
afterEach(() => {
sb.dispose();
resetSources();
resetDotnet();
vi.restoreAllMocks();
});
const list = (cwd = app) => parseSources(sb.ok(["nuget", "list", "source", "--format", "detailed"], cwd));
const paths = (cwd = app) => parseConfigPaths(sb.ok(["nuget", "config", "paths"], cwd));
it("lists a disabled source, a local folder and masks nothing it was never given (<clear /> in the workspace file)", () => {
mkdirSync(join(sb.root, "feed"), { recursive: true });
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /><add key="priv" value="https://example.invalid/v3/index.json" /></packageSources>` +
`<disabledPackageSources><add key="priv" value="true" /></disabledPackageSources>` +
`<packageSourceCredentials><priv><add key="Username" value="bob" /><add key="ClearTextPassword" value="s3cret-pw" /></priv></packageSourceCredentials></configuration>`,
);
const sources = list();
expect(sources.map((s) => [s.name, s.enabled])).toEqual([
["local", true],
["priv", false],
]);
expect(JSON.stringify(sources)).not.toContain("s3cret-pw");
expect(paths().some((p) => p.endsWith("NuGet.Config") && p.includes("ws"))).toBe(true);
});
it("merges levels: a nearer file adds to the user-wide one and the workspace file is the default target", () => {
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><add key="ws" value="./feed" /></packageSources></configuration>`,
);
// The user-wide file is created by the CLI on first use; add a user source through it.
sb.ok(["nuget", "add", "source", "https://user.example.invalid/i.json", "-n", "user-feed"], app);
const names = list().map((s) => s.name);
expect(names).toEqual(expect.arrayContaining(["ws", "user-feed"]));
const choices = configChoices(paths(), sb.root);
expect(choices[0]).toMatchObject({ scope: "workspace", exists: true });
expect(choices.at(-1)!.scope).toBe("user");
expect(choices.at(-1)!.path.startsWith(sb.home)).toBe(true);
});
it("creates the workspace file when none exists and adds, disables, enables and removes through the store", async () => {
const empty = sandbox(sdk);
try {
const proj = join(empty.root, "p");
mkdirSync(proj);
writeFileSync(join(proj, "P.csproj"), "<Project />");
mkdirSync(join(empty.root, "feed"));
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => empty.ok(args, cwd));
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, b64) => {
writeFileSync(path, Buffer.from(b64, "base64"));
return { status: "ok", data: null };
});
useProject.setState({ project: { root: empty.root } as never });
useDotnet.setState({
selected: join(proj, "P.csproj"),
model: { projects: [{ path: join(proj, "P.csproj") } as never], solutions: [] },
});
await loadSources();
expect(useSources.getState().error).toBe("");
const target = join(empty.root, "NuGet.Config").replace(/\\/g, "/");
expect(useSources.getState().target).toBe(target);
expect(existsSync(target)).toBe(false);
await changeSource("add", "local", join(empty.root, "feed"));
expect(useSources.getState().error).toBe("");
expect(readFileSync(target, "utf8")).toContain('key="local"');
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true);
await changeSource("disable", "local");
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(false);
await changeSource("enable", "local");
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true);
await changeSource("remove", "local");
expect(useSources.getState().sources.some((s) => s.name === "local")).toBe(false);
// The created file carries no <clear />: the user-wide nuget.org source stays in effect.
expect(useSources.getState().sources.map((s) => s.name)).toContain("nuget.org");
} finally {
empty.dispose();
}
});
it("blocks edits to a source absent from the selected config and keeps the list", async () => {
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd));
useProject.setState({ project: { root: sb.root } as never });
useDotnet.setState({
selected: join(app, "App.csproj"),
model: { projects: [{ path: join(app, "App.csproj") } as never], solutions: [] },
});
await loadSources();
const before = useSources.getState().sources;
await changeSource("remove", "no-such-source");
expect(useSources.getState().error).toContain("Choose the NuGet.Config file that defines this source");
expect(useSources.getState().sources).toEqual(before);
expect(useSources.getState().busy).toBe(false);
});
it("search and install keep using the effective sources (a local feed packed here)", () => {
const feed = join(sb.root, "feed");
sb.pack(feed, "Demo.Pkg", ["1.0.0", "2.0.0-beta.1"]);
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /></packageSources></configuration>`,
);
expect(sb.ok(["package", "search", "Demo.Pkg", "--format", "json"], app)).toContain("Demo.Pkg");
sb.ok(["add", join(app, "App.csproj"), "package", "Demo.Pkg", "--version", "1.0.0"], app);
expect(readFileSync(join(app, "App.csproj"), "utf8")).toContain("Demo.Pkg");
}, 240_000);
it("fails with the CLI's message when the SDK is missing or the file is malformed", () => {
const bad = join(sb.root, "bad");
mkdirSync(bad, { recursive: true });
writeFileSync(join(bad, "NuGet.Config"), "<configuration><packageSources>");
const r = sb.run(["nuget", "list", "source", "--format", "detailed"], bad);
expect(r.code).not.toBe(0);
expect(r.out).toMatch(/NuGet\.Config|XML|configuration/i);
});
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import { configChoices, maskUrl, parseConfigPaths, parseSources, sourceArgs } from "./sources";
describe("package source parsing", () => {
it("reads enabled and disabled sources, names with spaces and local folders", () => {
const text = [
"Registered Sources:",
"",
" 1. nuget.org [Enabled]",
" https://api.nuget.org/v3/index.json",
" 2. My Feed [Disabled]",
" /srv/feed",
"",
].join("\n");
expect(parseSources(text)).toEqual([
{ name: "nuget.org", url: "https://api.nuget.org/v3/index.json", enabled: true },
{ name: "My Feed", url: "/srv/feed", enabled: false },
]);
});
it("reads CRLF output and an empty list", () => {
expect(parseSources("Registered Sources:\r\n\r\n 1. a [Enabled]\r\n /f\r\n")).toHaveLength(1);
expect(parseSources("No sources found.\n")).toEqual([]);
});
it("masks credentials embedded in a source URL", () => {
expect(maskUrl("https://user:[email protected]/v3/index.json")).toBe(
"https://***@pkgs.example.com/v3/index.json",
);
expect(maskUrl("https://[email protected]/i.json")).toBe("https://***@pkgs.example.com/i.json");
expect(maskUrl("https://pkgs.example.com/a@b")).toBe("https://pkgs.example.com/a@b");
const [source] = parseSources(" 1. p [Enabled]\n https://u:[email protected]/i.json\n");
expect(source!.url).not.toContain("ClearTextPassword");
});
it("reads the config path list, ignoring other lines", () => {
expect(parseConfigPaths("/w/NuGet.Config\nC:\\Users\\a\\NuGet.Config\nwarning: x\n")).toEqual([
"/w/NuGet.Config",
"C:\\Users\\a\\NuGet.Config",
]);
});
});
describe("choosing the NuGet.Config to write", () => {
it("defaults to the workspace file nearest the root, user-wide files last", () => {
expect(
configChoices(["/w/app/NuGet.Config", "/w/NuGet.Config", "/home/u/.nuget/NuGet/NuGet.Config"], "/w"),
).toEqual([
{ path: "/w/NuGet.Config", scope: "workspace", exists: true },
{ path: "/w/app/NuGet.Config", scope: "workspace", exists: true },
{ path: "/home/u/.nuget/NuGet/NuGet.Config", scope: "user", exists: true },
]);
});
it("offers a new root file when no workspace file exists, never defaulting to the user file", () => {
const [first, second] = configChoices(["/home/u/.nuget/NuGet/NuGet.Config"], "/w");
expect(first).toEqual({ path: "/w/NuGet.Config", scope: "workspace", exists: false });
expect(second!.scope).toBe("user");
});
it("keeps distinct POSIX directories separate", () => {
const files = configChoices(["/home/user/project/NuGet.Config"], "/home/user/Project");
expect(files.map((file) => file.scope)).toEqual(["workspace", "user"]);
});
it("matches Windows paths case-insensitively", () => {
expect(configChoices(["c:\\Repo\\nuget.config"], "C:\\Repo")[0]!.scope).toBe("workspace");
});
});
describe("dotnet nuget arguments", () => {
it("always names the file", () => {
expect(sourceArgs("add", "/w/NuGet.Config", "n", "/f")).toEqual([
"nuget",
"add",
"source",
"/f",
"--name",
"n",
"--configfile",
"/w/NuGet.Config",
]);
expect(sourceArgs("disable", "/w/NuGet.Config", "n")).toEqual([
"nuget",
"disable",
"source",
"n",
"--configfile",
"/w/NuGet.Config",
]);
});
});
+210
Переглянути файл
@@ -0,0 +1,210 @@
import { create } from "zustand";
import { call, commands, IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { toBase64 } from "@/platform/base64";
import { dotnet } from "@/platform/dotnet";
import { dirname, useProject } from "@/platform/project";
import { selectedProject, useDotnet } from "./store";
export interface PackageSource {
name: string;
url: string;
enabled: boolean;
}
export interface ConfigFile {
path: string;
/** Where the file lives: next to the project, or in the user / machine-wide hierarchy. */
scope: "workspace" | "user";
/** False for the `NuGet.Config` offered next to the root when no file exists yet. */
exists: boolean;
}
interface State {
sources: PackageSource[];
configs: ConfigFile[];
/** The NuGet.Config the next add / enable / disable / remove writes to. */
target: string;
targetNames: string[];
project: string;
busy: boolean;
error: string;
}
const initial: State = { sources: [], configs: [], target: "", targetNames: [], project: "", busy: false, error: "" };
export const useSources = create<State>(() => initial);
let controller: AbortController | undefined;
let generation = 0;
export function resetSources() {
generation++;
controller?.abort();
useSources.setState(initial);
}
/** A password or token written into a source URL (`https://user:secret@host`) is never shown. */
export function maskUrl(url: string): string {
return url.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi, "$1***@");
}
/** `dotnet nuget list source --format detailed`: a numbered `name [Enabled|Disabled]` line, then the URL line. */
export function parseSources(text: string): PackageSource[] {
const result: PackageSource[] = [];
const lines = text.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const head = /^\s*\d+\.\s+(.+?)\s+\[(Enabled|Disabled)(?:,[^\]]*)?\]\s*$/.exec(lines[i]!);
if (!head) continue;
result.push({ name: head[1]!, url: maskUrl((lines[i + 1] ?? "").trim()), enabled: head[2] === "Enabled" });
}
return result;
}
/** `dotnet nuget config paths`: one file per line, nearest first. */
export function parseConfigPaths(text: string): string[] {
return text
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(l));
}
const norm = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
function inside(path: string, dir: string): boolean {
const file = norm(path);
const root = norm(dir);
if (/^[a-z]:$|^[a-z]:\/|^\/\//i.test(root)) return file.toLowerCase().startsWith(`${root.toLowerCase()}/`);
return file.startsWith(`${root}/`);
}
/**
* The files a source can be written to: those under the workspace root, nearest to the
* root first, with `<root>/NuGet.Config` offered (and created on first write) when none
* exists, then the user-wide ones. The default is the first workspace file.
*/
export function configChoices(paths: string[], root: string): ConfigFile[] {
const workspace = paths.filter((p) => inside(p, root));
const fallback = `${norm(root)}/NuGet.Config`;
const files: ConfigFile[] = (workspace.length ? workspace : [fallback]).map((path) => ({
path,
scope: "workspace" as const,
exists: workspace.length > 0,
}));
files.sort((a, b) => norm(a.path).length - norm(b.path).length);
return [
...files,
...paths.filter((p) => !inside(p, root)).map((path) => ({ path, scope: "user" as const, exists: true })),
];
}
export type SourceOperation = "add" | "enable" | "disable" | "remove";
export function sourceArgs(op: SourceOperation, config: string, name: string, url = ""): string[] {
return op === "add"
? ["nuget", "add", "source", url, "--name", name, "--configfile", config]
: ["nuget", op, "source", name, "--configfile", config];
}
export const EMPTY_CONFIG = toBase64(
new TextEncoder().encode('<?xml version="1.0" encoding="utf-8"?>\n<configuration>\n</configuration>\n'),
);
async function run(work: (signal: AbortSignal, cwd: string, root: string, project: string) => Promise<Partial<State>>) {
const project = selectedProject();
const root = useProject.getState().project?.root;
if (!project || !root) return;
controller?.abort();
const current = ++generation;
const abort = new AbortController();
controller = abort;
const isCurrent = () => selectedProject()?.path === project.path && useProject.getState().project?.root === root;
const stopIfChanged = () => {
if (!isCurrent()) abort.abort();
};
const stopProject = useProject.subscribe(stopIfChanged);
const stopSelection = useDotnet.subscribe(stopIfChanged);
useSources.setState({ busy: true, error: "" });
try {
const patch = await work(abort.signal, dirname(project.path), root, project.path);
if (current === generation && !abort.signal.aborted) useSources.setState(patch);
} catch (e) {
if (current === generation && !abort.signal.aborted) useSources.setState({ error: maskUrl(String(e)) });
} finally {
stopProject();
stopSelection();
if (current === generation) {
controller = undefined;
useSources.setState({ busy: false });
}
}
}
async function namesInConfig(file: ConfigFile | undefined, cwd: string, signal: AbortSignal): Promise<string[]> {
if (!file?.exists) return [];
const list = await dotnet(
["nuget", "list", "source", "--format", "detailed", "--configfile", file.path],
cwd,
signal,
);
return parseSources(list).map((source) => source.name);
}
async function load(
cwd: string,
root: string,
project: string,
signal: AbortSignal,
keep: string,
): Promise<Partial<State>> {
const [list, paths] = await Promise.all([
dotnet(["nuget", "list", "source", "--format", "detailed"], cwd, signal),
dotnet(["nuget", "config", "paths"], cwd, signal),
]);
const configs = configChoices(parseConfigPaths(paths), root);
const target = configs.find((config) => config.path === keep) ?? configs[0];
return {
project,
sources: parseSources(list),
configs,
target: target?.path ?? "",
targetNames: await namesInConfig(target, cwd, signal),
};
}
export function loadSources() {
return run((signal, cwd, root, project) => {
const current = useSources.getState();
return load(cwd, root, project, signal, current.project === project ? current.target : "");
});
}
export function selectSourceConfig(path: string) {
const { configs, project } = useSources.getState();
const config = configs.find((candidate) => candidate.path === path);
if (!config || selectedProject()?.path !== project) return;
useSources.setState({ target: path, targetNames: [] });
return run(async (signal, cwd) => ({ targetNames: await namesInConfig(config, cwd, signal) }));
}
export function cancelSources() {
controller?.abort();
}
export function changeSource(op: SourceOperation, name: string, url = "") {
const { project, target, configs, targetNames } = useSources.getState();
const config = configs.find((candidate) => candidate.path === target);
if (!config || !name.trim() || selectedProject()?.path !== project) return;
const address = url.trim();
if (op === "add" && maskUrl(address) !== address) {
useSources.setState({ error: tx("Remove credentials from the package source URL before adding it.") });
return;
}
if (op !== "add" && !targetNames.includes(name)) {
useSources.setState({ error: tx("Choose the NuGet.Config file that defines this source to change it.") });
return;
}
return run(async (signal, cwd, root, activeProject) => {
if (op === "add" && !config.exists) {
// The default template adds <clear />, which hides the inherited sources.
try {
await call(commands.fsCreateFileBytes(target, EMPTY_CONFIG));
} catch (e) {
if (!(e instanceof IpcError) || e.kind !== "alreadyExists") throw e;
}
}
await dotnet(sourceArgs(op, target, name.trim(), address), cwd, signal);
return load(cwd, root, activeProject, signal, target);
});
}
+76
Переглянути файл
@@ -103,6 +103,82 @@ describe("the .NET solution tree", () => {
expect(solution.menuPath).toBe("/repo/App.sln");
});
it("lists a project's packages, projects, frameworks and analyzers under Dependencies", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [
{
...project("/repo/App/App.csproj", "App"),
packages: [{ id: "Newtonsoft.Json", version: "13.0.3" }],
references: ["/repo/Lib/Lib.csproj"],
frameworkReferences: ["Microsoft.NETCore.App"],
analyzers: ["Analyzers.dll"],
},
project("/repo/Lib/Lib.csproj", "Lib"),
],
solutions: [{ path: "/repo/App.sln", projects: ["/repo/App/App.csproj", "/repo/Lib/Lib.csproj"] }],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
const [app, lib] = useProjectViewRoots.getState().roots.get("dotnetSolution:/repo/App.sln")!.children!;
expect(lib!.children).toBeUndefined();
const deps = app!.children!;
expect(deps.map((d) => d.label)).toEqual(["Dependencies"]);
expect(deps[0]!.children!.map((g) => [g.label, g.children!.map((c) => [c.label, c.detail ?? ""])])).toEqual([
["Packages", [["Newtonsoft.Json", "13.0.3"]]],
["Projects", [["Lib", ""]]],
["Frameworks", [["Microsoft.NETCore.App", ""]]],
["Analyzers", [["Analyzers.dll", ""]]],
]);
});
it("nests solution folders with their projects and solution items under the solution", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [project("/repo/src/libs/Core/Core.csproj", "Core"), project("/repo/App/App.csproj", "App")],
solutions: [
{
path: "/repo/App.sln",
projects: ["/repo/src/libs/Core/Core.csproj", "/repo/App/App.csproj"],
folders: [
{ path: ["src"], files: ["/repo/README.md"], projects: [] },
{ path: ["src", "libs"], files: [], projects: ["/repo/src/libs/Core/Core.csproj"] },
{ path: ["empty"], files: [], projects: [] },
],
},
],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
type Shape = { label: string; file?: boolean; children?: readonly Shape[] };
const shape = (e: Shape): unknown =>
e.children ? [e.label, e.children.map(shape)] : [e.label, e.file ? "file" : "node"];
const solution = useProjectViewRoots.getState().roots.get("dotnetSolution:/repo/App.sln")!;
expect(solution.children!.map(shape)).toEqual([
[
"src",
[
["libs", [["Core", "file"]]],
["README.md", "file"],
],
],
["empty", []],
["App", "file"],
]);
});
it("lists a solution that only has folders", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [],
solutions: [
{ path: "/repo/App.sln", projects: [], folders: [{ path: ["Items"], files: ["/repo/a.txt"], projects: [] }] },
],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
});
it("shows the solution label through the tx template", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
+122 -9
Переглянути файл
@@ -12,11 +12,15 @@
* ride on one placeholder root's grey detail text — scanning while the shared
* scan runs, the failure after it failed; idle and empty means no root at all.
*/
import type { DotnetWorkspace } from "@/platform/dotnet";
import type { DotnetProject, DotnetSolution, DotnetWorkspace } from "@/platform/dotnet";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
import { basename, dirname, useProject } from "@/platform/project";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import {
registerProjectViewRoot,
type ProjectViewRootContribution,
type ProjectViewRootEntry,
} from "@/workbench/contributions";
import { ensureDotnetModel, useDotnet } from "./store";
import { isDotnetProjectPath, isDotnetSolutionPath } from "./target";
@@ -63,6 +67,112 @@ const stateRoot = (detail: string): ProjectViewRootContribution => ({
detail,
});
/**
* The Dependencies node of a project (#7429): its direct packages, project references and framework
* references, from the one MSBuild evaluation the workspace scan already ran (no process per
* expansion). Empty groups are left out, and a project with none has no node. Transitive packages
* are not in a static evaluation; they need a restore's assets file.
*/
export function dependencies(
project: DotnetProject | undefined,
nameOf: (path: string) => string,
): ProjectViewRootEntry[] {
if (!project) return [];
const rows = (
items: readonly { id?: string; label: string; detail?: string }[],
icon: string,
): ProjectViewRootEntry[] => items.map((i) => ({ ...i, icon, leaf: true }));
const groups: ProjectViewRootEntry[] = [
{
id: "packages",
label: tx`Packages`,
icon: "package",
children: rows(
project.packages.map((p) => ({ label: p.id, detail: p.version })),
"package",
),
},
{
id: "projects",
label: tx`Projects`,
icon: ICON,
children: rows(
project.references.map((reference) => ({ id: encodeURIComponent(reference), label: nameOf(reference) })),
ICON,
),
},
{
id: "frameworks",
label: tx`Frameworks`,
icon: "library",
children: rows(
(project.frameworkReferences ?? []).map((f) => ({ label: f })),
"library",
),
},
{
id: "analyzers",
label: tx`Analyzers`,
icon: "library",
children: rows(
(project.analyzers ?? []).map((analyzer) => ({ id: encodeURIComponent(analyzer), label: basename(analyzer) })),
"library",
),
},
].filter((g) => g.children.length);
return groups.length
? [
{
id: "dependencies",
label: tx`Dependencies`,
detail: project.frameworks.length > 1 ? (project.evaluatedFramework ?? project.frameworks[0]) : undefined,
icon: "library",
children: groups,
},
]
: [];
}
/**
* A solution's children (#7431): its solution folders as nested virtual folder nodes, each with
* its projects and its solution items (files that open in the editor), then the projects that sit
* outside every folder. A solution without folders lists its projects flat, as before.
*/
export function solutionChildren(
solution: DotnetSolution,
leaf: (path: string) => ProjectViewRootEntry,
): ProjectViewRootEntry[] {
const folders = solution.folders ?? [];
const inFolders = new Set(folders.flatMap((f) => f.projects));
const file = (path: string): ProjectViewRootEntry => ({
label: basename(path),
icon: "file",
path,
file: true,
});
const roots: ProjectViewRootEntry[] = [];
const foldersByPath = new Map<string, ProjectViewRootEntry[]>();
const pathId = (path: string[]) => path.map(encodeURIComponent).join("/");
// SLNX can declare "/src/libs/" without a separate element for "/src/".
for (const folder of folders) {
let siblings = roots;
for (const [index, name] of folder.path.entries()) {
const id = pathId(folder.path.slice(0, index + 1));
let children = foldersByPath.get(id);
if (!children) {
children = [];
foldersByPath.set(id, children);
siblings.push({ id: `folder:${id}`, label: name, icon: "folder", children });
}
siblings = children;
}
}
for (const folder of folders) {
foldersByPath.get(pathId(folder.path))?.push(...folder.projects.map(leaf), ...folder.files.map(file));
}
return [...roots, ...solution.projects.filter((project) => !inFolders.has(project)).map(leaf)];
}
/**
* One group per solution (a leaf per project), standalone projects as roots of
* their own. With the model still empty, the one placeholder root carries the
@@ -95,29 +205,32 @@ export function treeRoots(
// node above the folder. Nested ones (a .NET part of a larger repository) stay in their folders.
const topLevel = (path: string) => contentRoots.includes(dirname(path));
const projectName = (path: string) => model.projects.find((p) => p.path === path)?.name ?? solutionName(path);
const leaf = (path: string) => ({ label: projectName(path), icon: ICON, path, file: true });
const leaf = (path: string): ProjectViewRootEntry => {
const children = dependencies(
model.projects.find((p) => p.path === path),
projectName,
);
return { label: projectName(path), icon: ICON, path, file: true, ...(children.length && { children }) };
};
const grouped = new Set(model.solutions.flatMap((s) => s.projects));
const roots: ProjectViewRootContribution[] = [];
for (const solution of model.solutions) {
if (!solution.projects.length || !topLevel(solution.path)) continue;
if (!(solution.projects.length || solution.folders?.length) || !topLevel(solution.path)) continue;
roots.push({
id: solutionId(solution.path),
label: tx`Solution '${solutionName(solution.path)}'`,
icon: ICON,
menuPath: solution.path,
beforeProject: true,
children: solution.projects.map(leaf),
children: solutionChildren(solution, leaf),
});
}
for (const project of model.projects)
if (!grouped.has(project.path) && topLevel(project.path))
roots.push({
id: projectId(project.path),
label: project.name,
icon: ICON,
beforeProject: true,
path: project.path,
file: true,
...leaf(project.path),
});
return roots.map((root, i) => ({ ...root, order: -200 + i }));
}
+21 -1
Переглянути файл
@@ -146,6 +146,26 @@ function sortedGroups(groups: readonly LibraryGroup[]): LibraryGroup[] {
);
}
/** Last folder name of the directory holding `path` (`/a/.venv/Lib` or `E:\a\.venv\Lib` → `.venv`). */
function parentName(path: string): string {
const parts = path.split(/[\\/]+/).filter(Boolean);
return parts[parts.length - 2] ?? "";
}
/**
* "library root", or for a folder sharing its name with a sibling (a venv's `Lib` beside the
* base interpreter's, #7444) also the parent folder (`note`), as IDEA shows a root's location.
*/
export function rootDetail(
roots: readonly { name: string; path: string }[],
root: { name: string; path: string },
): { detail: string; note?: string } {
const same = roots.filter((r) => r.name === root.name);
if (same.length < 2) return { detail: "library root" };
const parent = parentName(root.path);
return parent ? { detail: "library root", note: parent } : { detail: "library root" };
}
/** The "External Libraries" node for `groups` (`< Python 3.12 (.venv) >` › `python3.12`, `site-packages`). */
export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootContribution | null {
if (!groups.length) return null;
@@ -163,7 +183,7 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
label: r.name,
icon: isArchiveRoot(r.path) ? "file-archive" : "folder-library",
path: r.path,
detail: "library root",
...rootDetail(g.roots, r),
})),
})),
};
+57 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
import { librariesRoot, openedLibraryGroup, rootDetail, touchesManifest } from "./index";
import { mergeLibraryGroups } from "@/platform/libraries";
describe("External Libraries", () => {
@@ -185,4 +185,60 @@ describe("External Libraries", () => {
group("maven", "/m2/dep.jar!"),
]);
});
describe("same-named library roots (#7444)", () => {
const uvVenv = [
{ name: "Lib", path: "D:\\uv\\cpython-3.12-windows-x86_64-none\\Lib" },
{ name: "Lib", path: "E:\\proj\\.venv\\Lib" },
{ name: "site-packages", path: "E:\\proj\\.venv\\Lib\\site-packages" },
{ name: "DLLs", path: "D:\\uv\\cpython-3.12-windows-x86_64-none\\DLLs" },
];
it("keeps the plain detail for unique names", () => {
for (const r of uvVenv.slice(2)) expect(rootDetail(uvVenv, r)).toEqual({ detail: "library root" });
expect(rootDetail([], { name: "a", path: "/a" })).toEqual({ detail: "library root" });
});
it("names the parent folder (Windows paths)", () => {
expect(rootDetail(uvVenv, uvVenv[0]!)).toEqual({
detail: "library root",
note: "cpython-3.12-windows-x86_64-none",
});
expect(rootDetail(uvVenv, uvVenv[1]!)).toEqual({ detail: "library root", note: ".venv" });
});
it("handles POSIX paths, three siblings and a root without a parent", () => {
const roots = [
{ name: "lib", path: "/a/lib" },
{ name: "lib", path: "/b/lib" },
{ name: "lib", path: "/c/lib" },
{ name: "lib", path: "/lib" },
];
const out = roots.map((r) => rootDetail(roots, r));
expect(out.map((o) => o.note)).toEqual(["a", "b", "c", undefined]);
});
it("finds the parent folder with mixed and UNC separators", () => {
const roots = ["C:\\a\\Lib", "C:/b/Lib", "\\\\server\\share\\c\\Lib", "/d/Lib", "C:\\e/Lib", "/f/Lib"].map(
(path) => ({ name: "Lib", path }),
);
const out = roots.map((r) => rootDetail(roots, r));
expect(out.map((o) => o.note)).toEqual(["a", "b", "c", "d", "e", "f"]);
});
it("treats names case-sensitively and ignores trailing separators", () => {
const roots = [
{ name: "Lib", path: "C:\\py\\Lib\\" },
{ name: "lib", path: "C:\\py2\\lib" },
];
expect(roots.map((r) => rootDetail(roots, r))).toEqual([{ detail: "library root" }, { detail: "library root" }]);
});
it("reaches the tree nodes of the contribution", () => {
const kids = librariesRoot([{ name: "Python 3.12 (.venv)", kind: "python", roots: uvVenv }])!.children![0]!
.children!;
expect(kids.map((c) => c.detail)).toEqual(Array(4).fill("library root"));
expect(kids.map((c) => c.note)).toEqual(["cpython-3.12-windows-x86_64-none", ".venv", undefined, undefined]);
});
});
});
+10 -1
Переглянути файл
@@ -130,13 +130,22 @@ describe("MCP confirmations", () => {
expect(mocks.respond).toHaveBeenCalledWith(8, false, "Error: cannot open");
});
it("starts an agent command in the Run tool window and says whether it started", async () => {
const request = { type: "agentRun", name: "_agent_test", command: "npm test", cwd: "/project", env: {} } as const;
const target = { kind: "container", id: "a".repeat(64) } as const;
const request = {
type: "agentRun",
name: "_agent_test",
command: "npm test",
cwd: "/project",
env: {},
target,
} as const;
await handleMcpRequest(9, request);
expect(mocks.execute).toHaveBeenCalledWith("run.agentStart", {
name: "_agent_test",
command: "npm test",
cwd: "/project",
env: {},
target,
});
expect(mocks.respond).toHaveBeenCalledWith(9, true, null);
mocks.execute.mockRejectedValueOnce(new Error("The command did not start"));
+2 -2
Переглянути файл
@@ -105,8 +105,8 @@ export async function handleMcpRequest(
if (request.type === "agentRun") {
// The Run tool window starts it in the agent tab; the answer says whether it started.
try {
const { name, command, cwd, env } = request;
await executeActionOrThrow("run.agentStart", { name, command, cwd, env });
const { name, command, cwd, env, target } = request;
await executeActionOrThrow("run.agentStart", { name, command, cwd, env, target });
await send(id, true);
} catch (error) {
await send(id, false, error instanceof Error ? error.message : String(error)).catch(() => {});
+64
Переглянути файл
@@ -1077,6 +1077,70 @@ describe("ProjectView", () => {
}
});
it("tells same-named library roots apart with their parent folder (#7444)", async () => {
for (const d of ["/base/Lib", "/p/.venv/Lib", "/p/.venv/Lib/site-packages"]) fs.nodes.set(d, { kind: "dir" });
const remove = registerProjectViewRoot({
id: "externalLibraries",
label: "External Libraries",
icon: "library",
readOnly: true,
children: [
{
label: "< Python 3.12 >",
icon: "file-python",
children: [
{
label: "Lib",
icon: "folder-library",
path: "/base/Lib",
detail: "library root",
note: "base",
},
{
label: "Lib",
icon: "folder-library",
path: "/p/.venv/Lib",
detail: "library root",
note: ".venv",
},
{
label: "site-packages",
icon: "folder-library",
path: "/p/.venv/Lib/site-packages",
detail: "library root",
},
],
},
],
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("External Libraries"));
fireEvent.mouseDown(row("External Libraries"));
tree.focus();
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("< Python 3.12 >"));
fireEvent.mouseDown(row("< Python 3.12 >"));
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("site-packageslibrary root"));
const details = [...tree.querySelectorAll(`.${styles.detail}`)].map((d) => d.textContent);
// The project root shows its path first.
expect(details.slice(1)).toEqual(["library root · base", "library root · .venv", "library root"]);
// The `.venv/Lib` listing holds `site-packages` too: every row keeps its own key.
fireEvent.mouseDown(
within(tree)
.getAllByRole("treeitem")
.filter((r) => r.textContent?.startsWith("Lib"))[1]!,
);
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(tree.querySelectorAll("[data-project-key]").length).toBeGreaterThan(5));
const keys = [...tree.querySelectorAll("[data-project-key]")].map((r) => r.getAttribute("data-project-key"));
expect(new Set(keys).size).toBe(keys.length);
} finally {
act(() => remove());
}
});
it("renames in IDEA's Rename dialog with Shift+F6, validating conflicts, and undoes with ⌘Z", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
+26 -9
Переглянути файл
@@ -326,6 +326,7 @@ interface RowProps {
cut: boolean;
dropTarget: boolean;
detail: string | null;
note?: string;
/** Tooltip when no decoration gives one (a root's path while it is not shown beside it). */
hint?: string | null;
onEditDone: () => void;
@@ -345,6 +346,7 @@ const Row = memo(function Row({
cut,
dropTarget,
detail,
note,
hint,
onEditDone,
onClick,
@@ -388,11 +390,12 @@ const Row = memo(function Row({
// IDEA dims the icon of excluded folders only; git-ignored ones just get the ignored colour.
const dimIcon = node.excluded || unavailable;
const showUnavailableDetail = unavailable && node.root && !node.icon;
const fullDetail = detail && note ? `${detail} · ${note}` : detail;
const detailTitle = showUnavailableDetail
? detail
? `${detail} · ${tx("unavailable")}`
? fullDetail
? `${fullDetail} · ${tx("unavailable")}`
: tx("unavailable")
: (detail ?? undefined);
: (fullDetail ?? undefined);
return (
<span
className={clsx(styles.content, cut && styles.cut, dropTarget && styles.dropTarget)}
@@ -456,6 +459,7 @@ const Row = memo(function Row({
{(detail || showUnavailableDetail) && (
<span className={styles.detail} title={detailTitle}>
{detail}
{detail && note ? ` · ${note}` : null}
{detail && showUnavailableDetail ? " · " : null}
{showUnavailableDetail && <T>unavailable</T>}
</span>
@@ -687,8 +691,10 @@ export function ProjectView() {
: n.member
? n.member.children.length > 0
: // A file whose outline came back empty (unsupported or no members) has nothing to show.
showMembers && !n.placeholder && (outlines.get(n.path)?.length ?? 1) > 0,
[showMembers, outlines],
!n.placeholder &&
!n.group &&
(model.children.has(n.key) || (showMembers && (outlines.get(n.path)?.length ?? 1) > 0)),
[model.children, showMembers, outlines],
);
const loadChildren = useCallback(
@@ -699,8 +705,8 @@ export function ProjectView() {
const getChildren = useCallback(
(n: ProjectNode) => {
if (n.member) return memberNodes(n.path, n.member.children);
if (!n.dir) return outlineRows.get(n.path);
const children = model.children.get(n.key);
if (!n.dir && !children) return n.group ? undefined : outlineRows.get(n.path);
if (
!children ||
!decorationProviders.size ||
@@ -727,7 +733,16 @@ export function ProjectView() {
const onSelectionChange = useCallback((next: Set<string>, lead: ProjectNode | null) => {
setSelection(next, lead?.key ?? null);
const { options: o } = useProjectTree.getState();
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
if (
revealing.current ||
!o.autoscrollToSource ||
!lead ||
lead.dir ||
lead.group ||
lead.placeholder ||
next.size !== 1
)
return;
const opts = { preview: previewTabEnabled(), focus: false, external: false };
if (lead.member) {
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
@@ -737,7 +752,7 @@ export function ProjectView() {
const onActivate = useCallback((node: ProjectNode) => {
if (node.member) {
void revealRange(node.path, { start: node.member.selection_range.start }, { focus: true });
} else if (!node.dir && !node.placeholder) void openFile(node.path, { focus: true });
} else if (!node.dir && !node.placeholder && !node.group) void openFile(node.path, { focus: true });
}, []);
const onContextMenu = useCallback((node: ProjectNode | null, sel: Set<string>, e: ReactMouseEvent) => {
@@ -773,7 +788,7 @@ export function ProjectView() {
const onRowClick = useCallback((node: ProjectNode, e: ReactMouseEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey || e.altKey) return;
if (node.placeholder || dragged.current) return;
if (node.placeholder || node.group || dragged.current) return;
const { options: o, editing: ed } = useProjectTree.getState();
if (ed) return;
if (e.detail > 1 && !(node.dir && o.singleClickExpand && e.detail % 2 === 1)) return;
@@ -1076,6 +1091,7 @@ export function ProjectView() {
editing={editing}
cut={cutPaths.has(node.path)}
dropTarget={dropTarget === node.key}
note={node.note}
detail={
node.detail ??
(rootPath(node) && options.showRootPaths ? rootPath(node) : null) ??
@@ -1148,6 +1164,7 @@ export function ProjectView() {
getDirectory={(node) => (node.group || node.placeholder ? null : targetFolder(node))}
getChildren={getChildren}
isExpandable={isExpandable}
activateExpandable={(node) => !node.dir && model.children.has(node.key)}
loadChildren={loadChildren}
renderNode={renderNode}
rowTint={(n) =>
+39
Переглянути файл
@@ -53,6 +53,45 @@ describe("withExtraRoots", () => {
expect(base.roots).toHaveLength(1);
});
it("shows a file node that expands, with virtual leaves that are never files", () => {
const base = buildModel({ path: "/p", name: "proj" }, new Map(), DEFAULT_TREE_OPTIONS);
const m = withExtraRoots(
base,
[
{
id: "sln",
label: "Solution",
icon: "x",
children: [
{
label: "App",
icon: "x",
path: "/s/App/App.csproj",
file: true,
children: [
{
id: "deps",
label: "Dependencies",
icon: "x",
children: [{ label: "Pkg", detail: "1.0", icon: "x", leaf: true }],
},
],
},
],
},
],
new Map(),
DEFAULT_TREE_OPTIONS,
);
const app = m.children.get("\0group:sln")![0]!;
expect([app.label, app.dir, app.path]).toEqual(["App", false, "/s/App/App.csproj"]);
expect(menuGroupContext([app])).toEqual({ paths: ["/s/App/App.csproj"], dirs: [false] });
const deps = m.children.get(app.key)![0]!;
expect(deps.group).toBe(true);
const pkg = m.children.get(deps.key)![0]!;
expect([pkg.label, pkg.detail, pkg.dir, pkg.group]).toEqual(["Pkg", "1.0", false, true]);
});
it("returns the model itself without extra roots", () => {
const base = buildModel({ path: "/p", name: "proj" }, new Map(), DEFAULT_TREE_OPTIONS);
expect(withExtraRoots(base, [], new Map(), DEFAULT_TREE_OPTIONS)).toBe(base);
+52 -6
Переглянути файл
@@ -59,6 +59,8 @@ export interface ProjectNode {
icon?: string;
/** Grey text after the label ("library root"). */
detail?: string;
/** Untranslated text after `detail`. */
note?: string;
/** A node grouping other nodes, without a folder of its own ("External Libraries"). */
group?: boolean;
/** A group node: the file whose context-menu groups its menu shows (a solution's `.sln`). */
@@ -295,6 +297,9 @@ export interface ExtraRoot {
file?: boolean;
children?: readonly ExtraRoot[];
detail?: string;
note?: string;
/** A virtual row with no file or folder behind it (a package of a project's Dependencies): a childless group node. */
leaf?: boolean;
/** A group node: the file whose context-menu groups the node shows. */
menuPath?: string;
readOnly?: boolean;
@@ -317,6 +322,17 @@ const LIB_SEP = "\u0000";
export const isLibKey = (key: string) => key.startsWith(LIB_PREFIX);
/** Namespace suffix of a library root that lies inside a sibling root of its group, once per such sibling. */
const NESTED_NS = "/nested";
/** How many other folders of a group hold folder `extra`. */
const nestingDepth = (siblings: readonly ExtraRoot[], extra: ExtraRoot): number =>
extra.path === undefined || extra.children
? 0
: siblings.filter(
(o) => o.path !== undefined && !o.children && o.path !== extra.path && isSameOrInside(extra.path!, o.path),
).length;
export const libKey = (group: string, path: string) => `${LIB_PREFIX}${group}${LIB_SEP}${path}`;
/** The folder / file a node key stands for (keys outside library subtrees are paths). */
@@ -384,9 +400,9 @@ export function withExtraRoots(
byKey: new Map(model.byKey),
keyOfPath: new Map(model.keyOfPath),
};
const add = (extra: ExtraRoot, parentKey: string | null, readOnly: boolean): ProjectNode | null => {
const add = (extra: ExtraRoot, parentKey: string | null, readOnly: boolean, nesting = 0): ProjectNode | null => {
const ro = readOnly || !!extra.readOnly;
if (extra.file && extra.path !== undefined && !extra.children) {
if (extra.file && extra.path !== undefined) {
// A file leaf is keyed in its group's namespace (like a library folder): the
// same file also shows in its own folder below the project, and `pathOfKey`
// still resolves the leaf to the real path for selection and context menus.
@@ -406,16 +422,24 @@ export function withExtraRoots(
symlink: false,
icon: extra.icon,
detail: extra.detail,
note: extra.note,
};
if (ro) node.readOnly = true;
out.byKey.set(key, node);
if (extra.children) {
const built = extra.children.map((child) => add(child, key, ro)).filter((node): node is ProjectNode => !!node);
out.children.set(key, built);
}
return node;
}
if (extra.path !== undefined && !extra.children) {
const path = extra.path;
// Library folders of a group are keyed in their own namespace; other
// folders (scratches) by path, so ones inside the project stay under it.
const ns = ro && parentKey ? parentKey.slice(GROUP_PREFIX.length) : null;
// A root inside a sibling root (a venv's `Lib` and its `Lib/site-packages`) lists in a
// namespace of its own: the sibling's listing holds the same folder, and one key on two
// rows overlaps them in the virtual list (#7444).
const ns = ro && parentKey ? parentKey.slice(GROUP_PREFIX.length) + NESTED_NS.repeat(nesting) : null;
const rekey = (k: string) => (ns === null ? k : libKey(ns, k));
if (out.byKey.has(rekey(path))) return null;
if (ns === null && model.roots.some((r) => !r.group && isSameOrInside(path, r.path))) return null;
@@ -427,6 +451,7 @@ export function withExtraRoots(
root: !parentKey,
icon: extra.icon,
detail: extra.detail,
note: extra.note,
};
if (ro) rootNode.readOnly = true;
const nodes = new Map<string, ProjectNode>();
@@ -446,6 +471,26 @@ export function withExtraRoots(
}
const key = `${parentKey ? `${parentKey}/` : GROUP_PREFIX}${extra.id ?? extra.label}`;
if (out.byKey.has(key)) return null;
if (extra.leaf) {
const node: ProjectNode = {
key,
path: key,
chain: [],
label: extra.label,
dir: false,
root: false,
entry: null,
ignored: false,
excluded: false,
symlink: false,
icon: extra.icon,
detail: extra.detail,
group: true,
readOnly: true,
};
out.byKey.set(key, node);
return node;
}
const node: ProjectNode = {
key,
path: key,
@@ -459,6 +504,7 @@ export function withExtraRoots(
symlink: false,
icon: extra.icon,
detail: extra.detail,
note: extra.note,
group: true,
menuPath: extra.menuPath,
readOnly: true,
@@ -470,7 +516,7 @@ export function withExtraRoots(
const depth = (c: ExtraRoot) => c.path?.split("/").length ?? 0;
const built: (ProjectNode | null)[] = [];
for (const i of children.map((_, i) => i).sort((a, b) => depth(children[b]!) - depth(children[a]!)))
built[i] = add(children[i]!, key, ro);
built[i] = add(children[i]!, key, ro, nestingDepth(children, children[i]!));
out.children.set(
key,
built.filter((n): n is ProjectNode => !!n),
@@ -603,10 +649,10 @@ export function visibleInfo(model: TreeModel, expanded: ReadonlySet<string>): Vi
const walk = (nodes: readonly ProjectNode[]) => {
for (const n of nodes) {
visible.add(n.key);
if (!n.dir || !expanded.has(n.key)) continue;
if (!expanded.has(n.key)) continue;
const kids = model.children.get(n.key);
if (kids) walk(kids);
else pending.push(n.path);
else if (n.dir) pending.push(n.path);
}
};
walk(model.roots);
+116
Переглянути файл
@@ -0,0 +1,116 @@
import { describe, expect, it } from "vitest";
import { buildModel, DEFAULT_TREE_OPTIONS, libKey, pathOfKey, withExtraRoots, type ExtraRoot } from "./model";
const dir = (path: string) => ({
name: path.split("/").pop()!,
path,
kind: "dir" as const,
size: 0,
mtimeMs: 1,
ignored: false,
excluded: false,
hidden: false,
});
const group = (...paths: string[]): ExtraRoot => ({
id: "externalLibraries",
label: "External Libraries",
icon: "library",
readOnly: true,
children: [
{
label: "< Python >",
icon: "file-python",
children: paths.map((path) => ({ label: path.split("/").pop()!, icon: "folder-library", path })),
},
],
});
/** Keys of every row below the first SDK group, listed folders and all. */
function rowKeys(extra: ExtraRoot, listings: Map<string, ReturnType<typeof dir>[]>): string[] {
const base = buildModel({ path: "/p", name: "proj" }, listings as never, DEFAULT_TREE_OPTIONS);
const m = withExtraRoots(base, [extra], listings as never, DEFAULT_TREE_OPTIONS);
const out: string[] = [];
const walk = (k: string) =>
(m.children.get(k) ?? []).forEach((n) => {
out.push(n.key);
walk(n.key);
});
walk(m.children.get(m.roots[1]!.key)![0]!.key);
return out;
}
describe("nested library roots (#7444)", () => {
const unique = (keys: string[]) => expect(new Set(keys).size).toBe(keys.length);
const L = "/v/.venv/Lib";
const listing = (path: string, ...kids: string[]) => [path, kids.map(dir)] as const;
it("keeps keys unique whatever the root order", () => {
for (const order of [
[L, `${L}/site-packages`],
[`${L}/site-packages`, L],
]) {
const keys = rowKeys(group(...order), new Map([["/p", []], listing(L, `${L}/site-packages`)]));
expect(keys).toHaveLength(3);
unique(keys);
}
});
it("keeps keys unique for three nesting levels and sibling roots with a shared name prefix", () => {
const keys = rowKeys(
group(L, `${L}/site-packages`, `${L}/site-packages/pkg`, `${L}2`),
new Map([["/p", []], listing(L, `${L}/site-packages`), listing(`${L}/site-packages`, `${L}/site-packages/pkg`)]),
);
unique(keys);
// `Lib2` is not inside `Lib`: its key stays the plain one.
expect(keys).toContain(libKey("externalLibraries/< Python >", `${L}2`));
});
it("leaves roots that are not nested on their plain keys", () => {
const keys = rowKeys(group("/a/Lib", "/b/Lib"), new Map([["/p", []]]));
expect(keys).toEqual([
libKey("externalLibraries/< Python >", "/a/Lib"),
libKey("externalLibraries/< Python >", "/b/Lib"),
]);
});
it("resolves a nested root's key back to its folder", () => {
const keys = rowKeys(group(L, `${L}/site-packages`), new Map([["/p", []]]));
expect(keys.map(pathOfKey)).toEqual([L, `${L}/site-packages`]);
});
it("never lists one key twice", () => {
const LIBS: ExtraRoot = {
id: "externalLibraries",
label: "External Libraries",
icon: "library",
readOnly: true,
children: [
{
label: "< Python >",
icon: "file-python",
children: [
{ label: "Lib", icon: "folder-library", path: "/v/.venv/Lib" },
{ label: "site-packages", icon: "folder-library", path: "/v/.venv/Lib/site-packages" },
],
},
],
};
const listings = new Map([
["/p", []],
["/v/.venv/Lib", [dir("/v/.venv/Lib/site-packages")]],
]);
const base = buildModel({ path: "/p", name: "proj" }, listings, DEFAULT_TREE_OPTIONS);
const m = withExtraRoots(base, [LIBS], listings, DEFAULT_TREE_OPTIONS);
const group = m.children.get(m.roots[1]!.key)![0]!;
const rows: string[] = [];
const walk = (k: string) =>
(m.children.get(k) ?? []).forEach((n) => {
rows.push(n.key);
walk(n.key);
});
walk(group.key);
expect(rows.length).toBeGreaterThan(0);
expect(new Set(rows).size).toBe(rows.length);
});
});
+17 -7
Переглянути файл
@@ -1,11 +1,12 @@
/** Run configurations of commands agents run through the IDE's MCP server (`run_command`). */
import type { IpcPath, RunConfig } from "@/bindings";
import type { IpcPath, McpAgentRunTarget, RunConfig } from "@/bindings";
import { workflowSettings } from "@/platform/workflowSettings";
/** Names the agent tab a run belongs to; the backend logs it for the agent. */
export const AGENT_PARAM = "mcp.agentRun";
/** Settings › Tools › Terminal › Shell path, which the backend runs the command line with. */
const SHELL_PARAM = "mcp.agentShell";
const TARGET_PARAM = "mcp.agentTarget";
/** The agent tab name of a configuration, or `null` for any other run. */
export function agentName(config: Pick<RunConfig, "params">): string | null {
@@ -13,11 +14,16 @@ export function agentName(config: Pick<RunConfig, "params">): string | null {
}
/**
* The command line of agent tab `name`, with the shell of the IDE's terminal but on pipes (as
* JetBrains' `execute_terminal_command`): programs print plain lines, the console shows them and
* sends the user's input lines.
* The command line and approved execution target of agent tab `name`. The console shows output
* from the process's pipes and sends the user's input lines.
*/
export function agentConfig(name: string, command: string, cwd: IpcPath, env: Record<string, string>): RunConfig {
export function agentConfig(
name: string,
command: string,
cwd: IpcPath,
env: Record<string, string>,
target: McpAgentRunTarget,
): RunConfig {
const terminal = workflowSettings().terminal;
return {
id: `mcp-agent:${name}`,
@@ -31,8 +37,12 @@ export function agentConfig(name: string, command: string, cwd: IpcPath, env: Re
isTest: false,
debugAdapter: null,
allowParallel: true,
params: { [AGENT_PARAM]: name, [SHELL_PARAM]: terminal.shellPath },
// This machine: an agent's command never goes to a default run target.
params: {
[AGENT_PARAM]: name,
[SHELL_PARAM]: terminal.shellPath,
[TARGET_PARAM]: JSON.stringify(target),
},
// The backend starts the shell or Dev Containers CLI on this machine.
target: "",
};
}
+9 -2
Переглянути файл
@@ -23,7 +23,7 @@ function session(id: string, config: RunConfig, status: RunSession["status"], en
describe("agent tabs", () => {
it("run the command line on pipes, on this machine", () => {
const config = agentConfig("_agent_build", "cargo build", "/project", { A: "1" });
const config = agentConfig("_agent_build", "cargo build", "/project", { A: "1" }, { kind: "host" });
expect(agentName(config)).toBe("_agent_build");
expect(agentName(plain)).toBeNull();
expect(config).toMatchObject({
@@ -38,10 +38,17 @@ describe("agent tabs", () => {
expect(config.emulateTerminal).toBeFalsy();
expect(config.env).toMatchObject({ A: "1" });
expect(config.params).toHaveProperty("mcp.agentShell");
expect(config.params?.["mcp.agentTarget"]).toBe(JSON.stringify({ kind: "host" }));
});
it("stores the approved container target in the config reused by reruns", () => {
const target = { kind: "container", id: "a".repeat(64) } as const;
const config = agentConfig("_agent_build", "in dev container app: cargo build", "/project", {}, target);
expect(config.params?.["mcp.agentTarget"]).toBe(JSON.stringify(target));
});
it("archive the oldest finished ones beyond the limit, never a running one or another run", () => {
const agent = (name: string) => agentConfig(name, "true", "/p", {});
const agent = (name: string) => agentConfig(name, "true", "/p", {}, { kind: "host" });
const sessions = [
session("old", agent("_agent_old"), "finished", 1),
session("failed", agent("_agent_failed"), "failed", 2),
+3 -8
Переглянути файл
@@ -1,19 +1,14 @@
/** The Run tool window's agent tabs: starting them, and archiving finished ones. */
import type { IpcPath } from "@/bindings";
import type { McpUiRequest } from "@/bindings";
import { agentRunSettings } from "@/platform/workflowSettings";
import { agentConfig, agentName } from "./agentConfig";
import { closeSession, isLive, startRun, useRun, type RunSession } from "./store";
export interface AgentRunRequest {
name: string;
command: string;
cwd: IpcPath;
env: Record<string, string>;
}
export type AgentRunRequest = Omit<Extract<McpUiRequest, { type: "agentRun" }>, "type">;
/** Starts an agent's command in its tab (reused once its last command finished). */
export async function startAgentRun(request: AgentRunRequest): Promise<void> {
const config = agentConfig(request.name, request.command, request.cwd, request.env);
const config = agentConfig(request.name, request.command, request.cwd, request.env, request.target);
const existing = useRun.getState().sessions.find((s) => s.config.id === config.id);
// The backend refuses a running name first; nothing here stops a run on the agent's behalf.
if (existing && isLive(existing)) throw new Error(`${request.name} is still running`);
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more