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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1c00a1125d fix(ui): remember splitter positions in the Git and other tool windows
SplitGroup only remembers sizes with a storageKey, and none of the Git views
passed one, so the Commit, Local Changes, Log, Stash/Shelf and revision
splitters went back to their defaults whenever the view was recreated. Give
them, the Commit dialog, and the Todo, Find, Problems, Usages, Build, HTTP
Client and Dependency Analyzer splits a key, with stable panel ids.

A view whose preview pane comes and goes keys its sizes per panel set;
SplitGroup now applies that set's saved sizes when the key changes, once the
panels have registered, so toggling a preview restores its size without
remounting the view.
2026-11-14 23:41:17 +08:00
l0ng-ai 1dc1e3cca1 feat(debugger): Focus On Breakpoint toggle for the Threads & Variables tab (#3400)
A breakpoint hit always brought Threads & Variables to the front. Its tab's context menu now has Focus On Breakpoint (on by default, client setting debugger.variablesOnBreakpoint); turned off, a hit keeps the current tab, e.g. Console. Finishing a step already kept it.
2026-11-14 23:34:17 +08:00
l0ng-ai 4a82c22fdc fix(plugins): keep document indexer markers on their lines while typing (#3398)
Every edit emptied the indexed-marker gutter until the host re-indexed the file; the column has no fixed width, so the text shifted left and back on each keystroke. The markers are now mapped through the change (a deleted line drops its own), as line markers and bookmarks already do.
2026-11-14 23:27:33 +08:00
Mr0Bread 010e7ba6b4 feat(agents): add configurable task input focus shortcut (#3382)
Focus Agent Input (⌘L on macOS, Ctrl+L on Windows / Linux, in every built-in keymap) returns focus to the current writable task's message input from its conversation, in an editor tab or the tool window, keeping the draft, caret and selection. It applies only while focus is inside an agent task, so the keys keep their editor and terminal meaning elsewhere; the binding is under Settings › Keymap › Agents.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-14 23:24:59 +08:00
Mr0Bread 9984e40b83 fix(agents): refresh available models before starting tasks (#3366)
New Task showed no models until an agent's first task. It now shows the cached catalog at once and discovers the agent's models without starting a task (no prompt, no project MCP servers): one shared lookup per provider and project, fresh for 15 minutes, with a Refresh models action and a 30-second cooldown. Catalogs persist per effective launch configuration (a digest, never the arguments or credentials); a selected model the latest catalog dropped blocks Start until another is chosen. Discovery requires a trusted project.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-14 23:22:14 +08:00
Muuтаmuutot 36a6e6359d feat(editor): resolve an ambiguous Python base name through the file's imports (#3384)
A base name several modules declare was skipped, so a project with many Config classes got no marker for them. The subclass file's from-imports (aliases included) now pick the declaration; with no import naming it the base is still ignored. Imports are read only when a base may name a class of the open file, so a marker refresh does not read every subclass file of the project.

Co-authored-by: muutot <+[email protected]>
2026-11-14 23:14:53 +08:00
Muuтаmuutot 4f64326f89 fix(editor): keep close gestures when the close button is hidden (#3354)
EditorArea passed closable: showCloseButton, and closable gates every close gesture in Tabs, so Close button position: None made editor tabs unclosable by middle click, Shift+click and Delete. Tabs gets a visual-only showCloseButton that hides the button while the tab stays closable.

Co-authored-by: muutot <[email protected]>
2026-11-14 23:12:14 +08:00
akshathayadav378-boopтаakshathayadav378-boop b5c2d0dc5e fix(settings): let Project View branch decorations be bold and italic (#3387)
The six Project View branch attributes never set fontStyle, so Settings disabled Bold and Italic for them although the Project view's branch suffix already reads --git-<attr>-bold/-italic/-effect. Setting it enables the checkboxes and makes the overrides emit those variables.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-14 23:10:13 +08:00
l0ng-ai c9dca15972 fix(debugger): let a Node.js program read input while it is debugged (#3395)
js-debug launched the program with the internal console, so it had no standard input. Run it in the debugger's pseudo-terminal instead, and reap a runInTerminal program as soon as it exits: an unreaped zombie looked alive to js-debug's processId polling and kept the session open.
2026-11-14 23:08:36 +08:00
l0ng-ai 41b581eafd fix(github): recognise remotes cloned through ssh.github.com (#3391)
A clone over GitHub's SSH-over-HTTPS host (ssh://[email protected]:443/o/r.git or [email protected]:o/r.git) wasn't recognised as a GitHub repository. parseGitHubRemote now accepts ssh.github.com for SSH remotes; https://ssh.github.com stays rejected. Sibling of #3379.
2026-11-14 22:57:59 +08:00
akshathayadav378-boopтаakshathayadav378-boop 13e18af777 fix(vcs): open Bitbucket SSH clones on bitbucket.org (#3379)
For a Bitbucket Cloud repository cloned over SSH ([email protected]:team/repo.git), Open In used ssh.bitbucket.org as the web host and GitLab routes. remoteWebUrl now maps the services' SSH front hosts (ssh.bitbucket.org, ssh.github.com, altssh.gitlab.com) to their web hosts before building the URL.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-14 22:54:44 +08:00
charlie-morrisonтаcharlie-morrison 488e819b46 fix(vcs): keep the merge editor responsive on long files (#3381)
Opening a conflicted package-lock.json in the merge editor froze the app. The Your/Their panes diffed each side against the base with @codemirror/merge's default config, which gives up past ~16 KB of changed span and returns one chunk from the first change to the last, so each pane rendered the whole base as one deletion widget; syncMergeScroll ran an unbounded character diff on first scroll. Both now use the IDEA line comparison the diff viewer uses (ideaDiffConfig).

Co-authored-by: charlie-morrison <[email protected]>
2026-11-14 22:53:04 +08:00
l0ng-ai ad8df8fe00 feat(database): open several query consoles per data source (#3386)
New › Query Console always reopened the single console of a data source. It now creates another console each time (console, console_1, console_2…, as in DataGrip); Jump to Query Console opens the only console directly or lists them with New Query Console; Tools › Query Console keeps opening the default one. Backend: db_consoles(id, create).
2026-11-14 22:50:51 +08:00
l0ng-ai 19d6eab21a feat(http-client): find in the response body and open the files .http lines name (#3383)
The response pane had no find: ⌘F (or a Find button next to Show Raw) now opens the console find bar with matches marked in the body. ⌘-click / ⌘B on the file a .http line names (< body, > handler, >> redirect, <> saved response) opens it; saved responses resolve against .idea/httpRequests/ (where IntelliJ IDEA writes them), then the request file's folder.
2026-11-14 22:32:50 +08:00
Muuтаmuutot 5c0befeff0 feat(lsp): compute Python inheritance gutter markers from the IDE index (#3359)
Python's overrides / is-overridden gutter markers never appeared: basedpyright and pyrefly declare no typeHierarchyProvider, and a single-root server cannot see classes in attached projects. The IDE now extracts every class X(Base) with tree-sitter across the project (content roots included) and nav_inheritance exposes them; the editor merges this graph with the server's answer. A base name is trusted only when it names one class (unique in the project or declared in the same file). Class bases are cached per file and parsed again only when the file changes.

Co-authored-by: muutot <[email protected]>
2026-11-14 22:24:48 +08:00
Akbar Husain 07bd8ded5e feat(run): report Zig test runs in the test runner (#3355)
Zig test blocks had run markers but their runs never reached the test runner: no parser read the runners' output. A parser now reads zig test's per-test progress lines, error-return traces and summary, and zig build test's failure blocks and --summary all counts (added to those runs). Results are rooted at the module stem so gutter icons turn green/red per test; Rerun Failed and Run Selected build --test-filter configs for standalone zig test runs. test names are unescaped in run targets so the marker label, --test-filter and the runner's names agree.

Co-authored-by: akbar1214 <[email protected]>
2026-11-14 22:16:35 +08:00
Mr0Bread 4ab85d5f49 feat(editor): resize the vertical editor tab column by dragging its edge (#3365)
With tabs placed left or right, the column could not be resized and was never narrower than 140 px. It now fits its longest name up to a limit (260 px by default); dragging its inner edge, or ←/→ on the focused edge, changes the limit for every editor group and it is remembered. The editor keeps at least 60% of each group.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-14 22:15:22 +08:00
Mansur Akhmadiтаmansur-akhmadi 3c91adfae2 feat(vcs): choose the repository in the Rebase dialog when the project has several (#3351)
Git > Rebase… always rebased the repository selected in the branch widget. With two or more repositories the dialog now has the repository combo: picking one reloads its branches and the label, clears the chosen upstream and --onto base, and Rebase runs in that repository.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-14 22:12:34 +08:00
Mansur Akhmadiтаmansur-akhmadi 5cfa6614a1 feat(vcs): choose the repository in the Merge dialog when the project has several (#3332)
Git > Merge… always merged into the repository selected in the branch widget. With two or more repositories the dialog now has the repository combo (as in Pull): picking one reloads its branches and title, clears the chosen branch, and Merge runs in that repository.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-14 22:12:04 +08:00
Shohruh Ismoilovтаshohruh-genius e875d97f7c fix(project): show relevant file templates in New menus (#3342)
The New menu offered every language template in every project. It now uses the detected type of the project owning the selected folder for language-specific templates (Rust, Python, Go, PHP, Java/Kotlin); generic and web templates (JavaScript, TypeScript) stay in every project, as in IntelliJ IDEA Ultimate, and From Template still lists the whole catalog. Tomcat Context Descriptor is offered only when the project has a Tomcat run configuration.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-14 22:07:27 +08:00
Mr0Bread 31016ee684 fix(agents): add Copy Link Address to the context menu of links in readable text (#3371)
Right-clicking a link in Agent Task chat (and other readable panes using the shared Copy menu) only offered Copy, which copied the selected label. Links now also get Copy Link Address, as in browsers; Copy keeps copying the selection, and in-page anchors get no link item.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-14 22:05:29 +08:00
l0ng-ai 6a93f1cce6 fix(debugger): show a JVM session's Memory tab from the start; pass lldb-dap's environment for cargo debugging (#3380)
The Memory tab appeared only once the debugger reported its capabilities, so a Java or Kotlin session's tab bar grew a tab after the program started; it is now shown from the start with a placeholder until the program runs. A cargo configuration debugged with lldb-dap passed CodeLLDB's sourceLanguages and an environment object; lldb-dap now gets KEY=VALUE strings like other native programs.
2026-11-14 22:01:34 +08:00
l0ng-ai 2b4e3c79f8 fix(debugger): let a Python program read input while it is debugged (#3374)
debugpy launched the program with console "internalConsole", which gives it no standard input, so input() raised EOFError. It now runs with console "integratedTerminal": debugpy starts it through runInTerminal on the pseudo-terminal the debugger already provides, and what is typed in the debug console reaches it. Output comes from that terminal, so redirectOutput is dropped (it doubled every line). Node under js-debug still lacks input; its terminal launch needs its own fix.
2026-11-14 21:34:21 +08:00
143 змінених файлів з 5674 додано та 498 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
name = "ide-agent"
version = "0.1.45"
dependencies = [
"blake3",
"dunce",
"encoding_rs",
"ide-core",
+4
Переглянути файл
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
encoding_rs.workspace = true
blake3.workspace = true
ide-vfs.workspace = true
ide-core.workspace = true
ide-mcp.workspace = true
@@ -24,3 +25,6 @@ dunce.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+35 -27
Переглянути файл
@@ -3,6 +3,7 @@
//! `initialize` alone).
use super::{Conn, Dialect};
use crate::catalogs::Discovered;
use crate::config;
use crate::model::AgentConfigOption;
use crate::provider::ProviderSpec;
@@ -15,7 +16,7 @@ use std::time::Duration;
const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(3) } else { Duration::from_secs(120) };
/// Opens `session/new`, reads `configOptions`, and records per-model `thought_level` choices.
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<(), String> {
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<Discovered, String> {
let root = shared.paths.project_root.clone();
let launch = spec.clone();
let launch = tokio::task::spawn_blocking({
@@ -25,12 +26,12 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<(),
.await
.map_err(|e| e.to_string())?;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let stderr: Arc<Mutex<Vec<String>>> = Arc::default();
let lines = stderr.clone();
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(move |l| lines.lock().push(l));
let client = Dialect::wrap(Arc::new(ide_jsonrpc::NoopHandler));
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), commands: Mutex::new(None) });
let client = Dialect::wrap(updates.clone());
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
.map_err(|e| format!("Couldn't start {} (`{}`): {e}", launch.name, launch.command))?;
let _stop = crate::catalogs::KillPeer(peer.clone());
let conn = Conn::new(peer.clone(), client);
let work = async {
conn.initialize(&client_info()).await.map_err(|e| e.to_string())?;
@@ -51,34 +52,41 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<(),
(Some(model), Some(effort)) => model.current.clone().map(|m| vec![(m, effort)]).unwrap_or_default(),
_ => Vec::new(),
};
let option_ids: Vec<_> = options.iter().map(|o| o.id.as_str()).collect();
tracing::info!(
"agent {}: settings discovery got {} config option(s) {:?}, {} model effort list(s)",
launch.id,
options.len(),
option_ids,
levels.len()
);
shared.remember_discovered(&launch.id, &options, &[], &levels);
Ok::<(), String>(())
let commands = updates
.commands
.lock()
.clone()
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
Ok::<_, String>(Discovered { config: options, commands, levels: levels.into_iter().collect() })
};
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
peer.kill();
match result {
Ok(Ok(())) => Ok(()),
Ok(Err(e)) => Err(match stderr.lock().last() {
Some(line) => format!("{e}: {line}"),
None => e,
}),
Err(_) => {
let tail = stderr.lock().join("\n");
if tail.is_empty() {
Err("the agent did not answer in time".into())
} else {
Err(format!("the agent did not answer in time:\n{tail}"))
}
Ok(result) => result,
Err(_) => Err("the agent did not answer in time".into()),
}
}
#[derive(Default)]
struct DiscoveryUpdates {
provider: String,
commands: Mutex<Option<Vec<crate::AgentCommand>>>,
}
impl ide_jsonrpc::Handler for DiscoveryUpdates {
fn on_notification(&self, method: &str, params: Value) {
if method == "session/update"
&& let Some(update) = params.get("update")
&& update["sessionUpdate"] == "available_commands_update"
{
// Commands are protocol data, not stderr (which may contain credentials).
*self.commands.lock() = Some(config::commands_of(update, &self.provider));
}
}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, format!("unsupported discovery request {method}")))
}
}
fn is_thought_level(o: &AgentConfigOption) -> bool {
+1
Переглянути файл
@@ -108,6 +108,7 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
connector,
+1
Переглянути файл
@@ -155,6 +155,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
connector,
+427
Переглянути файл
@@ -0,0 +1,427 @@
//! Model availability for new tasks. Sessions own selections; discovery owns catalogs.
use crate::{
AgentCommand, AgentConfigOption, AgentEvent, AgentModelCatalog, Known, Shared, acp, config, native, provider,
};
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::watch;
use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
/// Backend-wide single-flight model lookups, scoped to project and effective launch configuration.
#[derive(Default)]
pub struct AgentCatalogs {
state: Mutex<State>,
#[cfg(test)]
clock_ms: std::sync::atomic::AtomicU64,
}
#[derive(Default)]
struct State {
stores: HashMap<PathBuf, Store>,
entries: HashMap<Key, Entry>,
subscribers: Vec<Weak<Shared>>,
generation: u64,
}
struct Entry {
// Launch credentials remain only in memory, never serialized or logged.
context: LaunchContext,
generation: u64,
completed: Option<Instant>,
successful: Option<Instant>,
retry_at_ms: Option<f64>,
error: Option<String>,
flight: Option<watch::Receiver<bool>>,
abort: Option<tokio::task::AbortHandle>,
catalog: Option<CatalogData>,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CatalogData {
pub config: Vec<AgentConfigOption>,
pub thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
pub refreshed_at_ms: Option<f64>,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(flatten)]
catalog: CatalogData,
}
#[derive(PartialEq)]
struct LaunchContext {
spec: provider::ProviderSpec,
executable: PathBuf,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
impl LaunchContext {
fn new(spec: provider::ProviderSpec, root: &std::path::Path) -> Self {
let resolved = spec.clone().resolve_for_launch(root);
let executable = dunce::canonicalize(&resolved.command).unwrap_or_else(|_| PathBuf::from(&resolved.command));
let metadata = std::fs::metadata(&executable).ok();
Self {
spec,
executable,
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
}
fn fingerprint(&self) -> String {
let mut hash = blake3::Hasher::new();
fn field(hash: &mut blake3::Hasher, value: &[u8]) {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v1");
field(
&mut hash,
match self.spec.driver {
provider::Driver::Acp => b"acp",
provider::Driver::Codex => b"codex",
provider::Driver::Claude => b"claude",
},
);
field(&mut hash, self.spec.command.as_bytes());
hash.update(&(self.spec.args.len() as u64).to_le_bytes());
for arg in &self.spec.args {
field(&mut hash, arg.as_bytes());
}
hash.update(&(self.spec.env.len() as u64).to_le_bytes());
for (name, value) in &self.spec.env {
field(&mut hash, name.as_bytes());
field(&mut hash, value.as_bytes());
}
field(&mut hash, self.executable.to_string_lossy().as_bytes());
if let Some(modified) = self.modified.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) {
hash.update(&modified.as_nanos().to_le_bytes());
}
if let Some(len) = self.len {
hash.update(&len.to_le_bytes());
}
hash.finalize().to_hex().to_string()
}
}
pub(crate) struct Discovered {
pub config: Vec<AgentConfigOption>,
pub commands: Option<Vec<AgentCommand>>,
pub levels: BTreeMap<String, Vec<AgentConfigOption>>,
}
pub(crate) struct KillPeer(pub ide_jsonrpc::Peer);
impl Drop for KillPeer {
fn drop(&mut self) {
self.0.kill();
}
}
impl AgentCatalogs {
fn now(&self) -> Instant {
let now = Instant::now();
#[cfg(test)]
let now = now + Duration::from_millis(self.clock_ms.load(std::sync::atomic::Ordering::Relaxed));
now
}
fn epoch_ms(&self) -> f64 {
let now = crate::now_ms();
#[cfg(test)]
let now = now + self.clock_ms.load(std::sync::atomic::Ordering::Relaxed) as f64;
now
}
pub(crate) fn store(&self, path: &std::path::Path) -> Store {
self.state
.lock()
.stores
.entry(path.to_path_buf())
.or_insert_with(|| {
Arc::new(Mutex::new(
std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(),
))
})
.clone()
}
pub(crate) fn subscribe(&self, shared: &Arc<Shared>) {
let mut state = self.state.lock();
state.subscribers.retain(|s| s.strong_count() > 0);
state.subscribers.push(Arc::downgrade(shared));
}
fn key(shared: &Shared, provider: &str) -> Key {
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
}
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
let cache = shared.known.lock();
let Some(known) = cache.get(provider) else { return CatalogData::default() };
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
config: known.config.clone(),
thought_levels: known.thought_levels.clone(),
refreshed_at_ms: None,
})
}
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
self.state
.lock()
.entries
.get(&Self::key(shared, provider))
.and_then(|e| e.catalog.clone())
.unwrap_or_else(|| Self::fallback(shared, provider))
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: catalog.thought_levels,
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: entry
.retry_at_ms
.filter(|_| entry.completed.is_some_and(|at| self.now().duration_since(at) < COOLDOWN)),
error: entry.error.clone(),
}
}
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
pub(crate) fn request(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
force: bool,
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
let key = Self::key(shared, &spec.id);
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
let now = self.now();
let mut state = self.state.lock();
let changed = state.entries.get(&key).is_none_or(|e| e.context != context);
if changed {
if let Some(abort) = state.entries.get_mut(&key).and_then(|entry| entry.abort.take()) {
abort.abort();
}
state.generation += 1;
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
.and_then(|saved| saved.catalog.refreshed_at_ms)
.map(|at| self.epoch_ms() - at)
.filter(|age| *age >= 0.0 && *age < FRESH_FOR.as_millis() as f64)
.map(|age| Duration::from_secs_f64(age / 1000.0));
let successful = age.and_then(|age| now.checked_sub(age));
let completed = age.filter(|age| *age < COOLDOWN).and_then(|age| now.checked_sub(age));
let retry_at_ms = completed
.and_then(|_| saved.as_ref().and_then(|s| s.catalog.refreshed_at_ms))
.map(|at| at + COOLDOWN.as_millis() as f64);
let catalog = saved.map(|saved| {
let mut catalog = saved.catalog;
if !matching {
catalog.refreshed_at_ms = None;
}
catalog
});
state.entries.insert(
key.clone(),
Entry {
context,
generation,
completed,
successful,
retry_at_ms,
catalog,
error: None,
flight: None,
abort: None,
},
);
}
let entry = state.entries.get_mut(&key).expect("catalog entry");
let cooling = entry.completed.is_some_and(|at| now.duration_since(at) < COOLDOWN);
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
let mut start = None;
if entry.flight.is_none() && !cooling && (force || !fresh) {
let (done, ready) = watch::channel(false);
entry.flight = Some(ready);
entry.error = None;
entry.retry_at_ms = None;
start = Some((entry.generation, done));
}
let snapshot = self.snapshot(shared, &spec.id, entry);
let flight = entry.flight.clone();
drop(state);
if let Some((generation, done)) = start {
self.broadcast(shared, &snapshot);
let coordinator = self.clone();
let shared = shared.clone();
let flight_key = key.clone();
let task = shared.runtime.clone().spawn(async move {
let result = discover(&shared, spec).await;
coordinator.complete(&shared, flight_key, generation, result);
let _ = done.send(true);
});
// A subscriber can re-enter and change configuration during the start event.
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key).filter(|entry| entry.generation == generation) {
if entry.flight.is_some() {
entry.abort = Some(task.abort_handle());
}
} else {
task.abort();
}
}
(snapshot, flight)
}
fn complete(&self, shared: &Shared, key: Key, generation: u64, result: Result<Discovered, String>) {
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
.into_iter()
.find(|spec| spec.id == key.2)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
let mut state = self.state.lock();
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
// Configuration may have changed without another refresh request arriving.
if current.as_ref() != Some(&entry.context) {
entry.flight = None;
entry.abort = None;
entry.completed = None;
entry.retry_at_ms = None;
entry.error = None;
let snapshot = self.snapshot(shared, &key.2, entry);
state.entries.remove(&key);
drop(state);
self.broadcast(shared, &snapshot);
return;
}
let now = self.now();
entry.completed = Some(now);
entry.retry_at_ms = Some(self.epoch_ms() + COOLDOWN.as_millis() as f64);
entry.flight = None;
entry.abort = None;
let success = match result {
Ok(found) => {
let mut cache = shared.known.lock();
let known = cache.entry(key.2.clone()).or_default();
let catalog = CatalogData {
config: found.config,
thought_levels: found.levels,
refreshed_at_ms: Some(self.epoch_ms()),
};
known.config = catalog.config.clone();
known.thought_levels = catalog.thought_levels.clone();
if let Some(commands) = found.commands {
known.commands.insert(shared.root_key(), commands);
}
known.authoritative = true;
known.refreshed_at_ms = catalog.refreshed_at_ms;
known.catalogs.insert(
shared.root_key(),
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
entry.successful = Some(now);
entry.error = None;
true
}
Err(error) => {
entry.error = Some(error);
false
}
};
let snapshot = self.snapshot(shared, &key.2, entry);
drop(state);
self.broadcast(shared, &snapshot);
if success {
for subscriber in self.subscribers(shared) {
subscriber.emit(AgentEvent::Providers);
}
}
}
fn subscribers(&self, shared: &Shared) -> Vec<Arc<Shared>> {
self.state
.lock()
.subscribers
.iter()
.filter_map(Weak::upgrade)
.filter(|s| {
s.paths.models_file == shared.paths.models_file && s.paths.project_root == shared.paths.project_root
})
.collect()
}
fn broadcast(&self, shared: &Shared, catalog: &AgentModelCatalog) {
for subscriber in self.subscribers(shared) {
subscriber.emit(AgentEvent::ModelCatalog { catalog: catalog.clone() });
}
}
}
impl crate::AgentManager {
/// Return cached choices immediately and schedule discovery when eligible.
pub fn refresh_models(&self, provider: &str, force: bool) -> IdeResult<AgentModelCatalog> {
// Settings and environment secrets can change while this window is open.
*self.shared.providers.write() =
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force).0)
}
}
async fn discover(shared: &Arc<Shared>, spec: provider::ProviderSpec) -> Result<Discovered, String> {
match spec.driver {
provider::Driver::Acp => acp::discover::run(shared, &spec).await,
provider::Driver::Codex => native::codex::discover(spec, shared.paths.project_root.clone()).await,
provider::Driver::Claude => {
let found = native::claude::discover(spec.clone(), shared.paths.project_root.clone()).await?;
Ok(Discovered {
commands: Some(config::commands_of(
&serde_json::json!({ "availableCommands": found.commands }),
&spec.id,
)),
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
levels: found
.efforts
.into_iter()
.map(|(model, option)| {
let levels = option
.map(|o| config::options_of(&serde_json::json!({ "configOptions": [o] })))
.unwrap_or_default();
(model, levels)
})
.collect(),
})
}
}
}
#[cfg(test)]
mod tests;
+501
Переглянути файл
@@ -0,0 +1,501 @@
use super::*;
use crate::{AgentManager, AgentPaths, Connector};
use ide_jsonrpc::{Framing, Peer};
use serde_json::{Value, json};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{mpsc, oneshot};
const PROVIDER: &str = "catalog-test";
#[derive(Debug)]
struct Pending {
params: Value,
reply: oneshot::Sender<Result<Value, String>>,
}
struct Harness {
connector: Connector,
pending: mpsc::UnboundedReceiver<Pending>,
launches: Arc<AtomicUsize>,
live: Arc<AtomicUsize>,
}
struct Live(Arc<AtomicUsize>);
impl Drop for Live {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
impl Harness {
fn new() -> Self {
let (pending_tx, pending) = mpsc::unbounded_channel();
let launches = Arc::new(AtomicUsize::new(0));
let live = Arc::new(AtomicUsize::new(0));
let connector: Connector = Arc::new({
let launches = launches.clone();
let live = live.clone();
move |_, _, client, _| {
launches.fetch_add(1, Ordering::SeqCst);
live.fetch_add(1, Ordering::SeqCst);
let guard = Live(live.clone());
let pending = pending_tx.clone();
let (client_io, server_io) = tokio::io::duplex(1 << 16);
let (read, mut write) = tokio::io::split(server_io);
tokio::spawn(async move {
let _guard = guard;
let mut lines = BufReader::new(read).lines();
while let Some(line) = lines.next_line().await.unwrap() {
let request: Value = serde_json::from_str(&line).unwrap();
let id = &request["id"];
if id.is_null() {
continue;
}
let response = match request["method"].as_str().unwrap() {
"initialize" => json!({ "id": id, "jsonrpc": "2.0", "result": {
"protocolVersion": 1, "agentCapabilities": {}, "authMethods": [] } }),
"session/new" => {
let (reply, result) = oneshot::channel();
pending.send(Pending { params: request["params"].clone(), reply }).unwrap();
let result = tokio::select! {
result = result => result.unwrap(),
_ = lines.next_line() => break,
};
match result {
Ok(result) => json!({ "id": id, "jsonrpc": "2.0", "result": result }),
Err(error) => {
json!({ "id": id, "jsonrpc": "2.0", "error": { "code": -32000, "message": error } })
}
}
}
method => panic!("discovery must not call {method}"),
};
if write.write_all(format!("{response}\n").as_bytes()).await.is_err() {
break;
}
}
});
let (read, write) = tokio::io::split(client_io);
Ok(Peer::connect_framed(read, write, client, Framing::Lines))
}
});
Self { connector, pending, launches, live }
}
async fn next(&mut self) -> Pending {
tokio::time::timeout(Duration::from_secs(5), self.pending.recv()).await.unwrap().unwrap()
}
}
fn configure(root: &Path, version: &str) {
std::fs::create_dir_all(root.join("agents")).unwrap();
let executable = root.join("catalog-test-bin");
if !executable.exists() {
std::fs::write(&executable, "first executable").unwrap();
}
std::fs::write(
root.join("agents/catalog-test.toml"),
format!(
"name = \"Catalog Test\"\ncommand = {}\n[env]\nTOKEN = \"secret-{version}\"\n",
serde_json::to_string(&executable.to_string_lossy()).unwrap()
),
)
.unwrap();
}
fn make_manager(root: &Path, catalogs: Arc<AgentCatalogs>, harness: &Harness) -> AgentManager {
make_manager_at(root, &root.join("models.json"), catalogs, harness)
}
fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>, harness: &Harness) -> AgentManager {
AgentManager::with_connector(
AgentPaths {
project_root: root.to_path_buf(),
store_dir: root.join("store"),
worktrees_dir: root.join("worktrees"),
models_file: models_file.to_path_buf(),
catalogs,
custom_agents_dir: Some(root.join("agents")),
home_dir: Some(root.to_path_buf()),
env_secrets: None,
},
tokio::runtime::Handle::current(),
harness.connector.clone(),
)
}
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
let (tx, rx) = mpsc::unbounded_channel();
manager.subscribe(Arc::new(move |event| {
let _ = tx.send(event);
}));
rx
}
async fn completed(events: &mut mpsc::UnboundedReceiver<AgentEvent>) -> AgentModelCatalog {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let AgentEvent::ModelCatalog { catalog } = events.recv().await.unwrap()
&& !catalog.refreshing
{
return catalog;
}
}
})
.await
.unwrap()
}
fn response(models: &[&str], effort: &[&str]) -> Value {
json!({ "sessionId": "discovery-only", "configOptions": [
{ "id": "model", "type": "select", "category": "model", "currentValue": models.first(),
"options": models.iter().map(|m| json!({ "value": m, "name": m })).collect::<Vec<_>>() },
{ "id": "effort", "type": "select", "category": "thought_level", "currentValue": effort.first(),
"options": effort.iter().map(|e| json!({ "value": e })).collect::<Vec<_>>() }
] })
}
fn model_values(catalog: &AgentModelCatalog) -> Vec<&str> {
catalog
.config
.iter()
.filter(|o| o.category.as_deref() == Some("model"))
.flat_map(|o| o.values.iter().map(|v| v.value.as_str()))
.collect()
}
async fn stopped(harness: &Harness) {
tokio::time::timeout(Duration::from_secs(5), async {
while harness.live.load(Ordering::SeqCst) != 0 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
fn advance(catalogs: &AgentCatalogs, seconds: u64) {
catalogs.clock_ms.fetch_add(seconds * 1000, Ordering::Relaxed);
}
#[tokio::test]
async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_revert_it() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
let cached = manager.refresh_models(PROVIDER, false).unwrap();
assert!(cached.refreshing);
assert_eq!(model_values(&cached), ["old", "retained"]);
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
let pending = harness.next().await;
assert_eq!(pending.params["mcpServers"], json!([]));
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
let fresh = completed(&mut events).await;
assert_eq!(model_values(&fresh), ["retained", "new"]);
assert_eq!(fresh.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["new", "retained"]);
assert_eq!(fresh.thought_levels["retained"][0].values[0].value, "medium");
assert!(fresh.refreshed_at_ms.is_some() && fresh.retry_at_ms.is_some());
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
assert_eq!(manager.refresh_models(PROVIDER, false).unwrap().config, fresh.config);
let provider = manager.providers().into_iter().find(|p| p.id == PROVIDER).unwrap();
assert_eq!(provider.config, fresh.config);
let persisted = std::fs::read_to_string(tmp.path().join("models.json")).unwrap();
assert!(!persisted.contains("secret-one") && !persisted.contains("TOKEN"));
let restored = make_manager(tmp.path(), Arc::default(), &harness);
let restored_snapshot = restored.refresh_models(PROVIDER, false).unwrap();
assert!(!restored_snapshot.refreshing, "matching persisted launch context remains fresh");
assert_eq!(restored_snapshot.refreshed_at_ms, fresh.refreshed_at_ms);
let provider = restored.providers().into_iter().find(|p| p.id == PROVIDER).unwrap();
assert_eq!(provider.config, fresh.config);
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
}
#[tokio::test]
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let options = config::options_of(&response(&["legacy"], &["low"]));
std::fs::write(
tmp.path().join("models.json"),
serde_json::to_vec(&json!({
(PROVIDER): { "config": options, "thoughtLevels": {}, "projectCommands": {} }
}))
.unwrap(),
)
.unwrap();
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
let cached = manager.refresh_models(PROVIDER, false).unwrap();
assert_eq!(model_values(&cached), ["legacy"]);
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
let failed = completed(&mut events).await;
assert_eq!(failed.config, cached.config);
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
}
#[tokio::test]
async fn concurrent_windows_commands_and_manual_requests_share_one_flight_and_cooldown() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let first = Arc::new(make_manager(tmp.path(), catalogs.clone(), &harness));
let second = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut first_events = events(&first);
let mut second_events = events(&second);
assert!(first.refresh_models(PROVIDER, false).unwrap().refreshing);
let pending = harness.next().await;
for _ in 0..10 {
assert!(second.refresh_models(PROVIDER, true).unwrap().refreshing);
assert!(first.refresh_models(PROVIDER, true).unwrap().refreshing);
}
let commands = tokio::spawn({
let first = first.clone();
async move { first.commands(PROVIDER, None).await }
});
tokio::task::yield_now().await;
assert_eq!(harness.launches.load(Ordering::SeqCst), 1);
pending.reply.send(Ok(response(&["one"], &["low"]))).unwrap();
let done = completed(&mut first_events).await;
assert_eq!(completed(&mut second_events).await, done);
commands.await.unwrap().unwrap();
for force in [false, true, false, true] {
assert!(!second.refresh_models(PROVIDER, force).unwrap().refreshing);
}
advance(&catalogs, 29);
assert!(!first.refresh_models(PROVIDER, true).unwrap().refreshing);
advance(&catalogs, 1);
assert!(!first.refresh_models(PROVIDER, false).unwrap().refreshing, "automatic refresh remains fresh");
assert!(first.refresh_models(PROVIDER, true).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["two"], &["high"]))).unwrap();
let newer = completed(&mut first_events).await;
assert_eq!(model_values(&newer), ["two"]);
assert_eq!(completed(&mut second_events).await, newer);
advance(&catalogs, 15 * 60 - 1);
assert!(!second.refresh_models(PROVIDER, false).unwrap().refreshing);
advance(&catalogs, 1);
assert!(second.refresh_models(PROVIDER, false).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["three"], &["low"]))).unwrap();
completed(&mut first_events).await;
assert_eq!(harness.launches.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn failure_keeps_successful_choices_and_throttles_manual_and_auto_retries() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, true).unwrap();
harness.next().await.reply.send(Ok(response(&["cached"], &["low"]))).unwrap();
let success = completed(&mut events).await;
let disk = std::fs::read(tmp.path().join("models.json")).unwrap();
advance(&catalogs, 15 * 60);
manager.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Err("Authentication expired".into())).unwrap();
let failed = completed(&mut events).await;
assert_eq!(failed.config, success.config);
assert_eq!(failed.thought_levels, success.thought_levels);
assert_eq!(failed.refreshed_at_ms, success.refreshed_at_ms);
assert!(failed.error.as_deref().unwrap().contains("Authentication expired"));
assert_eq!(std::fs::read(tmp.path().join("models.json")).unwrap(), disk);
assert!(!manager.refresh_models(PROVIDER, false).unwrap().refreshing);
assert!(!manager.refresh_models(PROVIDER, true).unwrap().refreshing);
advance(&catalogs, 29);
assert!(!manager.refresh_models(PROVIDER, true).unwrap().refreshing);
advance(&catalogs, 1);
assert!(manager.refresh_models(PROVIDER, false).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["recovered"], &["high"]))).unwrap();
let recovered = completed(&mut events).await;
assert_eq!(model_values(&recovered), ["recovered"]);
assert!(recovered.error.is_none());
}
#[tokio::test]
async fn timeout_cleans_up_and_enters_the_same_failure_cooldown() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false).unwrap();
let pending = harness.next().await;
tokio::time::pause();
tokio::time::advance(Duration::from_secs(4)).await;
let failed = completed(&mut events).await;
assert!(failed.error.as_deref().unwrap().contains("time"));
assert!(failed.retry_at_ms.is_some());
assert!(!manager.refresh_models(PROVIDER, true).unwrap().refreshing);
assert!(!manager.refresh_models(PROVIDER, false).unwrap().refreshing);
tokio::time::resume();
stopped(&harness).await;
assert_eq!(harness.live.load(Ordering::SeqCst), 0, "timed-out connection must close");
assert!(pending.reply.is_closed());
advance(&catalogs, 30);
assert!(manager.refresh_models(PROVIDER, false).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["retry"], &["low"]))).unwrap();
completed(&mut events).await;
}
#[tokio::test]
async fn changed_effective_config_supersedes_old_completion_without_queueing() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let first = make_manager(tmp.path(), catalogs.clone(), &harness);
let second = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&second);
first.refresh_models(PROVIDER, false).unwrap();
let obsolete = harness.next().await;
configure(tmp.path(), "two");
assert!(second.refresh_models(PROVIDER, false).unwrap().refreshing);
let latest = harness.next().await;
latest.reply.send(Ok(response(&["latest"], &["high"]))).unwrap();
let fresh = completed(&mut events).await;
let _ = obsolete.reply.send(Ok(response(&["obsolete"], &["low"])));
stopped(&harness).await;
let shown = first.refresh_models(PROVIDER, false).unwrap();
assert_eq!(shown.config, fresh.config);
assert_eq!(shown.refreshed_at_ms, fresh.refreshed_at_ms);
assert!(!shown.refreshing);
assert_eq!(harness.launches.load(Ordering::SeqCst), 2);
assert!(!std::fs::read_to_string(tmp.path().join("models.json")).unwrap().contains("obsolete"));
// A changed configuration also invalidates successful freshness/cooldown.
configure(tmp.path(), "three");
assert!(first.refresh_models(PROVIDER, false).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["new-config"], &["medium"]))).unwrap();
completed(&mut events).await;
}
#[tokio::test]
async fn invalid_provider_is_a_request_error_and_does_not_launch() {
let tmp = tempfile::tempdir().unwrap();
let harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
assert!(manager.refresh_models("missing-provider", true).is_err());
assert_eq!(harness.launches.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn replacing_the_executable_at_the_same_path_invalidates_freshness_and_obsolete_responses() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "unchanged-environment");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), catalogs, &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false).unwrap();
let obsolete = harness.next().await;
std::fs::write(tmp.path().join("catalog-test-bin"), "replacement executable with different size").unwrap();
manager.refresh_models(PROVIDER, false).unwrap();
let latest = harness.next().await;
latest.reply.send(Ok(response(&["updated"], &["high"]))).unwrap();
let fresh = completed(&mut events).await;
let _ = obsolete.reply.send(Ok(response(&["obsolete"], &["low"])));
stopped(&harness).await;
assert_eq!(manager.refresh_models(PROVIDER, false).unwrap().config, fresh.config);
std::fs::write(tmp.path().join("catalog-test-bin"), "another executable").unwrap();
assert!(manager.refresh_models(PROVIDER, false).unwrap().refreshing);
harness.next().await.reply.send(Ok(response(&["new-install"], &["medium"]))).unwrap();
assert_eq!(model_values(&completed(&mut events).await), ["new-install"]);
assert_eq!(harness.launches.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn project_catalogs_and_persisted_freshness_do_not_leak_between_contexts() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("project-a");
let b = tmp.path().join("project-b");
configure(&a, "account-a");
configure(&b, "account-b");
let models_file = tmp.path().join("shared-models.json");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let first = make_manager_at(&a, &models_file, catalogs.clone(), &harness);
let second = make_manager_at(&b, &models_file, catalogs, &harness);
let mut first_events = events(&first);
let mut second_events = events(&second);
first.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Ok(response(&["account-a-model"], &["low"]))).unwrap();
let a_catalog = completed(&mut first_events).await;
second.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Ok(response(&["account-b-model"], &["high"]))).unwrap();
let b_catalog = completed(&mut second_events).await;
assert_eq!(first.refresh_models(PROVIDER, false).unwrap().config, a_catalog.config);
assert_eq!(second.refresh_models(PROVIDER, false).unwrap().config, b_catalog.config);
assert_eq!(first.providers().into_iter().find(|p| p.id == PROVIDER).unwrap().config, a_catalog.config);
for (root, expected) in [(&a, &a_catalog), (&b, &b_catalog)] {
let restored = make_manager_at(root, &models_file, Arc::default(), &harness);
let cached = restored.refresh_models(PROVIDER, false).unwrap();
assert!(!cached.refreshing, "matching persisted context should retain freshness");
assert_eq!(cached.config, expected.config);
assert_eq!(cached.refreshed_at_ms, expected.refreshed_at_ms);
}
assert_eq!(harness.launches.load(Ordering::SeqCst), 2);
configure(&a, "new-account");
let changed = make_manager_at(&a, &models_file, Arc::default(), &harness);
let mut events = events(&changed);
let stale = changed.refresh_models(PROVIDER, false).unwrap();
assert!(stale.refreshing, "a different launch environment cannot reuse persisted freshness");
assert!(stale.refreshed_at_ms.is_none());
assert_eq!(stale.config, a_catalog.config, "stale cached choices remain selectable");
harness.next().await.reply.send(Ok(response(&["new-account-model"], &["medium"]))).unwrap();
completed(&mut events).await;
let persisted = std::fs::read_to_string(models_file).unwrap();
assert!(!persisted.contains("secret-") && !persisted.contains("TOKEN"));
}
#[tokio::test]
async fn configuration_changed_without_another_request_also_discards_old_discovery() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "before");
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false).unwrap();
let obsolete = harness.next().await;
configure(tmp.path(), "after");
obsolete.reply.send(Ok(response(&["obsolete"], &["low"]))).unwrap();
let discarded = completed(&mut events).await;
assert!(model_values(&discarded).is_empty());
assert!(discarded.refreshed_at_ms.is_none());
assert!(!tmp.path().join("models.json").exists());
manager.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Ok(response(&["current"], &["high"]))).unwrap();
assert_eq!(model_values(&completed(&mut events).await), ["current"]);
}
#[tokio::test]
async fn successful_empty_catalog_removes_all_previous_models_and_efforts() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let catalogs = Arc::new(AgentCatalogs::default());
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, true).unwrap();
harness.next().await.reply.send(Ok(response(&["removed"], &["low"]))).unwrap();
completed(&mut events).await;
advance(&catalogs, 30);
manager.refresh_models(PROVIDER, true).unwrap();
harness.next().await.reply.send(Ok(response(&[], &[]))).unwrap();
let empty = completed(&mut events).await;
assert!(model_values(&empty).is_empty() && empty.thought_levels.is_empty());
assert!(empty.refreshed_at_ms.is_some() && empty.error.is_none());
}
+63 -149
Переглянути файл
@@ -8,6 +8,7 @@
//! next prompt when the agent supports `session/load`.
mod acp;
mod catalogs;
mod config;
mod conversation;
mod external;
@@ -21,6 +22,7 @@ mod skills;
mod timeline;
mod worktree;
pub use catalogs::AgentCatalogs;
pub use external::ExternalSession;
pub use model::*;
@@ -88,6 +90,8 @@ pub struct AgentPaths {
pub worktrees_dir: PathBuf,
/// Settings each agent offered last time (shared by all projects), and its commands per project.
pub models_file: PathBuf,
/// Shared by every project/window on this backend.
pub catalogs: Arc<AgentCatalogs>,
/// User-defined agents, one `<id>.toml` each (`name`, `command`, `args`, `env`).
pub custom_agents_dir: Option<PathBuf>,
/// The user's home: its `.claude` holds their own skills and commands.
@@ -123,12 +127,10 @@ struct Shared {
sink: RwLock<Option<AgentSink>>,
security: RwLock<Option<SecurityHook>>,
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
known: Mutex<HashMap<String, Known>>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
probes: Mutex<HashMap<String, AgentProbe>>,
/// One pre-session lookup of commands and settings per provider, including failed attempts.
command_fetches: Mutex<HashMap<String, tokio::sync::watch::Receiver<bool>>>,
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
idle_release_ms: AtomicU64,
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
@@ -145,6 +147,14 @@ struct Known {
/// By project root: skills and custom commands differ per project.
#[serde(default, rename = "projectCommands")]
commands: HashMap<String, Vec<AgentCommand>>,
/// Successful discovery, unlike a session report, owns availability.
#[serde(default)]
authoritative: bool,
#[serde(default, rename = "refreshedAtMs")]
refreshed_at_ms: Option<f64>,
/// Authoritative availability and freshness are scoped to project and launch context.
#[serde(default, rename = "projectCatalogs")]
catalogs: HashMap<String, catalogs::SavedCatalog>,
}
impl Shared {
@@ -171,7 +181,11 @@ impl Shared {
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
let config = self.paths.catalogs.cached(self, provider).config;
self.config_for_new_task(config, provider)
}
fn config_for_new_task(&self, mut config: Vec<AgentConfigOption>, provider: &str) -> Vec<AgentConfigOption> {
// Model-specific options are offered separately, never as provider-wide defaults.
config.retain(|o| o.category.as_deref() != Some("thought_level"));
config::add_client_options(provider, &mut config);
@@ -197,80 +211,6 @@ impl Shared {
cache.get(provider).and_then(|k| k.commands.get(&self.root_key())).cloned().unwrap_or_default()
}
async fn fetch_settings(self: &Arc<Self>, spec: provider::ProviderSpec) {
let mut ready = {
let mut fetches = self.command_fetches.lock();
fetches
.entry(spec.id.clone())
.or_insert_with(|| {
let (done, ready) = tokio::sync::watch::channel(false);
let shared = self.clone();
// Keep the lookup alive if a composer unmounts while it is waiting.
self.runtime.spawn(async move {
tracing::info!("agent {}: settings discovery started", spec.id);
let discovered = if spec.driver == provider::Driver::Acp {
acp::discover::run(&shared, &spec).await.map(|_| None)
} else if spec.driver == provider::Driver::Claude {
native::claude::discover(spec.clone(), shared.paths.project_root.clone()).await.map(Some)
} else {
return;
};
if let Ok(Some(found)) = discovered {
let commands =
config::commands_of(&json!({ "availableCommands": found.commands }), &spec.id);
let options = config::options_of(&json!({ "configOptions": found.options }));
let levels: Vec<_> = found
.efforts
.into_iter()
.map(|(model, o)| {
let options = o.map(|o| config::options_of(&json!({ "configOptions": [o] })));
(model, options.unwrap_or_default())
})
.collect();
let _ = tokio::task::spawn_blocking(move || {
// Notifies subscribers itself when the discovery
// changed the cached config; unchanged results
// stay silent.
shared.remember_discovered(&spec.id, &options, &commands, &levels);
})
.await;
} else if let Err(e) = discovered {
tracing::info!("agent {}: settings discovery failed: {e}", spec.id);
}
let _ = done.send(true);
});
ready
})
.clone()
};
while !*ready.borrow_and_update() {
if ready.changed().await.is_err() {
break;
}
}
}
fn has_config(&self, provider: &str) -> bool {
self.known.lock().get(provider).is_some_and(|k| !k.config.is_empty())
}
/// Whether the thinking levels of every model the agent offers are known (#1686).
fn knows_all_levels(&self, provider: &str) -> bool {
let cache = self.known.lock();
let Some(known) = cache.get(provider) else { return false };
let models: Vec<&str> = known
.config
.iter()
.filter(|o| o.category.as_deref() == Some("model"))
.flat_map(|o| o.values.iter().map(|v| v.value.as_str()))
.collect();
// No advertised models yet: nothing to attach effort levels to.
if models.is_empty() {
return false;
}
models.iter().all(|id| known.thought_levels.contains_key(*id))
}
fn root_key(&self) -> String {
self.paths.project_root.to_string_lossy().into_owned()
}
@@ -283,78 +223,48 @@ impl Shared {
commands: Option<&[AgentCommand]>,
model: Option<&str>,
) {
self.remember_inner(provider, config, commands, model, &[], false);
}
/// `levels`: each model's thinking-level options, so a new task offers them for any model
/// it picks (#1686). A session's report for a model wins over these.
fn remember_discovered(
&self,
provider: &str,
config: &[AgentConfigOption],
commands: &[AgentCommand],
levels: &[(String, Vec<AgentConfigOption>)],
) {
self.remember_inner(provider, Some(config), Some(commands), model_of(config).as_deref(), levels, true);
}
fn remember_inner(
&self,
provider: &str,
config: Option<&[AgentConfigOption]>,
commands: Option<&[AgentCommand]>,
model: Option<&str>,
discovered_levels: &[(String, Vec<AgentConfigOption>)],
discovered: bool,
) {
// Keep the update and its disk write ordered; a session report wins over discovery.
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
let mut changed = false;
for (model, levels) in discovered_levels {
if !known.thought_levels.contains_key(model) {
known.thought_levels.insert(model.clone(), levels.clone());
changed = true;
}
}
if let Some(c) = config.filter(|_| !discovered || known.config.is_empty()) {
// Running tasks retain their own reported settings. Once discovery has
// succeeded, a session's older list/defaults cannot change New Task choices.
if !known.authoritative
&& let Some(config) = config.filter(|c| !c.is_empty())
{
if let Some(model) = model {
let levels: Vec<_> =
c.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
config.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
if known.thought_levels.get(model) != Some(&levels) {
known.thought_levels.insert(model.to_owned(), levels);
changed = true;
}
}
if !c.is_empty() && known.config != c {
known.config = c.to_vec();
if known.config != config {
known.config = config.to_vec();
changed = true;
}
}
let root = self.root_key();
if let Some(c) = commands.filter(|c| {
!c.is_empty()
&& (!discovered || known.commands.get(&root).is_none_or(Vec::is_empty))
&& known.commands.get(&root).map(Vec::as_slice) != Some(c)
}) {
known.commands.insert(root, c.to_vec());
if let Some(commands) = commands.filter(|c| !c.is_empty())
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
{
known.commands.insert(self.root_key(), commands.to_vec());
changed = true;
}
if !changed {
return;
if changed {
self.persist_known(&cache);
}
if let Ok(bytes) = serde_json::to_vec_pretty(&*cache)
drop(cache);
if changed {
self.emit(AgentEvent::Providers);
}
}
fn persist_known(&self, cache: &HashMap<String, Known>) {
if let Ok(bytes) = serde_json::to_vec_pretty(cache)
&& let Err(e) = write_file(&self.paths.models_file, &bytes)
{
tracing::warn!("saving agent settings: {e}");
}
// The cached provider config actually changed (a session report, discovery,
// or a turn update): tell subscribers to re-list, so a changed model list
// reaches the composer without waiting for the next task (#1490). Unchanged
// reports stay silent, so routine session traffic emits nothing. The cache
// lock is released first; the sink never runs under it.
drop(cache);
self.emit(AgentEvent::Providers);
}
}
@@ -469,8 +379,7 @@ impl AgentManager {
}
fn with_connector(paths: AgentPaths, runtime: tokio::runtime::Handle, connector: Connector) -> Self {
let known =
std::fs::read(&paths.models_file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
let known = paths.catalogs.store(&paths.models_file);
let providers = RwLock::new(provider::load(paths.custom_agents_dir.as_deref(), paths.env_secrets.as_deref()));
let shared = Arc::new(Shared {
paths,
@@ -479,13 +388,13 @@ impl AgentManager {
sink: RwLock::new(None),
security: RwLock::new(None),
new_task_approvals: RwLock::new(None),
known: Mutex::new(known),
known,
providers,
probes: Mutex::new(HashMap::new()),
command_fetches: Mutex::new(HashMap::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
});
shared.paths.catalogs.subscribe(&shared);
let mut tasks = HashMap::new();
for file in std::fs::read_dir(&shared.paths.store_dir).into_iter().flatten().flatten() {
let path = file.path();
@@ -542,9 +451,9 @@ impl AgentManager {
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
.map(|p| {
let mut info = provider::describe(p);
info.config = self.shared.known_config(&p.id);
info.thought_levels =
self.shared.known.lock().get(&p.id).map(|k| k.thought_levels.clone()).unwrap_or_default();
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = catalog.thought_levels;
info.commands = self.shared.known_commands(&p.id);
info
})
@@ -632,17 +541,20 @@ impl AgentManager {
// merged without duplicating what `availableCommands` or the disk offer.
let mut offered = offered;
if task.is_none()
&& (offered.is_empty() || !self.shared.has_config(&provider) || !self.shared.knows_all_levels(&provider))
&& let Some(spec) = self
.shared
.spec(&provider)
.filter(|s| matches!(s.driver, provider::Driver::Claude | provider::Driver::Acp))
&& let Some(spec) =
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
.into_iter()
.find(|spec| spec.id == provider)
{
let claude = spec.driver == provider::Driver::Claude;
self.shared.fetch_settings(spec).await;
if claude {
offered = self.shared.known_commands(&provider);
let (_, flight) = self.shared.paths.catalogs.request(&self.shared, spec, false);
if let Some(mut ready) = flight {
while !*ready.borrow_and_update() {
if ready.changed().await.is_err() {
break;
}
}
}
offered = self.shared.known_commands(&provider);
}
for &(name, description) in builtin_commands(&provider) {
if !offered.iter().any(|c| c.name == name) {
@@ -794,16 +706,18 @@ impl AgentManager {
}
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let mut config = self.shared.known_config(&spec.id);
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
if let Some(model) = model_of(&config)
&& let Some(levels) = self.shared.known.lock().get(&spec.id).and_then(|k| k.thought_levels.get(&model))
&& let Some(levels) = levels.remove(&model)
{
config.extend(levels.iter().cloned().map(|mut o| {
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) =
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
{
+17
Переглянути файл
@@ -538,6 +538,19 @@ pub struct AgentChanges {
pub commits: Vec<AgentCommit>,
}
/// Authoritative choices for new tasks, independent of any running session's settings.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentModelCatalog {
pub provider: String,
pub config: Vec<AgentConfigOption>,
pub thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
pub refreshing: bool,
pub refreshed_at_ms: Option<f64>,
pub retry_at_ms: Option<f64>,
pub error: Option<String>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
@@ -575,6 +588,10 @@ pub enum AgentEvent {
provider: String,
limits: Vec<AgentLimit>,
},
/// A model lookup started or completed, including unsuccessful lookups.
ModelCatalog {
catalog: AgentModelCatalog,
},
/// The installed or configured agent providers changed.
Providers,
}
+2
Переглянути файл
@@ -85,6 +85,8 @@ pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discove
let (spec, cwd) = spec.await.map_err(|e| e.to_string())?;
let mut args = spec.args;
args.extend(Start::New { id: uuid::Uuid::new_v4().to_string() }.args());
// Metadata discovery must not launch project-configured MCP servers.
args.extend(["--strict-mcp-config".into(), "--mcp-config".into(), "{\"mcpServers\":{}}".into()]);
let launch = Launch { program: spec.command, args, cwd, env: spec.env };
let mut io = cli::Process.launch(&launch, Arc::new(|_| {})).map_err(|e| e.to_string())?;
let _stop = io.kill.clone().drop_guard();
+98 -37
Переглянути файл
@@ -44,6 +44,92 @@ pub(crate) fn connect(
})
}
/// A model lookup uses app-server directly: no thread, task, prompt or project MCP.
pub(crate) async fn discover(
spec: ProviderSpec,
cwd: std::path::PathBuf,
) -> Result<crate::catalogs::Discovered, String> {
let spec = tokio::task::spawn_blocking({
let cwd = cwd.clone();
move || spec.resolve_for_launch(&cwd)
})
.await
.map_err(|e| e.to_string())?;
let peer = Peer::spawn_framed(
&spec.command,
&spec.args,
&cwd,
&spec.env,
Arc::new(ide_jsonrpc::NoopHandler),
Box::new(|_| {}),
Framing::Lines,
)
.map_err(|e| e.to_string())?;
let _stop = crate::catalogs::KillPeer(peer.clone());
tokio::time::timeout(Duration::from_secs(30), async {
let _: Value = peer.request("initialize", initialize_params(), None).await.map_err(|e| e.to_string())?;
peer.notify("initialized", Value::Null).map_err(|e| e.to_string())?;
let mut models = list_models(&peer).await.map_err(|e| e.message)?;
models.retain(|model| !model.hidden);
let mut settings = Settings::of(&json!({}), &models);
if settings.model.is_empty()
&& let Some(model) = models.first()
{
settings.model = model.id.clone();
settings.fit_effort(&models);
}
let options = translate::config_options(&models, &settings);
let config = crate::config::options_of(&json!({ "configOptions": options }));
let levels = models
.iter()
.map(|model| {
let mut settings = settings.clone();
settings.model = model.id.clone();
settings.fit_effort(&models);
let options = translate::config_options(&models, &settings);
let levels = crate::config::options_of(&json!({ "configOptions": options }))
.into_iter()
.filter(|o| o.category.as_deref() == Some("thought_level"))
.collect();
(model.id.clone(), levels)
})
.collect();
Ok(crate::catalogs::Discovered { config, commands: None, levels })
})
.await
.map_err(|_| "Codex model discovery timed out".to_owned())?
}
fn initialize_params() -> Value {
json!({
"clientInfo": { "name": "openidea", "title": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
"capabilities": { "experimentalApi": true, "optOutNotificationMethods": OPT_OUT },
})
}
async fn list_models(peer: &Peer) -> Result<Vec<ModelInfo>, ResponseError> {
let mut all = Vec::new();
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page: Value = peer.request("model/list", json!({ "cursor": cursor }), None).await.map_err(from_codex)?;
let Some(data) = page.get("data").and_then(Value::as_array) else {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
};
let models = translate::models_of(&page);
if models.len() != data.len() {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
}
all.extend(models);
match page.get("nextCursor") {
None | Some(Value::Null) => return Ok(all),
Some(Value::String(next)) if next.is_empty() => return Ok(all),
Some(Value::String(next)) if seen.insert(next.clone()) => cursor = json!(next),
_ => return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model-list cursor")),
}
}
}
/// Connects `client` to a shim driving the codex connection `connect_codex` opens (it
/// gets the handler for what codex sends). Each side's end closes the other.
fn attach(
@@ -250,15 +336,7 @@ impl CodexShim {
}
async fn initialize(&self) -> Result<Value, ResponseError> {
let info = self
.call(
"initialize",
json!({
"clientInfo": { "name": "openidea", "title": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
"capabilities": { "experimentalApi": true, "optOutNotificationMethods": OPT_OUT },
}),
)
.await?;
let info = self.call("initialize", initialize_params()).await?;
self.codex().notify("initialized", Value::Null).map_err(from_codex)?;
self.state.lock().initialized = true;
// `<client>/<codex version> (<platform>) …`
@@ -282,32 +360,15 @@ impl CodexShim {
}))
}
/// The models codex offers; empty when it can't list them.
async fn models(&self) -> Arc<Vec<ModelInfo>> {
/// Cache only complete, successful listings; a failed page must never become availability.
async fn models(&self) -> Result<Arc<Vec<ModelInfo>>, ResponseError> {
let mut cached = self.models.lock().await;
if let Some(m) = cached.as_ref() {
return m.clone();
if let Some(models) = cached.as_ref() {
return Ok(models.clone());
}
let mut all = Vec::new();
let mut cursor = Value::Null;
loop {
match self.call("model/list", json!({ "cursor": cursor })).await {
Ok(page) => {
all.extend(translate::models_of(&page));
match page.get("nextCursor").filter(|c| c.is_string()) {
Some(next) if *next != cursor => cursor = next.clone(),
_ => break,
}
}
Err(e) => {
tracing::warn!("codex: listing models failed: {}", e.message);
return Arc::new(all);
}
}
}
let models = Arc::new(all);
let models = Arc::new(list_models(self.codex()).await?);
*cached = Some(models.clone());
models
Ok(models)
}
async fn publish_skills(&self, session: &str) {
@@ -341,7 +402,7 @@ impl CodexShim {
}
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
let models = self.models().await;
let models = self.models().await?;
let mut request = json!({ "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
@@ -358,7 +419,7 @@ impl CodexShim {
/// Resumes the thread and replays its history before answering.
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
let id = str_param(params, "sessionId")?;
let models = self.models().await;
let models = self.models().await?;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
@@ -376,7 +437,7 @@ impl CodexShim {
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let models = self.models().await;
let models = self.models().await?;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
@@ -397,7 +458,7 @@ impl CodexShim {
let session = str_param(params, "sessionId")?;
let option = str_param(params, "configId")?;
let value = str_param(params, "value")?;
let models = self.models().await;
let models = self.models().await?;
let mut state = self.state.lock();
let settings = state
.threads
@@ -414,7 +475,7 @@ impl CodexShim {
if input.is_empty() {
return Err(invalid("empty prompt"));
}
let models = self.models().await;
let models = self.models().await?;
let (done, ended) = oneshot::channel();
let settings = {
let mut state = self.state.lock();
+149
Переглянути файл
@@ -11,6 +11,155 @@ use std::collections::VecDeque;
use std::path::PathBuf;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
struct ModelPages {
pages: Mutex<VecDeque<Result<Value, (i64, String)>>>,
cursors: Mutex<Vec<Value>>,
}
impl Handler for ModelPages {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
assert_eq!(method, "model/list", "listing models must never start a thread or turn");
self.cursors.lock().push(params["cursor"].clone());
self.pages.lock().pop_front().expect("another expected page")
}
}
fn model_peer(pages: Arc<ModelPages>) -> (Peer, Peer) {
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let server = Peer::connect_framed(read, write, pages, Framing::Lines);
let (read, write) = tokio::io::split(ours);
(Peer::connect_framed(read, write, Arc::new(ide_jsonrpc::NoopHandler), Framing::Lines), server)
}
#[tokio::test]
async fn model_pagination_failure_does_not_cache_an_incomplete_catalog() {
let first = json!({ "data": [{ "id": "first" }], "nextCursor": "next" });
let pages = Arc::new(ModelPages {
pages: Mutex::new(VecDeque::from([
Ok(first.clone()),
Err((-32000, "authentication expired".into())),
Ok(first),
Ok(json!({ "data": [{ "id": "second" }], "nextCursor": null })),
])),
cursors: Mutex::default(),
});
let (peer, server) = model_peer(pages.clone());
let shim = CodexShim {
runtime: tokio::runtime::Handle::current(),
codex: OnceLock::from(peer.clone()),
client: OnceLock::new(),
state: Mutex::default(),
models: tokio::sync::Mutex::new(None),
skills: tokio::sync::Mutex::new(()),
};
assert_eq!(shim.models().await.unwrap_err().message, "authentication expired");
let models = shim.models().await.unwrap();
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["first", "second"]);
assert_eq!(shim.models().await.unwrap().len(), 2);
assert_eq!(*pages.cursors.lock(), [Value::Null, json!("next"), Value::Null, json!("next")]);
peer.kill();
server.kill();
}
#[tokio::test]
async fn repeated_or_invalid_model_cursors_and_malformed_pages_are_failures() {
for pages in [
vec![json!({ "data": [], "nextCursor": "a" }), json!({ "data": [], "nextCursor": "a" })],
vec![
json!({ "data": [], "nextCursor": "a" }),
json!({ "data": [], "nextCursor": "b" }),
json!({ "data": [], "nextCursor": "a" }),
],
vec![json!({ "data": [], "nextCursor": 7 })],
vec![json!({ "nextCursor": null })],
vec![json!({ "data": [{}], "nextCursor": null })],
] {
let pages =
Arc::new(ModelPages { pages: Mutex::new(pages.into_iter().map(Ok).collect()), cursors: Mutex::default() });
let (peer, server) = model_peer(pages);
assert!(list_models(&peer).await.is_err());
peer.kill();
server.kill();
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn native_discovery_only_initializes_and_pages_models_then_stops_the_process() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let script = tmp.path().join("fake-codex");
std::fs::write(
&script,
r#"#!/usr/bin/env python3
import json, os, pathlib, sys
pathlib.Path('pid').write_text(str(os.getpid()))
for line in sys.stdin:
request = json.loads(line)
with pathlib.Path('requests').open('a') as f:
f.write(json.dumps(request) + '\n')
method = request['method']
if method == 'initialized':
continue
if method == 'initialize':
result = {}
elif method == 'model/list':
cursor = request['params']['cursor']
model = 'one' if cursor is None else 'two'
result = {'data': [{'id': model, 'isDefault': cursor is None,
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
'nextCursor': 'second-page' if cursor is None else None}
else:
raise RuntimeError('must not create a thread or prompt: ' + method)
print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': result}), flush=True)
"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let spec = ProviderSpec {
id: "codex".into(),
name: "Codex".into(),
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
args: Vec::new(),
env: Vec::new(),
login_hint: String::new(),
source: crate::AgentSource::Builtin,
};
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
let models: Vec<_> = found
.config
.iter()
.filter(|o| o.category.as_deref() == Some("model"))
.flat_map(|o| o.values.iter().map(|v| v.value.as_str()))
.collect();
assert_eq!(models, ["one", "two"]);
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(
requests.iter().map(|r| r["method"].as_str().unwrap()).collect::<Vec<_>>(),
["initialize", "initialized", "model/list", "model/list"]
);
assert_eq!(requests[2]["params"]["cursor"], Value::Null);
assert_eq!(requests[3]["params"]["cursor"], "second-page");
let pid = std::fs::read_to_string(tmp.path().join("pid")).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let alive = std::process::Command::new("kill").args(["-0", pid.trim()]).output().unwrap().status.success();
if !alive {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("discovery must kill and reap its child");
}
// ---- Pure translations -------------------------------------------------------------
fn models() -> Vec<ModelInfo> {
+1
Переглянути файл
@@ -25,6 +25,7 @@ fn paths(dir: &Path) -> AgentPaths {
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
}
}
+18 -62
Переглянути файл
@@ -405,6 +405,7 @@ fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentMan
// user's profile, when temp lives under it) leaks into the test.
home_dir: Some(dir.to_path_buf()),
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
connector,
@@ -442,7 +443,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn claude_commands_before_session_are_fetched_once_and_saved() {
async fn claude_commands_share_catalog_discovery_and_persist_results() {
use std::os::unix::fs::PermissionsExt;
for outcome in ["success", "session_report", "empty", "settings_timeout", "error", "exit", "timeout", "missing"] {
@@ -502,14 +503,18 @@ for line in sys.stdin:
std::fs::write(root.join(".claude/skills/triage/SKILL.md"), "---\nname: triage\ndescription: Triage\n---\n")
.unwrap();
let mgr = manager(root, Arc::new(FakeAgent::default()));
{
let mut providers = mgr.shared.providers.write();
let spec = providers.iter_mut().find(|p| p.id == "claude").unwrap();
if outcome != "missing" {
spec.command = script.to_string_lossy().into_owned();
}
spec.env = vec![("OUTCOME".into(), outcome.into())];
if outcome != "missing" {
provider::set_builtin_command(&root.join("agents"), None, "claude", Some(&script.to_string_lossy()))
.unwrap();
}
provider::set_builtin_env(
&root.join("agents"),
None,
"claude",
BTreeMap::from([("OUTCOME".into(), outcome.into())]),
)
.unwrap();
mgr.reload_providers();
let concurrent = async {
if outcome == "session_report" {
tokio::time::timeout(Duration::from_secs(10), async {
@@ -553,7 +558,6 @@ for line in sys.stdin:
effort.unwrap().current.as_deref(),
Some(match outcome {
"settings_timeout" => "default",
"session_report" => "low",
_ => "high",
})
);
@@ -571,6 +575,8 @@ for line in sys.stdin:
assert_eq!(launches.lines().count(), 1, "{outcome}");
let args: Vec<String> = serde_json::from_str(launches.trim()).unwrap();
assert!(args.windows(2).any(|a| a == ["--input-format", "stream-json"]));
assert!(args.iter().any(|a| a == "--strict-mcp-config"));
assert!(args.windows(2).any(|a| a == ["--mcp-config", "{\"mcpServers\":{}}"]));
let requests = std::fs::read_to_string(root.join("requests")).unwrap();
let subtypes: Vec<String> = requests
.lines()
@@ -1431,6 +1437,7 @@ async fn real_claude_task_in_a_worktree() {
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
);
@@ -2265,6 +2272,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
custom_agents_dir: Some(agents_dir.clone()),
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
connector,
@@ -2597,6 +2605,7 @@ async fn delete_running_agent(no_load: bool) {
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
connector,
@@ -2659,34 +2668,6 @@ fn mcp_servers_follow_server_state_and_agent_capabilities() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_settings_win_over_discovery_in_memory_and_on_disk() {
for discovery_first in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let options = |model: &str, effort: &str| {
config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": model,
"options": [{ "value": "saved" }, { "value": "discovered" }] },
{ "id": "effort", "category": "thought_level", "type": "select", "currentValue": effort,
"options": [{ "value": "low" }, { "value": "high" }] }
] }))
};
let saved = options("saved", "low");
let discovered = options("discovered", "high");
if discovery_first {
mgr.shared.remember_discovered("claude", &discovered, &[], &[]);
}
mgr.shared.remember("claude", Some(&saved), None, Some("saved"));
mgr.shared.remember_discovered("claude", &discovered, &[], &[]);
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
for mgr in [&mgr, &restored] {
assert_eq!(model_of(&mgr.shared.known_config("claude")).as_deref(), Some("saved"));
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["saved"], saved[1..]);
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn provider_reload_does_not_start_acp_discovery() {
let agent = Arc::new(FakeAgent::default());
@@ -2773,31 +2754,6 @@ async fn discovery_times_out_when_session_new_hangs() {
assert!(!cursor.config.iter().any(|o| o.category.as_deref() == Some("model")));
}
#[tokio::test(flavor = "multi_thread")]
async fn discovered_effort_levels_fill_models_no_session_has_reported() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let effort = |values: &[&str], current: &str| {
config::options_of(&json!({ "configOptions": [
{ "id": "effort", "category": "thought_level", "type": "select", "currentValue": current,
"options": values.iter().map(|v| json!({ "value": v })).collect::<Vec<_>>() }
] }))
};
let model = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "sonnet",
"options": [{ "value": "sonnet" }, { "value": "opus" }] }
] }));
// A session already reported sonnet's levels; discovery adds opus's.
let reported = [model.clone(), effort(&["low", "high"], "high")].concat();
mgr.shared.remember("claude", Some(&reported), None, Some("sonnet"));
let levels =
[("sonnet".to_owned(), effort(&["low"], "low")), ("opus".to_owned(), effort(&["low", "max"], "default"))];
mgr.shared.remember_discovered("claude", &model, &[], &levels);
let known = mgr.shared.known.lock();
assert_eq!(known["claude"].thought_levels["sonnet"], effort(&["low", "high"], "high"), "the session's report wins");
assert_eq!(known["claude"].thought_levels["opus"], effort(&["low", "max"], "default"));
}
#[test]
fn streamed_text_is_sent_as_appends() {
let mut streamed = HashMap::new();
+3
Переглянути файл
@@ -260,6 +260,8 @@ pub struct DebuggerSettings {
pub show_on_breakpoint: bool,
pub focus_app_on_breakpoint: bool,
pub hide_on_termination: bool,
/// A breakpoint or exception hit brings the Debug tool window's Threads & Variables tab to the front.
pub variables_on_breakpoint: bool,
pub breakpoints_any_file: bool,
/// While suspended, hovering the start of a line shows a Run to Cursor button.
pub run_to_cursor_inlay: bool,
@@ -285,6 +287,7 @@ impl Default for DebuggerSettings {
show_on_breakpoint: true,
focus_app_on_breakpoint: false,
hide_on_termination: false,
variables_on_breakpoint: true,
breakpoints_any_file: false,
run_to_cursor_inlay: true,
inline_values: true,
+59 -8
Переглянути файл
@@ -474,10 +474,7 @@ impl Session {
let _ = c.start_kill();
}
if let Some(mut program) = self.program.lock().take() {
let _ = program.child.kill();
let _ = std::thread::Builder::new().name("openidea-debug-reap".into()).spawn(move || {
let _ = program.child.wait();
});
program.kill();
}
}
}
@@ -574,7 +571,7 @@ fn launch_groups(s: &Session) -> Vec<libc::pid_t> {
for child in s.debuggees.lock().iter() {
push(child.id());
}
push(s.program.lock().as_ref().and_then(|p| p.child.process_id()));
push(s.program.lock().as_ref().and_then(ProgramTerminal::process_id));
groups.retain(|g| *g > 0);
groups
}
@@ -874,7 +871,10 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
/// A `runInTerminal` program and the pseudo-terminal it runs in.
pub(crate) struct ProgramTerminal {
writer: ide_core::input::InputWriter,
child: Box<dyn portable_pty::Child + Send + Sync>,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
pid: Option<u32>,
/// Set once the program has exited and been reaped.
exited: Arc<AtomicBool>,
_master: Box<dyn portable_pty::MasterPty + Send>,
}
@@ -882,6 +882,28 @@ impl ProgramTerminal {
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
self.writer.write(text.as_bytes())
}
/// The program's process id while it runs.
pub(crate) fn process_id(&self) -> Option<u32> {
if self.exited.load(Ordering::Acquire) { None } else { self.pid }
}
pub(crate) fn kill(&mut self) {
// After the reap the pid may belong to another process.
if !self.exited.load(Ordering::Acquire) {
let _ = self.killer.kill();
}
}
}
/// Reaps the program as soon as it exits. Until then it stays a zombie that `kill(pid, 0)` still
/// finds: js-debug polls the `processId` it was given and keeps the session (and its terminal)
/// open while that process looks alive, and Stop would wait for it as for a running program.
fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: Arc<AtomicBool>) {
let _ = std::thread::Builder::new().name("openidea-debug-reap".into()).spawn(move || {
let _ = child.wait();
exited.store(true, Ordering::Release);
});
}
/// `runInTerminal`: starts the debuggee on a pseudo-terminal, as an IDE terminal would (CodeLLDB
@@ -968,8 +990,12 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
#[cfg(unix)]
wait_readable,
);
if let Some(mut previous) = s.program.lock().replace(ProgramTerminal { writer, child, _master: pair.master }) {
let _ = previous.child.kill();
let killer = child.clone_killer();
let exited = Arc::new(AtomicBool::new(false));
reap_on_exit(child, exited.clone());
let program = ProgramTerminal { writer, killer, pid, exited, _master: pair.master };
if let Some(mut previous) = s.program.lock().replace(program) {
previous.kill();
}
s.owner.sink.emit(IdeEvent::Debug { session: s.id, event: DebugEvent::ProgramInput });
Ok(json!({ "processId": pid }))
@@ -1338,4 +1364,29 @@ mod tests {
assert_eq!(parse_jdwp_port("Listening for transport dt_socket at address: [::1]:51234"), Some(51234));
assert_eq!(parse_jdwp_port("unrelated output"), None);
}
/// js-debug polls the `runInTerminal` pid with `kill(pid, 0)`; an unreaped zombie answers it as
/// a live process and keeps the session open after the program ends.
#[cfg(unix)]
#[test]
fn a_terminal_program_is_reaped_when_it_exits() {
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let pair =
native_pty_system().openpty(PtySize { rows: 24, cols: 80, pixel_width: 0, pixel_height: 0 }).unwrap();
let mut cmd = CommandBuilder::new("/bin/sh");
cmd.args(["-c", "exit 0"]);
let child = pair.slave.spawn_command(cmd).unwrap();
let pid = child.process_id().unwrap() as libc::pid_t;
let exited = Arc::new(AtomicBool::new(false));
super::reap_on_exit(child, exited.clone());
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !exited.load(Ordering::Acquire) {
assert!(std::time::Instant::now() < deadline, "program was not reaped");
std::thread::sleep(std::time::Duration::from_millis(10));
}
// SAFETY: signal 0 only checks whether the process exists.
assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
}
}
+2
Переглянути файл
@@ -66,6 +66,7 @@ pub struct Host {
pub mcp_requests: mcp::Requests,
/// Commands agents run in the Run tool window (`run_command`).
pub mcp_agent_runs: mcp::AgentRuns,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: trust::TrustStore,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub config_dir: PathBuf,
@@ -152,6 +153,7 @@ impl Host {
mcp_reports: Default::default(),
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
agent_catalogs: Arc::default(),
trust: trust::TrustStore::load(&config_dir, &data_dir),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
+11 -2
Переглянути файл
@@ -7,8 +7,8 @@ use crate::rpc::Dispatcher;
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession,
McpScope, McpServer, McpServerInput, NewAgentTask,
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
ExternalSession, McpScope, McpServer, McpServerInput, NewAgentTask,
};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
@@ -28,6 +28,12 @@ pub fn providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
Ok(providers)
}
/// Refreshes the selected agent's model catalog without sending a prompt.
pub fn refresh_models(host: &Host, window: &str, provider: String, force: bool) -> IdeResult<AgentModelCatalog> {
host.require_trust(window)?;
host.project(window)?.agents.refresh_models(&provider, force)
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
pub fn set_command(host: &Host, window: &str, id: String, command: Option<String>) -> IdeResult<()> {
@@ -557,6 +563,9 @@ pub fn mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>> {
pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
d.add("agent_refresh_models", |c| async move {
refresh_models(&c.host, &c.window, c.arg("provider")?, c.arg("force")?)
});
d.add("agent_set_command", |c| async move { set_command(&c.host, &c.window, c.arg("id")?, c.arg("command")?) });
d.add("agent_set_env", |c| async move { set_env(&c.host, &c.window, c.arg("id")?, c.arg("env")?) });
d.add("agent_registry_list", |c| async move { registry_list(&c.host, &c.window, c.arg("request")?).await });
+45 -6
Переглянути файл
@@ -12,6 +12,7 @@ use ide_db::{
};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
/// One statement of a console run.
#[derive(Clone, Serialize, Deserialize, Type)]
@@ -179,6 +180,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
apply_edits(&c.host, &c.window, &id, &schema, &table, edits).await
});
d.add("db_console_path", |c| async move { console_path(&c.host, &c.arg::<String>("id")?) });
d.add("db_consoles", |c| async move { consoles(&c.host, &c.arg::<String>("id")?, c.arg("create")?) });
}
/// The data sources configured for the project (the tree's roots).
@@ -472,11 +474,52 @@ pub async fn apply_edits(
/// created on first use. Consoles are files of the project, so a remote
/// window resolves it on the host the project runs on.
pub fn console_path(host: &Host, id: &str) -> IdeResult<IpcPath> {
let file = console_dir(host, id)?.join("console.sql");
if !file.exists() {
std::fs::write(&file, "")?;
}
Ok(file.into())
}
/// The query consoles of data source `id`: the default `console.sql`, then
/// `console_1.sql`, `console_2.sql`… in order. `create` adds the next one first
/// (DataGrip's New › Query Console).
pub fn consoles(host: &Host, id: &str, create: bool) -> IdeResult<Vec<IpcPath>> {
let dir = console_dir(host, id)?;
let default = dir.join("console.sql");
let mut numbered: Vec<(u32, PathBuf)> = std::fs::read_dir(&dir)?
.filter_map(|e| {
let path = e.ok()?.path();
let n = path.file_name()?.to_str()?.strip_prefix("console_")?.strip_suffix(".sql")?.parse().ok()?;
Some((n, path))
})
.collect();
numbered.sort();
if create {
// The default console comes first; once it exists, the next number.
if !default.exists() {
std::fs::write(&default, "")?;
} else {
let n = numbered.last().map_or(1, |(n, _)| n + 1);
let file = dir.join(format!("console_{n}.sql"));
std::fs::write(&file, "")?;
numbered.push((n, file));
}
}
let mut out: Vec<IpcPath> = Vec::new();
if default.exists() {
out.push(default.into());
}
out.extend(numbered.into_iter().map(|(_, p)| p.into()));
Ok(out)
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
let (source, database) = ide_db::split_target(id);
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return Err(IdeError::invalid("invalid data source id"));
}
// One console per database: `<id>` for the default one, `<id>.<database>` for the others.
let name = match database {
Some(db) => {
let safe: String =
@@ -487,9 +530,5 @@ pub fn console_path(host: &Host, id: &str) -> IdeResult<IpcPath> {
};
let dir = host.data_dir.join("consoles").join("db").join(&name);
std::fs::create_dir_all(&dir)?;
let file = dir.join("console.sql");
if !file.exists() {
std::fs::write(&file, "")?;
}
Ok(file.into())
Ok(dir)
}
+87 -1
Переглянути файл
@@ -2,7 +2,7 @@ use super::doc::blocking;
use crate::Host;
use crate::Project;
use crate::rpc::Dispatcher;
use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
@@ -22,6 +22,23 @@ pub struct WebGoto {
const MAX_WEB_TARGETS: usize = 200;
/// A Python class definition and the base names written in its source. The UI builds a
/// name → locations index from every class in the project (attached dependency roots
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
/// server's type-hierarchy provider.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ClassInheritance {
/// Start of the class definition's selection range (0-based line, UTF-16 column).
pub path: IpcPath,
pub line: u32,
pub col: u32,
pub name: String,
/// Base names as written in source (bare name, e.g. `AllToAllTokenDispatcher`; a
/// qualified name keeps only its last segment).
pub bases: Vec<String>,
}
/// The project root and its resource roots (served at `/`), for file references.
fn reference_roots(project: &Project) -> (PathBuf, Vec<PathBuf>) {
let resources = project.roots().resource_dirs().iter().map(|d| project.root.join(d)).collect();
@@ -174,6 +191,74 @@ pub async fn nav_index_definitions(
.await
}
/// Every Python class in the project (attached dependency roots included) and its base
/// names. The index covers content roots, so this is the whole-project answer the UI uses
/// for inheritance gutter markers when no type-hierarchy provider exists.
pub async fn nav_inheritance(host: &Host, window: &str) -> IdeResult<Vec<ClassInheritance>> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let python = LanguageId::new("python");
let files = project.index.files_with_extensions(&["py".into(), "pyi".into()], 20_000);
let mut cache = CLASS_BASES.lock();
let mut out = Vec::new();
for path in files {
// The open (possibly unsaved) buffer is keyed by its text, a file on disk by its
// size and modification time, so only changed files are parsed again.
let open = project.documents.text_of(&path);
let stamp = match &open {
Some(text) => Stamp::Text(text_hash(text)),
None => match std::fs::metadata(&path) {
Ok(m) => Stamp::Disk(m.len(), m.modified().ok()),
Err(_) => continue,
},
};
let classes = match cache.get(&path) {
Some((cached, classes)) if *cached == stamp => classes,
_ => {
let text = match open {
Some(text) => text,
None => match project.text_of(&path) {
Ok(text) => text,
Err(_) => continue,
},
};
let classes = syntax.class_bases(&python, &text);
&cache.entry(path.clone()).insert_entry((stamp, classes)).into_mut().1
}
};
out.extend(classes.iter().map(|class| ClassInheritance {
path: IpcPath::from(path.clone()),
line: class.line,
col: class.col,
name: class.name.clone(),
bases: class.bases.clone(),
}));
}
Ok(out)
})
.await
}
#[derive(Clone, PartialEq, Eq)]
enum Stamp {
Text(u64),
Disk(u64, Option<std::time::SystemTime>),
}
fn text_hash(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut h);
h.finish()
}
type ClassBasesCache = std::collections::HashMap<PathBuf, (Stamp, Vec<ide_language::ClassBases>)>;
/// Class bases per Python file, reused while the file is unchanged.
static CLASS_BASES: std::sync::LazyLock<parking_lot::Mutex<ClassBasesCache>> =
std::sync::LazyLock::new(Default::default);
/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
pub async fn fs_resolve_reference(
host: &Host,
@@ -249,6 +334,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("nav_index_definitions", |c| async move {
nav_index_definitions(&c.host, &c.window, c.arg("name")?, c.arg("from")?).await
});
d.add("nav_inheritance", |c| async move { nav_inheritance(&c.host, &c.window).await });
d.add("fs_resolve_reference", |c| async move {
fs_resolve_reference(&c.host, &c.window, c.arg("from")?, c.arg("value")?).await
});
+1
Переглянути файл
@@ -664,6 +664,7 @@ impl Host {
.join(project_key)
}),
models_file: self.data_dir.join("agents").join("models.json"),
catalogs: self.agent_catalogs.clone(),
custom_agents_dir: Some(self.config_dir.join("agents")),
home_dir: dirs::home_dir(),
env_secrets: Some(Arc::new(AgentEnvSecrets {
+1
Переглянути файл
@@ -357,6 +357,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "docker_set_registry_password"
| "docker_run_env"
| "db_console_path"
| "db_consoles"
| "db_export_file"
| "vcs_write_patch"
| "app_metrics"
+98
Переглянути файл
@@ -0,0 +1,98 @@
//! Separate project windows share discovery and its backend-enforced cooldown.
#![cfg(unix)]
use ide_agent::AgentEvent;
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
use std::time::Duration;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn windows_share_model_discovery_and_manual_refresh_cooldown() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let config = tmp.path().join("config");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(config.join("agents")).unwrap();
let script = tmp.path().join("catalog.sh");
std::fs::write(
&script,
r#"#!/bin/sh
printf 'launch\n' >> "${0%/*}/launches"
while IFS= read -r line; do
case "$line" in
*'"id":'*) rest=${line#*\"id\":}; id=${rest%%,*}; id=${id%%\}*} ;;
*) continue ;;
esac
case "$line" in
*'"method":"initialize"'*)
printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id" ;;
*'"method":"session/new"'*)
while [ ! -f "${0%/*}/release" ]; do sleep 0.01; done
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"catalog","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"new-model","options":[{"value":"new-model","name":"New model"}]}]}}\n' "$id" ;;
esac
done
"#,
)
.unwrap();
std::fs::write(
config.join("agents/catalog-test.toml"),
format!(
"name = \"Catalog test\"\ncommand = \"/bin/sh\"\nargs = [{}]\n",
serde_json::to_string(&script).unwrap()
),
)
.unwrap();
let host = Host::new(HostConfig {
config_dir: config,
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("first", &root).unwrap();
host.open_project("second", &root).unwrap();
let (send, mut events) = tokio::sync::mpsc::unbounded_channel();
for window in ["first", "second"] {
let send = send.clone();
host.project(window).unwrap().agents.subscribe(Arc::new(move |event| {
if let AgentEvent::ModelCatalog { catalog } = event {
let _ = send.send((window, catalog));
}
}));
}
for _ in 0..20 {
for window in ["first", "second"] {
let state = ops::agent::refresh_models(&host, window, "catalog-test".into(), true).unwrap();
assert!(state.refreshing);
}
}
std::fs::write(tmp.path().join("release"), "").unwrap();
let completed = tokio::time::timeout(Duration::from_secs(10), async {
let mut windows = std::collections::HashSet::new();
while windows.len() < 2 {
let (window, catalog) = events.recv().await.expect("catalog event stream closed");
if !catalog.refreshing && catalog.refreshed_at_ms.is_some() {
assert!(catalog.error.is_none(), "{:?}", catalog.error);
windows.insert(window);
}
}
})
.await;
assert!(completed.is_ok(), "both windows must receive the completed catalog");
for _ in 0..20 {
for window in ["first", "second"] {
let catalog = ops::agent::refresh_models(&host, window, "catalog-test".into(), true).unwrap();
assert!(!catalog.refreshing);
assert!(catalog.retry_at_ms.is_some());
let models = catalog.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
assert_eq!(models.values[0].value, "new-model");
}
}
assert_eq!(std::fs::read_to_string(tmp.path().join("launches")).unwrap(), "launch\n");
}
+37
Переглянути файл
@@ -0,0 +1,37 @@
use ide_core::NullSink;
use ide_host::ops::db;
use ide_host::{Host, HostConfig};
use std::sync::Arc;
#[tokio::test]
async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
assert!(db::consoles(&host, "pg", false).unwrap().is_empty());
// The first new console is the default one, then console_1, console_2…
assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql"]);
assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql", "console_1.sql"]);
let all = db::consoles(&host, "pg", true).unwrap();
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
// Numbers sort numerically, and the default console path is the first one.
std::fs::write(all[0].0.with_file_name("console_10.sql"), "").unwrap();
assert_eq!(names(db::consoles(&host, "pg", false).unwrap())[3], "console_10.sql");
assert_eq!(db::console_path(&host, "pg").unwrap().0, all[0].0);
// Each database of a source has its own consoles.
assert!(db::consoles(&host, "pg:other", false).unwrap().is_empty());
assert!(db::consoles(&host, "../x", true).is_err());
}
+141
Переглянути файл
@@ -0,0 +1,141 @@
//! The native `nav_inheritance` command: it must return every Python class definition
//! in the project — attached dependency roots included — together with the base names
//! written in its source, so the UI can compute inheritance gutter markers without a
//! language server's type-hierarchy provider.
use ide_host::{Host, HostConfig, ops};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
const WINDOW: &str = "main";
struct Opened {
host: Arc<Host>,
root: PathBuf,
_tmp: tempfile::TempDir,
}
/// Opens a synthetic project whose Python files carry known class / base shapes, then
/// waits for the index to settle (it walks content roots, so dependency roots are covered).
async fn open() -> Opened {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("proj");
let src = root.join("src");
let dep = root.join("vendor");
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dep).unwrap();
// Own root: a plain class, a class with two bases + a keyword arg, a qualified base,
// and a subscripted generic base. A comment / docstring that mentions `class X(Y)`
// must not be reported.
std::fs::write(
src.join("app.py"),
concat!(
"class Base:\n",
" pass\n",
"\n",
"class Mixin:\n",
" pass\n",
"\n",
"class Child(Base, Mixin, metaclass=Meta):\n",
" # class Ghost(Spook): must be ignored\n",
" \"\"\"class Phantom(Apparition): must be ignored\"\"\"\n",
" pass\n",
"\n",
"class Qualified(pkg.mod.Base):\n",
" pass\n",
"\n",
"class Generic(Generic[T]):\n",
" pass\n",
),
)
.unwrap();
// A second own-root file to prove the command scans more than one file.
std::fs::write(src.join("extra.pyi"), "class Stub(Base):\n ...\n").unwrap();
// An attached dependency root (content root) — must be covered by the index.
std::fs::write(dep.join("dep.py"), "class DepBase:\n pass\n").unwrap();
let app = tmp.path().join("app");
let host = Arc::new(Host::new(HostConfig {
config_dir: app.join("config"),
data_dir: app.join("data"),
local_data_dir: app.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
ops::project::open(&host, WINDOW, &root).await.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let s = ops::nav::index_status(&host, WINDOW).unwrap();
if !s.indexing && s.files > 0 {
break;
}
assert!(Instant::now() < deadline, "indexing timed out; status: {s:?}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
Opened { host, root, _tmp: tmp }
}
fn find<'a>(all: &'a [ide_host::ops::nav::ClassInheritance], name: &str) -> &'a ide_host::ops::nav::ClassInheritance {
all.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name:?} in {all:#?}"))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn returns_all_python_classes_and_bases() {
let p = open().await;
let all = ops::nav::nav_inheritance(&p.host, WINDOW).await.unwrap();
// Both own-root Python files are scanned (src/app.py + src/extra.pyi).
let base = find(&all, "Base");
assert!(base.path.0.ends_with("src/app.py"), "Base path: {:?}", base.path);
// The location is the class name identifier (selection-range start), i.e. after `class `.
assert_eq!(base.line, 0);
assert_eq!(base.col, 6);
assert!(base.bases.is_empty(), "a bare class has no bases: {:?}", base.bases);
let child = find(&all, "Child");
assert_eq!(child.line, 6);
assert_eq!(child.col, 6);
// The `metaclass=Meta` keyword argument is not a base.
assert!(child.bases.contains(&"Base".to_string()), "Child bases: {:?}", child.bases);
assert!(child.bases.contains(&"Mixin".to_string()), "Child bases: {:?}", child.bases);
assert!(!child.bases.iter().any(|b| b == "Meta"), "metaclass must be skipped: {:?}", child.bases);
// A qualified base keeps only its last segment.
let qualified = find(&all, "Qualified");
assert_eq!(qualified.bases, vec!["Base".to_string()], "qualified base: {:?}", qualified.bases);
// A subscripted generic base keeps the identifier.
let generic = find(&all, "Generic");
assert_eq!(generic.bases, vec!["Generic".to_string()], "generic base: {:?}", generic.bases);
// Comments / docstrings are not mistaken for class definitions.
assert!(!all.iter().any(|c| c.name == "Ghost" || c.name == "Phantom"), "parsed a comment: {all:#?}");
// The .pyi stub in the second own-root file is included.
let stub = find(&all, "Stub");
assert!(stub.path.0.ends_with("src/extra.pyi"), "Stub path: {:?}", stub.path);
assert_eq!(stub.bases, vec!["Base".to_string()]);
// The attached dependency root is covered by the project index.
let dep = find(&all, "DepBase");
assert!(dep.path.0.starts_with(&p.root), "DepBase path: {:?}", dep.path);
// Every returned entry is a Python file.
assert!(all.iter().all(|c| { matches!(c.path.0.extension().and_then(|e| e.to_str()), Some("py" | "pyi")) }));
// A file changed on disk is parsed again; the others come from the cache.
let extra = p.root.join("src/extra.pyi");
std::fs::write(&extra, "class Stub(Child): ...\nclass Added(Base): ...\n").unwrap();
let again = ops::nav::nav_inheritance(&p.host, WINDOW).await.unwrap();
assert_eq!(find(&again, "Stub").bases, vec!["Child".to_string()]);
assert_eq!(find(&again, "Added").bases, vec!["Base".to_string()]);
assert_eq!(find(&again, "Child").bases, child.bases);
}
+4 -1
Переглянути файл
@@ -82,7 +82,9 @@ async fn serves_projects_files_documents_search_and_runs() {
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
assert!(files.is_array());
for command in ["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start"] {
for command in
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
{
let error = invoke(&peer, command, json!({})).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
}
@@ -365,6 +367,7 @@ async fn local_deployment_runs_on_the_project_host() {
"db_table_page",
"db_apply_edits",
"db_console_path",
"db_consoles",
"ssh_test",
"ssh_set_secret",
"ssh_password_saved",
+2
Переглянути файл
@@ -66,6 +66,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"docker_set_registry_password",
"docker_run_env",
"db_console_path",
"db_consoles",
"db_export_file",
"vcs_write_patch",
"remote_bootstrap_list",
@@ -92,6 +93,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"vcs_git_version",
"docker_compose_op",
"db_execute",
"agent_refresh_models",
"remote_delete",
"remote_mkdir",
"remote_rename",
+5 -5
Переглянути файл
@@ -22,11 +22,11 @@ pub use markers::{arduino_sketch_root, is_arduino_sketch_dir, marked_root};
pub use plugin_point::PluginLanguages;
pub use registry::{FileTypes, LanguageRegistry};
pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken,
FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion,
Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, VueComponentImport,
VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility, set_external_syntax, shift_pos,
shift_range,
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
+171
Переглянути файл
@@ -0,0 +1,171 @@
//! Extraction of Python class base names, used to build an inheritance graph
//! without an LSP `typeHierarchyProvider`.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use tree_sitter::{Node, Tree};
/// A Python class definition and the base names written in its source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClassBases {
/// The class name (bare identifier).
pub name: String,
/// 0-based line of the class name (selection-range start).
pub line: u32,
/// 0-based UTF-16 column of the class name (selection-range start).
pub col: u32,
/// Source-written base names (last segment of a qualified name).
pub bases: Vec<String>,
}
impl Syntax {
/// Class definitions of `text` with their base names, in source order.
/// Only Python is supported; every other language returns an empty vector.
pub fn class_bases(&self, lang: &LanguageId, text: &str) -> Vec<ClassBases> {
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
.unwrap_or_default()
}
}
fn extract(tree: &Tree, text: &str) -> Vec<ClassBases> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
let mut cursor = tree.walk();
visit(&mut cursor, &mut |node| {
if node.kind() != "class_definition" {
return;
}
let Some(name_node) = node.child_by_field_name("name") else { return };
let name = text.get(name_node.byte_range()).unwrap_or_default().to_owned();
if name.is_empty() {
return;
}
// Selection-range start of the class: its name identifier (`class Foo`
// -> `Foo`), matching `outline.rs` and the gutter marker candidates.
let range = idx.range(name_node.start_byte(), name_node.end_byte());
let bases = node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default();
out.push(ClassBases { name, line: range.start.line, col: range.start.col, bases });
});
out
}
/// Depth-first pre-order traversal of all descendants of `cursor`'s node.
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
fn base_names(args: Node, text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cursor = args.walk();
for arg in args.named_children(&mut cursor) {
if let Some(name) = base_name(arg, text) {
out.push(name);
}
}
out
}
/// Bare name of one base expression, or `None` for keyword arguments and
/// expressions that are not a (possibly qualified) name.
fn base_name(arg: Node, text: &str) -> Option<String> {
match arg.kind() {
"identifier" => text.get(arg.byte_range()).map(str::to_owned),
// `pkg.mod.Base` -> `Base`.
"attribute" => {
let attr = arg.child_by_field_name("attribute")?;
(attr.kind() == "identifier").then(|| text.get(attr.byte_range()).unwrap_or_default().to_owned())
}
// `Generic[T]` -> `Generic`.
"subscript" => {
let value = arg.child_by_field_name("value")?;
(value.kind() == "identifier").then(|| text.get(value.byte_range()).unwrap_or_default().to_owned())
}
// `metaclass=Meta`, `**kwargs`, `*bases` and other expressions.
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bases(src: &str) -> Vec<ClassBases> {
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
S.get_or_init(Syntax::new).class_bases(&LanguageId::new("python"), src)
}
fn shape(src: &str) -> Vec<(String, u32, u32, Vec<String>)> {
bases(src).into_iter().map(|c| (c.name, c.line, c.col, c.bases)).collect()
}
#[test]
fn no_bases() {
assert_eq!(shape("class A: pass"), vec![("A".to_owned(), 0, 6, vec![])]);
}
#[test]
fn multiple_bases_skips_metaclass() {
assert_eq!(
shape("class B(A, C, metaclass=Meta): pass"),
vec![("B".to_owned(), 0, 6, vec!["A".to_owned(), "C".to_owned()])]
);
}
#[test]
fn qualified_name_takes_last_segment() {
assert_eq!(shape("class D(pkg.mod.Base): pass"), vec![("D".to_owned(), 0, 6, vec!["Base".to_owned()])]);
}
#[test]
fn subscript_takes_value() {
assert_eq!(shape("class E(Generic[T]): pass"), vec![("E".to_owned(), 0, 6, vec!["Generic".to_owned()])]);
}
#[test]
fn multiline_bases() {
let src = "class F(\n A,\n B,\n):\n pass";
assert_eq!(shape(src), vec![("F".to_owned(), 0, 6, vec!["A".to_owned(), "B".to_owned()])]);
}
#[test]
fn nested_classes() {
let src = "class Outer:\n class Inner(Y):\n pass";
assert_eq!(
shape(src),
vec![("Outer".to_owned(), 0, 6, vec![]), ("Inner".to_owned(), 1, 10, vec!["Y".to_owned()]),]
);
}
#[test]
fn comments_and_strings_are_ignored() {
let src = r#"
# class Fake(Nope): pass
doc = """
class InDocstring(X): pass
"""
s = 'class InString(Y): pass'
class Real(Base): pass
"#;
assert_eq!(shape(src), vec![("Real".to_owned(), 6, 6, vec!["Base".to_owned()])]);
}
#[test]
fn other_languages_are_empty() {
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
let s = S.get_or_init(Syntax::new);
assert!(s.class_bases(&LanguageId::new("rust"), "struct A;").is_empty());
}
}
+2
Переглянути файл
@@ -6,6 +6,7 @@ mod external;
mod folding;
mod grammars;
mod highlight;
mod inheritance;
pub(crate) mod lines;
mod literals;
mod outline;
@@ -22,6 +23,7 @@ pub use external::{ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken,
use grammars::{SPECS, Spec};
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
+12 -1
Переглянути файл
@@ -50,7 +50,12 @@ Agents are unavailable in a project you have not marked as trusted.
- **Local checkout**: the agent edits your files directly.
</Step>
<Step title="Pick the agent and its settings">
Choose the agent, and its model, mode and other options when it offers them. Models and modes appear after the agent's first task.
Choose the agent, and its model, mode and other options when it offers them. Cached models appear immediately; the selected agent's catalog refreshes in the background when it is more than 15 minutes old, without sending a prompt or attaching project MCP servers.
After changing the agent CLI or account, open the model picker and choose **Refresh models**. Refreshes share one lookup and have a 30-second cooldown after completion, including failures. Cached choices remain usable while refreshing or after a failure.
Available models depend on the installed agent and account. If a selected model is removed, choose another before starting. Refreshing does not change running tasks.
</Step>
<Step title="Send">
The task opens as an editor tab and starts.
@@ -67,6 +72,12 @@ The task tab shows the conversation: your messages, the agent's replies, its rea
On your own messages you can **Edit** (the messages after it are replaced; files already changed stay as they are) or **Retract Message**. On replies you can **Copy Markdown**, **Quote Reply**, **Regenerate Response** and **Branch Conversation from Here**, which starts a new task from that point.
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
The shortcut does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. Outside the task conversation, the keys keep their usual editor or terminal behavior. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
Right-click a link and choose **Copy Link Address** to copy its URL; **Copy** copies the selected text.
### Permissions
When an agent wants to run a command or call a tool that needs approval, the task shows the request and is listed as **Needs Input**. Choose one of the options the agent offers, such as **Allow Once**, **Allow for This Session**, **Always Allow**, **Decline**, **Always Decline** or **Decline and Stop**. Many agents also have a mode picker that approves edits or everything automatically; use it with care.
+2
Переглянути файл
@@ -107,6 +107,8 @@ To format on every save, enable **Reformat code** (and optionally **Optimize imp
Tab placement, the tab limit and what happens when it is reached, the preview tab, sorting, and which tab is activated after one closes are set in **Settings › Editor › General › Editor Tabs**.
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
## Split editors
| Action | macOS | Windows / Linux |
+12 -1
Переглянути файл
@@ -50,7 +50,12 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
- **当前工作区**:agent 直接修改你的文件。
</Step>
<Step title="选择 agent 及其设置">
选择 agent,以及它提供的模型、模式等选项。这些选项会在该 agent 跑完第一个任务后出现。
选择 agent,以及它提供的模型、模式等选项。缓存的模型会立即显示;所选 agent 的模型列表超过 15 分钟未更新时,会在后台刷新,不发送提示词,也不接入项目 MCP 服务器。
更改 agent CLI 或账号后,打开模型选择器并单击 **刷新模型**。并发刷新会共用一次查询;每次查询完成后(包括失败)都有 30 秒冷却时间。刷新中或刷新失败后,缓存选项仍可使用。
可用模型取决于已安装的 agent 和账号。如果已选模型被移除,需要先选择其他模型才能开始任务。刷新不会更改正在运行的任务。
</Step>
<Step title="发送">
任务会在编辑器标签页中打开并开始运行。
@@ -67,6 +72,12 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
在你自己的消息上可以 **编辑**(其后的消息会被替换,已经改动的文件保持不变)或 **撤回消息**。在回复上可以 **复制 Markdown**、**引用回复**、**重新生成回复**,以及 **从此处创建分支对话**,从这一点开始一个新任务。
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。在任务对话之外,按键保留原有的编辑器或终端行为。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
右键点击链接并选择 **复制链接地址** 可复制它的 URL;**复制** 复制选中的文字。
### 权限
agent 要运行命令或调用需要授权的工具时,任务中会显示请求,并归入 **等待输入**。从 agent 提供的选项中选择,例如 **允许一次**、**在此会话中允许**、**始终允许**、**拒绝**、**始终拒绝** 或 **拒绝并停止**。很多 agent 还有模式选择器,可以自动批准编辑甚至所有操作,请谨慎使用。
+2
Переглянути файл
@@ -107,6 +107,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
标签页的位置、数量上限以及达到上限后的处理方式、预览标签页、排序方式,以及关闭标签页后激活哪一个,都在 **设置 › 编辑器 › 常规 › 编辑器标签页** 中设置。
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
## 拆分编辑器
| 操作 | macOS | Windows / Linux |
+379
Переглянути файл
@@ -0,0 +1,379 @@
import type { Locator, Page } from "@playwright/test";
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, openFromTree, test } from "./fixtures";
type Placement = "editor" | "toolWindow";
const firstTask: AgentTask = {
id: "focus-first",
title: "First focus task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
const draft = "draft keep this unsent";
const reboundShortcut = "Control+Meta+Shift+J";
const subagent: AgentEntry = {
type: "subagent",
id: "focus-child",
title: "Inspect focus behavior",
description: null,
status: "done",
error: null,
prompt: null,
reply: null,
tools: 0,
activity: null,
startedMs: null,
endedMs: null,
cancellable: false,
};
async function seedTasks(page: Page, placement: Placement, status: AgentTask["status"] = "ready") {
const entries: AgentEntry[] = Array.from({ length: 24 }, (_, turn): AgentEntry[] => [
{ type: "user", text: `Request ${turn}`, attachments: [] },
{ type: "agent", text: `Reply ${turn}` },
]).flat();
await page.evaluate(
async ({ firstTask, secondTask, entries, subagent, placement, status }) => {
// These modules must load in the browser's Vite realm, not Playwright's Node process.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
commands.agentChanges = async () => ({ status: "ok", data: [] });
document.documentElement.dataset.agentPromptCount = "0";
commands.agentPrompt = async () => {
const root = document.documentElement;
root.dataset.agentPromptCount = String(Number(root.dataset.agentPromptCount) + 1);
return { status: "ok", data: null };
};
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([
[firstTask.id, { ...firstTask, status }],
[secondTask.id, secondTask],
]),
entries: new Map([
[firstTask.id, [...entries, subagent]],
[secondTask.id, entries],
[`${firstTask.id}/${subagent.id}`, [{ type: "agent", text: "Subagent findings" }]],
]),
composers: new Map(),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: placement,
});
store.openTask(firstTask.id);
},
{ firstTask, secondTask, entries, subagent, placement, status },
);
await expect(messageBox(page)).toBeVisible();
await page.evaluate(() => document.fonts.ready);
}
function messageBox(page: Page) {
return page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
}
function conversation(page: Page) {
return page.locator("[class*='_stream_']:visible");
}
// Read the browser selection, not the store's focus request or a registry entry.
async function selection(box: Locator) {
return box.evaluate((element) => {
const selected = window.getSelection();
if (!selected?.anchorNode || !selected.focusNode) return null;
if (!element.contains(selected.anchorNode) || !element.contains(selected.focusNode)) return null;
const offset = (node: Node, at: number) => {
const range = document.createRange();
range.selectNodeContents(element);
range.setEnd(node, at);
return range.toString().length;
};
return {
anchor: offset(selected.anchorNode, selected.anchorOffset),
head: offset(selected.focusNode, selected.focusOffset),
text: selected.toString(),
};
});
}
async function selectDraft(box: Locator, range: boolean) {
await box.fill(draft);
await box.press("Home");
for (let index = 0; index < 6; index++) await box.press("ArrowRight");
if (range) {
for (let index = 0; index < 4; index++) await box.press("Shift+ArrowRight");
}
const expected = { anchor: 6, head: range ? 10 : 6, text: range ? "keep" : "" };
await expect.poll(() => selection(box)).toEqual(expected);
return expected;
}
for (const placement of ["editor", "toolWindow"] as const) {
for (const status of ["ready", "running"] as const) {
test(`${placement}: default shortcut restores ${status} task input without changing draft, selection or history`, async ({
workbench: page,
}) => {
await seedTasks(page, placement, status);
const box = messageBox(page);
const history = conversation(page);
for (const range of [false, true]) {
const expected = await selectDraft(box, range);
await history.click({ position: { x: 12, y: 20 } });
await expect(history).toBeFocused();
await history.press("Home");
await expect.poll(() => history.evaluate((element) => element.scrollTop)).toBe(0);
for (let repeat = 0; repeat < 3; repeat++) {
await page.keyboard.press("Meta+L");
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect.poll(() => selection(box)).toEqual(expected);
await expect.poll(() => history.evaluate((element) => element.scrollTop)).toBe(0);
}
}
await expect(page.getByRole("dialog", { name: "Go to Line:Column", exact: true })).toHaveCount(0);
await expect(page.locator("html")).toHaveAttribute("data-agent-prompt-count", "0");
});
}
test(`${placement}: focuses the shown task rather than another kept-alive composer`, async ({ workbench: page }) => {
await seedTasks(page, placement);
await messageBox(page).fill("first task's unsent draft");
await page.evaluate(async (id) => {
// Load the workbench store inside the browser, not the test runner.
const storePath = "/src/features/agents/store.ts";
(await import(storePath)).openTask(id);
}, secondTask.id);
await messageBox(page).fill("second task's unsent draft");
if (placement === "editor") {
await expect(page.getByRole("textbox", { name: "Message", exact: true, includeHidden: true })).toHaveCount(2);
await page.getByRole("tab", { name: firstTask.title, exact: true }).click();
} else {
await page.getByRole("button", { name: "Agent sessions", exact: true }).click();
await page.getByRole("tree", { name: "Agent tasks" }).getByText(firstTask.title, { exact: true }).dblclick();
}
await expect(messageBox(page)).toHaveText("first task's unsent draft");
await conversation(page).click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Meta+L");
await expect(messageBox(page)).toBeFocused();
await expect(messageBox(page)).toHaveText("first task's unsent draft");
if (placement === "editor") {
await page.getByRole("tab", { name: secondTask.title, exact: true }).click();
} else {
await page.getByRole("button", { name: "Agent sessions", exact: true }).click();
await page.getByRole("tree", { name: "Agent tasks" }).getByText(secondTask.title, { exact: true }).dblclick();
}
await conversation(page).click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Meta+L");
await expect(messageBox(page)).toBeFocused();
await expect(messageBox(page)).toHaveText("second task's unsent draft");
await expect(page.locator("html")).toHaveAttribute("data-agent-prompt-count", "0");
});
}
test("Settings → Keymap rebinds Focus Agent Input and removes its default shortcut", async ({ workbench: page }) => {
await seedTasks(page, "editor");
const box = messageBox(page);
const expected = await selectDraft(box, true);
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill("Focus Agent Input");
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Focus Agent Input/ });
await row.dblclick();
await page.getByRole("menuitem", { name: "Add Keyboard Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: "Keyboard Shortcut: Focus Agent Input", exact: true });
await recorder.getByRole("textbox", { name: "First stroke" }).press(reboundShortcut);
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(recorder).toBeHidden();
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Remove ⌘L", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
const history = conversation(page);
await history.click({ position: { x: 12, y: 20 } });
await expect(history).toBeFocused();
await page.keyboard.press("Meta+L");
await expect(history).toBeFocused();
await expect(box).not.toBeFocused();
await page.keyboard.press(reboundShortcut);
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect.poll(() => selection(box)).toEqual(expected);
await expect(page.locator("html")).toHaveAttribute("data-agent-prompt-count", "0");
});
test("modals and conversation popups keep keyboard focus", async ({ workbench: page }) => {
await seedTasks(page, "editor");
const box = messageBox(page);
await box.fill(draft);
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings", exact: true });
await search.fill("keymap");
await page.keyboard.press("Meta+L");
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await expect(box).not.toBeFocused();
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(settings).toBeHidden();
const reply = conversation(page).getByText("Reply 0", { exact: true });
await reply.dblclick();
await reply.click({ button: "right" });
const menu = page.getByRole("menu");
await expect(menu).toBeVisible();
const firstItem = menu.getByRole("menuitem").first();
await expect(firstItem).toBeFocused();
await page.keyboard.press("Meta+L");
await expect(menu).toBeVisible();
await expect(firstItem).toBeFocused();
await expect(box).not.toBeFocused();
await page.keyboard.press("Escape");
await expect(box).toHaveText(draft);
});
test("archived tasks do not focus their disabled composer", async ({ workbench: page }) => {
await seedTasks(page, "editor", "archived");
await expect(
page.getByText("This task is archived. Unarchive it to continue the conversation.", { exact: true }),
).toBeVisible();
const history = conversation(page);
await history.click({ position: { x: 12, y: 20 } });
await expect(history).toBeFocused();
await page.keyboard.press("Meta+L");
await expect(history).toBeFocused();
await expect(messageBox(page)).not.toBeFocused();
});
test("subagent conversations do not focus the hidden parent composer", async ({ workbench: page }) => {
await seedTasks(page, "editor");
await messageBox(page).fill(draft);
await page.getByTitle("Open the subagent's conversation", { exact: true }).click();
await expect(page.getByRole("navigation", { name: "Subagent", exact: true })).toBeVisible();
const history = conversation(page);
await history.click({ position: { x: 12, y: 20 } });
await expect(history).toBeFocused();
await page.keyboard.press("Meta+L");
await expect(history).toBeFocused();
await expect(messageBox(page)).toHaveCount(0);
await page
.getByRole("navigation", { name: "Subagent", exact: true })
.getByRole("button", { name: firstTask.title, exact: true })
.click();
await expect(messageBox(page)).toHaveText(draft);
await conversation(page).click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Meta+L");
await expect(messageBox(page)).toBeFocused();
});
test("editor Go to Line stays available while a docked agent conversation is visible", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
await seedTasks(page, "toolWindow");
await messageBox(page).fill(draft);
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+L");
const dialog = page.getByRole("dialog", { name: "Go to Line:Column", exact: true });
const line = dialog.getByRole("textbox", { name: "Line and column", exact: true });
await expect(line).toBeFocused();
await expect(messageBox(page)).not.toBeFocused();
await line.fill("2:1");
await dialog.getByRole("button", { name: "OK", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(content).toBeFocused();
await expect(messageBox(page)).toHaveText(draft);
});
for (const preset of ["intellij-windows", "vscode-windows", "eclipse-windows"]) {
test(`${preset} uses Ctrl+L to focus the task message`, async ({ workbench: page }) => {
await seedTasks(page, "editor");
const box = messageBox(page);
const expected = await selectDraft(box, true);
await page.evaluate(async (preset) => {
// Load the keymap in the browser where keyboard dispatch runs.
const keymapPath = "/src/platform/keymap.ts";
(await import(keymapPath)).applyKeymapSettings(preset, {});
}, preset);
const history = conversation(page);
await history.click({ position: { x: 12, y: 20 } });
await expect(history).toBeFocused();
await page.keyboard.press("Control+L");
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect.poll(() => selection(box)).toEqual(expected);
await expect(page.locator("html")).toHaveAttribute("data-agent-prompt-count", "0");
});
}
test("Find Action focuses the current task input after closing its popup", async ({ workbench: page }) => {
await seedTasks(page, "editor");
const box = messageBox(page);
const expected = await selectDraft(box, true);
await conversation(page).click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
const query = search.getByRole("combobox");
await query.fill("Focus Agent Input");
await expect(search.getByRole("option", { name: /Focus Agent Input/ })).toBeVisible();
await query.press("Enter");
await expect(search).toBeHidden();
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect.poll(() => selection(box)).toEqual(expected);
});
test("docked Changes view returns to the task input without losing its selection", async ({ workbench: page }) => {
await seedTasks(page, "toolWindow");
const box = messageBox(page);
const expected = await selectDraft(box, true);
await page.evaluate(async (id) => {
// Seed the store in the browser realm; a static import would run in Node.
const storePath = "/src/features/agents/store.ts";
(await import(storePath)).useAgents.setState({
changes: new Map([
[
id,
[
{
path: "/dev/acme-api/file.ts",
relPath: "file.ts",
kind: "modified",
added: 1,
removed: 0,
oldPath: null,
},
],
],
]),
});
}, firstTask.id);
await page.getByRole("button", { name: /1 changed file/ }).click();
const changes = page.getByRole("complementary", { name: "Changes", exact: true });
await expect(changes).toBeVisible();
await expect(box).toHaveCount(0);
await changes.getByRole("button", { name: "Back to conversation", exact: true }).focus();
await page.keyboard.press("Meta+L");
await expect(changes).toBeHidden();
await expect(box).toBeFocused();
await expect(box).toHaveText(draft);
await expect.poll(() => selection(box)).toEqual(expected);
});
+31
Переглянути файл
@@ -198,6 +198,37 @@ test("copies reply Markdown with the keyboard and keeps code copying separate",
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("const a = 1;");
});
test("copies a reply link's address from its context menu and keeps Copy for the selected text", async ({
page,
context,
}) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
const url = "https://example.com/pull/42?tab=files#diff";
const reply = await openReply(page, `[**Review changes**](${url})\n\nOrdinary reply text`);
const link = reply.getByRole("link", { name: "Review changes" });
await link.locator("strong").click({ button: "right" });
await page.getByRole("menuitem", { name: "Copy Link Address" }).click();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(url);
await link.evaluate((el) => {
const range = document.createRange();
range.selectNodeContents(el);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
});
await link.click({ button: "right" });
await page
.getByRole("menuitem", { name: /^Copy\b/ })
.first()
.click();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("Review changes");
const paragraph = reply.getByText("Ordinary reply text", { exact: true });
await paragraph.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Copy Link Address" })).toHaveCount(0);
await page.keyboard.press("Escape");
});
test("keeps latest reply actions visible and quotes into the draft without shifting content", async ({ page }) => {
const reply = await openReply(page, REPLY);
const copy = page.getByRole("button", { name: "Copy Markdown", exact: true });
+35
Переглянути файл
@@ -285,3 +285,38 @@ test("vertical tabs leave a narrow editor group most of its width", async ({ wor
expect(contentBox!.width).toBeGreaterThanOrEqual(paneBox!.width * 0.6 - 1);
}
});
test("dragging the vertical tab column's edge resizes it and the width is kept", async ({ workbench: page }) => {
await openFromTree(page, "settings.gradle.kts");
const placeLeft = () =>
page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({
settings: { ...base, editor: { ...base.editor, tabs: { ...base.editor.tabs, placement: "left" } } },
});
});
await placeLeft();
const strip = page.getByRole("tablist", { name: "Editor tabs" });
const handle = page.getByRole("separator", { name: "Resize editor tabs" });
const before = (await strip.boundingBox())!.width;
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x - 60, box.y + box.height / 2, { steps: 5 });
await page.mouse.up();
await expect.poll(async () => (await strip.boundingBox())!.width).toBeLessThan(before - 40);
const narrowed = (await strip.boundingBox())!.width;
// The next session starts with the dragged width.
await page.reload();
await openFromTree(page, "settings.gradle.kts");
await placeLeft();
await expect.poll(async () => Math.round((await strip.boundingBox())!.width)).toBe(Math.round(narrowed));
});
+14
Переглянути файл
@@ -172,6 +172,20 @@ test("accepting a deleted version removes the file before staging", async ({ pag
]);
});
test("a long side shows only the lines it changed against the base", async ({ page }) => {
// Edits spread over a long file make the default diff give up and mark everything between them.
const base = Array.from({ length: 2000 }, (_, i) => `"node_modules/pkg-${i}": "1.0.${i}",`);
const bump = (at: number) => lines(...base.map((l, i) => (i % 100 === at ? l.replace('"1.0.', '"2.0.') : l)));
await mountMerge(page, [lines(...base), bump(3), bump(50)]);
for (const [name, line] of [
["Your version", 3],
["Their version", 50],
] as const) {
const deleted = page.getByRole("region", { name }).locator(".cm-deletedChunk").first().locator(".cm-deletedLine");
await expect(deleted).toHaveText([base[line]!]);
}
});
test("the result starts as the base and every change waits for a decision", async ({ page }) => {
await mountMerge(page);
await expect(status(page)).toHaveText("3 changes left, 2 conflicts");
+102
Переглянути файл
@@ -0,0 +1,102 @@
import { expect, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const markers: Record<string, string> = {
"/work/api": "go.mod",
"/work/web": "pom.xml",
"/work/library": "pom.xml",
};
window.__ipc.handlers.fs_read_dir = ({ path }) => {
const name = markers[String(path)];
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
};
window.__ipc.handlers.run_configs = () => [
{
id: "workspace:web:tomcat",
name: "Web / Tomcat",
kind: "tomcat",
command: "catalina",
args: ["run"],
cwd: "/work/web",
module: "/work/web",
env: {},
detected: true,
isTest: false,
debugAdapter: null,
},
];
window.__ipc.handlers.project_roots = () => ({ folders: [] });
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const current = useProject.getState().project;
useProject.setState({
project: {
...current,
name: "Workspace",
root: "/workspace",
workspace: { version: 1, name: "Workspace", projects: Object.keys(markers) },
},
});
});
const newMenu = async (path: string) => {
await page.locator(`[data-project-path="${path}"]`).click({ button: "right" });
await page.getByRole("menuitem", { name: "New", exact: true }).hover();
await expect(page.getByRole("menuitem", { name: "From Template…", exact: true })).toBeVisible();
};
await newMenu("/work/api");
await expect(page.getByRole("menuitem", { name: "Go File", exact: true })).toBeVisible();
await page.screenshot({ path: test.info().outputPath("go-new-menu.png"), animations: "disabled" });
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await newMenu("/work/web");
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Go File", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "TypeScript File", exact: true })).toBeVisible();
await page.screenshot({ path: test.info().outputPath("tomcat-new-menu.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await page.locator('[data-project-path="/work/library"]').click();
await page.keyboard.press("Meta+n");
const popup = page.getByRole("dialog", { name: "New", exact: true });
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
});
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.fs_read_dir = ({ path }) =>
path === "/work/script" ? [{ name: "pyproject.toml", path: "/work/script/pyproject.toml", kind: "file" }] : [];
window.__ipc.handlers.run_configs = () => [];
window.__ipc.handlers.project_roots = () => ({ folders: [] });
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
useProject.setState({
project: { ...useProject.getState().project, name: "script", root: "/work/script" },
});
});
await page.locator('[data-project-path="/work/script"]').click();
await page.keyboard.press("Meta+n");
const popup = page.getByRole("dialog", { name: "New", exact: true });
await expect(popup.getByText("Python File", { exact: true })).toBeVisible();
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
await popup.getByRole("textbox", { name: "Search for file type" }).fill("from template");
await popup.getByText("From Template…", { exact: true }).click();
await expect(
page.getByRole("dialog", { name: "New File from Template" }).getByText("Go File", { exact: true }),
).toBeVisible();
});
+14 -2
Переглянути файл
@@ -4,8 +4,8 @@ use crate::state::AppState;
use ide_agent::registry::AgentRegistry;
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession,
McpServer, McpServerInput, NewAgentTask,
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
ExternalSession, McpServer, McpServerInput, NewAgentTask,
};
use ide_core::{IdeResult, IpcPath, RequestId};
use ide_host::ops::agent;
@@ -37,6 +37,18 @@ pub fn agent_providers(window: Window, state: State<'_, AppState>) -> IdeResult<
agent::providers(&state.host, window.label())
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
#[tauri::command]
#[specta::specta]
pub fn agent_refresh_models(
window: Window,
state: State<'_, AppState>,
provider: String,
force: bool,
) -> IdeResult<AgentModelCatalog> {
agent::refresh_models(&state.host, window.label(), provider, force)
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
#[tauri::command]
+7
Переглянути файл
@@ -362,3 +362,10 @@ pub async fn db_apply_edits(
pub fn db_console_path(state: State<'_, AppState>, id: String) -> IdeResult<IpcPath> {
ide_host::ops::db::console_path(&state.host, &id)
}
/// The query consoles of data source `id`; `create` adds the next one first.
#[tauri::command]
#[specta::specta]
pub fn db_consoles(state: State<'_, AppState>, id: String, create: bool) -> IdeResult<Vec<IpcPath>> {
ide_host::ops::db::consoles(&state.host, &id, create)
}
+3
Переглянути файл
@@ -123,6 +123,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::log_frontend,
agent::agent_subscribe,
agent::agent_providers,
agent::agent_refresh_models,
agent::agent_set_command,
agent::agent_set_env,
agent::agent_custom_save,
@@ -248,6 +249,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
nav::web_goto,
nav::nav_resolve_module,
nav::nav_index_definitions,
nav::nav_inheritance,
nav::fs_resolve_reference,
nav::path_completions,
nav::web_unresolved_references,
@@ -746,5 +748,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
db::db_table_page,
db::db_apply_edits,
db::db_console_path,
db::db_consoles,
])
}
+8
Переглянути файл
@@ -115,6 +115,14 @@ pub async fn nav_index_definitions(
ide_host::ops::nav::nav_index_definitions(&state.host, window.label(), name, from).await
}
/// Every Python class in the project (attached dependency roots included) and its base names,
/// for native inheritance gutter markers.
#[tauri::command]
#[specta::specta]
pub async fn nav_inheritance(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ClassInheritance>> {
ide_host::ops::nav::nav_inheritance(&state.host, window.label()).await
}
/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
#[tauri::command]
#[specta::specta]
+43
Переглянути файл
@@ -136,6 +136,8 @@ export const commands = {
/** Streams the project's agent events to this window; returns every task. */
agentSubscribe: (onEvent: Channel<AgentEvent>) => typedError<AgentTask[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
/** Refreshes the model catalog; force bypasses freshness, not the cooldown. */
agentRefreshModels: (provider: string, force: boolean) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force })),
/**
* Overrides built-in agent `id`'s command with `command` (its agent file keeps the
* built-in's driver and arguments), or returns it to auto-detection with `None`.
@@ -475,6 +477,11 @@ export const commands = {
* plus its configured dependencies).
*/
navIndexDefinitions: (name: string, from: IpcPath) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("nav_index_definitions", { name, from })),
/**
* Every Python class in the project (attached dependency roots included) and its base names,
* for native inheritance gutter markers.
*/
navInheritance: () => typedError<ClassInheritance[], IdeError>(__TAURI_INVOKE("nav_inheritance")),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/** Files and folders that continue `prefix`, a path being typed in `from`. */
@@ -1726,6 +1733,8 @@ export const commands = {
dbTablePage: (request: RequestId, id: string, schema: string, table: string, filter: string | null, sort: DbSortKey[], offset: number, limit: number) => typedError<DbTablePage, IdeError>(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })),
dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })),
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
/** The query consoles of data source `id`; `create` adds the next one first. */
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
};
/* Types */
@@ -1963,6 +1972,8 @@ export type AgentEvent =
{ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string } |
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
{ type: "limits"; provider: string; limits: AgentLimit[] } |
/** A model lookup started or completed, including unsuccessful lookups. */
{ type: "modelCatalog"; catalog: AgentModelCatalog } |
/** The installed or configured agent providers changed. */
{ type: "providers" };
@@ -2018,6 +2029,17 @@ export type AgentMcpServer_Serialize = {
agents?: string[],
};
/** Authoritative choices for new tasks, independent of any running session's settings. */
export type AgentModelCatalog = {
provider: string,
config: AgentConfigOption[],
thoughtLevels: { [key in string]: AgentConfigOption[] },
refreshing: boolean,
refreshedAtMs: number | null,
retryAtMs: number | null,
error: string | null,
};
export type AgentPermissionOption = {
id: string,
name: string,
@@ -2889,6 +2911,25 @@ export type ChoiceOption = {
label: string,
};
/**
* A Python class definition and the base names written in its source. The UI builds a
* name → locations index from every class in the project (attached dependency roots
* included) to compute ↑ overrides / ↓ overridden gutter markers without a language
* server's type-hierarchy provider.
*/
export type ClassInheritance = {
/** Start of the class definition's selection range (0-based line, UTF-16 column). */
path: IpcPath,
line: number,
col: number,
name: string,
/**
* Base names as written in source (bare name, e.g. `AllToAllTokenDispatcher`; a
* qualified name keeps only its last segment).
*/
bases: string[],
};
export type ClassifiedReference = {
/** Optional for older Java extensions; missing means unclassified. */
access?: ReferenceAccess | null,
@@ -4018,6 +4059,8 @@ export type DebuggerSettings = {
showOnBreakpoint?: boolean,
focusAppOnBreakpoint?: boolean,
hideOnTermination?: boolean,
/** A breakpoint or exception hit brings the Debug tool window's Threads & Variables tab to the front. */
variablesOnBreakpoint?: boolean,
breakpointsAnyFile?: boolean,
/** While suspended, hovering the start of a line shows a Run to Cursor button. */
runToCursorInlay?: boolean,
+23 -4
Переглянути файл
@@ -270,13 +270,29 @@
}
.tabsVertical > .tabs,
.tabsVertical > .tabRows {
/* Fits the labels up to the draggable limit (SideTabsResizer); the editor keeps at least 60%. */
width: max-content;
/* A narrow editor group keeps most of its width for the editor; labels truncate. */
min-width: min(140px, 40%);
max-width: min(260px, 40%);
max-width: min(var(--side-tabs-limit, 260px), 40%);
border-bottom: none;
border-right: 1px solid var(--border-editor-tabs, var(--border));
}
/* A zero-width handle on the column's inner border, with a wider hit area. */
.sideTabsResizer {
position: relative;
z-index: 1;
flex: none;
width: 0;
outline: none;
}
.sideTabsResizer::after {
content: "";
position: absolute;
inset: 0 -3px;
cursor: ew-resize;
}
.sideTabsResizer:focus-visible::after {
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
}
.tabsVertical .tabRows > .tabs {
min-height: 0;
border-bottom: none;
@@ -285,9 +301,12 @@
flex: 1 1 auto;
border-top: 1px solid var(--border-editor-tabs, var(--border));
}
.tabsRight > .sideTabsResizer {
order: 1;
}
.tabsRight > .tabs,
.tabsRight > .tabRows {
order: 1;
order: 2;
border-right: none;
border-left: 1px solid var(--border-editor-tabs, var(--border));
}
+7 -1
Переглянути файл
@@ -64,6 +64,7 @@ import { TextEditorHost } from "./TextEditorHost";
import { FindBar } from "./FindBar";
import { EditorBanners, VirtualBanner } from "./Banner";
import { CodeBreadcrumbs } from "./StatusItems";
import { SideTabsResizer, useSideTabsStyle } from "./SideTabsResizer";
import styles from "./EditorArea.module.css";
import { tx } from "@/platform/i18n";
@@ -219,7 +220,9 @@ function PaneView({ paneId }: { paneId: string }) {
: undefined,
italic: t.preview,
modified: dirty[i],
closable: showCloseButton,
// IDEA: hiding the close button is visual only. Keep close gestures
// (middle click, Shift+click, Delete) alive when its position is None.
showCloseButton,
color: colors[i] || undefined,
tint: tints[i] || undefined,
tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined),
@@ -252,6 +255,7 @@ function PaneView({ paneId }: { paneId: string }) {
const pinnedCount = tabs.filter((t) => t.pinned).length;
// Settings › Editor Tabs › Tab placement Left / Right: a vertical, scrolling column.
const vertical = tabPrefs.placement === "left" || tabPrefs.placement === "right";
const sideTabsStyle = useSideTabsStyle();
const pinnedRow = tabPrefs.pinnedSeparateRow && pinnedCount > 0 && pinnedCount < tabs.length;
const dnd = useMemo(() => {
// A tab released outside the window detaches into a forced new window.
@@ -366,6 +370,7 @@ function PaneView({ paneId }: { paneId: string }) {
vertical && styles.tabsVertical,
tabPrefs.placement === "right" && styles.tabsRight,
)}
style={vertical ? sideTabsStyle : undefined}
data-pane-id={paneId}
data-focus-scope=""
aria-label={tx("Editor")}
@@ -381,6 +386,7 @@ function PaneView({ paneId }: { paneId: string }) {
) : (
strip(items, dnd.all, actions)
)}
{vertical && !hidden && <SideTabsResizer side={tabPrefs.placement === "left" ? "left" : "right"} />}
<div
className={styles.content}
role="tabpanel"
+106
Переглянути файл
@@ -0,0 +1,106 @@
/**
* Width limit of editor tabs placed left / right, as in IDEA: the column fits its
* labels up to this limit, and dragging its inner edge sets the limit for every
* editor group. Remembered across sessions.
*/
import type { CSSProperties, KeyboardEvent, PointerEvent } from "react";
import { create } from "zustand";
import { lockDragCursor } from "@/ui";
import { tx } from "@/platform/i18n";
import styles from "./EditorArea.module.css";
const KEY = "openidea.editor.sideTabsWidth";
const MIN_WIDTH = 80;
const MAX_WIDTH = 800;
const KEY_STEP = 16;
/** CSS custom property read by `.tabsVertical` in EditorArea.module.css. */
const LIMIT_VAR = "--side-tabs-limit";
function load(): number | null {
try {
const v: unknown = JSON.parse(localStorage.getItem(KEY) ?? "null");
return typeof v === "number" && Number.isFinite(v) ? clamp(v) : null;
} catch {
return null;
}
}
function clamp(px: number) {
return Math.round(Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, px)));
}
/** `null`: the default limit from the stylesheet. */
const useSideTabsWidth = create<{ width: number | null }>(() => ({ width: load() }));
function setSideTabsWidth(px: number) {
const width = clamp(px);
useSideTabsWidth.setState({ width });
try {
localStorage.setItem(KEY, JSON.stringify(width));
} catch {
// Storage unavailable: the width lasts for this session.
}
}
/** Style for the editor pane that holds a vertical tab column. */
export function useSideTabsStyle(): CSSProperties | undefined {
const width = useSideTabsWidth((s) => s.width);
return width == null ? undefined : ({ [LIMIT_VAR]: `${width}px` } as CSSProperties);
}
/** The drag handle on the editor side of the tab column; render it right after the column. */
export function SideTabsResizer({ side }: { side: "left" | "right" }) {
const sign = side === "left" ? 1 : -1;
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
const handle = e.currentTarget;
const pane = handle.parentElement;
const start = handle.previousElementSibling?.getBoundingClientRect().width;
if (e.button !== 0 || !pane || start == null) return;
// No focus ring or text selection from a mouse drag.
e.preventDefault();
handle.setPointerCapture(e.pointerId);
const origin = e.clientX;
const previous = pane.style.getPropertyValue(LIMIT_VAR);
const releaseCursor = lockDragCursor("ew-resize");
let next: number | null = null;
// Only this pane follows the pointer; every group takes the new width on release.
const move = (ev: globalThis.PointerEvent) => {
if (!(ev.buttons & 1)) return end();
next = clamp(start + sign * (ev.clientX - origin));
pane.style.setProperty(LIMIT_VAR, `${next}px`);
};
const end = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
releaseCursor();
if (next != null) setSideTabsWidth(next);
else if (previous) pane.style.setProperty(LIMIT_VAR, previous);
else pane.style.removeProperty(LIMIT_VAR);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const dir = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
const width = e.currentTarget.previousElementSibling?.getBoundingClientRect().width;
if (!dir || width == null) return;
e.preventDefault();
setSideTabsWidth(width + sign * dir * KEY_STEP);
};
return (
<div
role="separator"
aria-orientation="vertical"
aria-label={tx("Resize editor tabs")}
tabIndex={0}
className={styles.sideTabsResizer}
onPointerDown={onPointerDown}
onKeyDown={onKeyDown}
/>
);
}
+11
Переглянути файл
@@ -80,4 +80,15 @@ describe("pinned tabs in a separate row", () => {
fireEvent.mouseDown(screen.getByRole("tab", { name: /f2/ }), { button: 1 });
expect(closeTab).toHaveBeenCalledWith("p1", "t2");
});
// Regression: Settings › Editor Tabs › "Close button position: None" hides the ×
// but must not disable middle-click. EditorArea used to pass closable:
// showCloseButton, so hiding the button made the tab unclosable.
it("middle click still closes when the close button is hidden (position None)", () => {
seed([false, false, false], { placement: "top", showCloseButton: false });
render(<EditorAreaView />);
expect(screen.queryByRole("button", { name: "Close Tab" })).toBeNull();
fireEvent.mouseDown(screen.getByRole("tab", { name: /f2/ }), { button: 1 });
expect(closeTab).toHaveBeenCalledWith("p1", "t2");
});
});
+331 -7
Переглянути файл
@@ -27,12 +27,14 @@ import {
isCancelled,
nextRequestId,
onIdeEvent,
type ClassInheritance,
type HierarchyItem,
type Location,
type OutlineItem,
type Pos,
type RequestId,
} from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { editorPrefs, type EditorExtras } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { gutterIconMarkup } from "@/ui";
@@ -48,7 +50,7 @@ import {
type MarkerCandidate,
type MarkerGroup,
} from "./lineMarkers";
import { overridersInType, superMethodTargets, type SuperDeps, type SuperMethod } from "./structureNav";
import { baseName, overridersInType, superMethodTargets, type SuperDeps, type SuperMethod } from "./structureNav";
import styles from "./LineMarkers.module.css";
/** Lines above / below the viewport that are asked with it. */
@@ -85,16 +87,49 @@ export function affectsMarkers(paths: readonly string[]): boolean {
return paths.some((p) => !OUTPUT_PATH.test(p));
}
/**
* The Python inheritance graph of the open project, shared by every document and kept
* across edits: it is a whole-project index answer, not a per-document one, so scanning
* it again for each edit would walk every Python file again. Dropped when other files
* change or a server settles (the index may have moved on).
*/
let inheritanceGraphCache: { root: string; promise: Promise<ClassInheritance[]> } | null = null;
/** The project whose graph is cached; `""` for no project (a loose file). */
function projectRoot(): string {
return useProject.getState().project?.root ?? "";
}
/** Forgets the cached graph (files changed, a server settled, or tests). */
export function forgetInheritanceGraph() {
inheritanceGraphCache = null;
}
function inheritanceGraph(): Promise<ClassInheritance[]> {
const root = projectRoot();
if (!inheritanceGraphCache || inheritanceGraphCache.root !== root) {
inheritanceGraphCache = { root, promise: lspRequest(() => commands.navInheritance()) };
// A failed request must not stick: the next pass retries it.
inheritanceGraphCache.promise.catch(() => {
if (inheritanceGraphCache?.root === root) inheritanceGraphCache = null;
});
}
return inheritanceGraphCache.promise;
}
/** Subscribes once per window and stays subscribed, so the settle echo guard survives remounts. */
function watchChanges() {
if (watching) return;
watching = true;
onIdeEvent("fsChanged", (e) => {
if (affectsMarkers([...e.created, ...e.modified, ...e.removed])) changes++;
if (!affectsMarkers([...e.created, ...e.modified, ...e.removed])) return;
changes++;
forgetInheritanceGraph();
});
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
docMarkers.clear();
forgetInheritanceGraph();
for (const plugin of live) plugin.refreshSoon();
});
}
@@ -131,6 +166,18 @@ export interface MarkerDeps {
implementations: (positions: Pos[]) => Promise<Location[][]>;
supers: SuperDeps;
readFiles: (paths: readonly string[]) => Promise<Map<string, string[] | null>>;
/**
* Every Python class of the project and its base names (the IDE index, attached
* dependency roots included). Some servers (basedpyright, pyrefly) answer no
* `typeHierarchyProvider`, so ↑/↓ are computed from this graph instead.
* Absent for languages whose servers do provide one (Java, Go, ...).
*/
inheritance?: () => Promise<ClassInheritance[]>;
/**
* The file a Python `import` path names (`from a.b import X`), `.x` resolved
* relative to `from`. Disambiguates a base name two files both declare.
*/
moduleFile?: (module: string, from: string) => Promise<string | null>;
}
interface CacheEntry {
@@ -142,6 +189,8 @@ interface CacheEntry {
export interface MarkerCache {
entries: Map<string, CacheEntry>;
unsupported: Set<MarkerGroup>;
/** The Python inheritance graph for this document version, fetched once per cache. */
inheritance?: Promise<ClassInheritance[] | null>;
}
export const emptyCache = (): MarkerCache => ({ entries: new Map(), unsupported: new Set() });
@@ -164,11 +213,16 @@ export async function fillMarkers(
if (!e) cache.entries.set(key, (e = {}));
return e;
};
// A Python inheritance graph answers both groups even when the language server
// has no type hierarchy: it must keep the candidates alive through the LSP
// "unsupported" bookkeeping, or the fallback would never get to run.
const graph = deps.inheritance ? await (cache.inheritance ??= deps.inheritance().catch(() => null)) : null;
const fallback = (graph?.length ?? 0) > 0;
const down =
groups.has("inheritors") && !cache.unsupported.has("inheritors")
groups.has("inheritors") && (fallback || !cache.unsupported.has("inheritors"))
? candidates.filter((c) => c.inheritable && cache.entries.get(candidateKey(c))?.inheritors === undefined)
: [];
const askSupers = groups.has("supers") && !cache.unsupported.has("supers");
const askSupers = groups.has("supers") && (fallback || !cache.unsupported.has("supers"));
const up = askSupers
? candidates.filter((c) => c.overriding && c.owner && cache.entries.get(candidateKey(c))?.supers === undefined)
: [];
@@ -186,8 +240,11 @@ export async function fillMarkers(
asked = await deps.implementations(ask.map((c) => ({ line: c.line, col: c.col })));
} catch (e) {
if (isCancelled(e)) throw e;
if (isUnavailable(e)) cache.unsupported.add("inheritors");
for (let i = down.length - 1; i >= 0; i--) if (!known.has(down[i]!)) down.splice(i, 1);
// With a fallback the candidates stay: the graph may still answer them.
if (!fallback) {
if (isUnavailable(e)) cache.unsupported.add("inheritors");
for (let i = down.length - 1; i >= 0; i--) if (!known.has(down[i]!)) down.splice(i, 1);
}
}
}
implementations = down.map((c) => withoutSelf(path, c, known.get(c) ?? asked[ask.indexOf(c)] ?? []));
@@ -208,8 +265,84 @@ export async function fillMarkers(
}),
);
}
// Python without a type-hierarchy provider: the IDE's inheritance graph holds every
// `class X(A)` of the project, so ↑/↓ are computed from it instead.
const byName = new Map<string, ClassInheritance[]>();
if (graph) for (const cls of graph) byName.set(cls.name, [...(byName.get(cls.name) ?? []), cls]);
// The inheritance graph's direct subclasses, keyed by the *declaration* each base
// resolves to (path + position), so classes sharing a bare name never mix up.
const resolver = baseResolver(byName, deps);
const subclassesOf = new Map<string, ClassInheritance[]>();
for (const cls of graph ?? []) {
for (const base of new Set(cls.bases)) {
// Only this file's classes are looked up below: read another file's imports only
// when its base may name one of them, not for every shared or library base name.
const exact = resolver.exact(base, cls.path);
const named = exact.length || !byName.get(base)?.some((c) => c.path === path) ? exact : null;
for (const decl of named ?? (await resolver.resolve(base, cls.path))) {
const key = declarationKey(decl);
subclassesOf.set(key, [...(subclassesOf.get(key) ?? []), cls]);
}
}
}
const classOf = (c: MarkerCandidate): ClassInheritance | null => {
// A class candidate is its own declaration; a method's is the `owner` it records.
const at = c.method ? c.owner : { line: c.line, col: c.col };
if (!at) return null;
const cls = candidates.find((k) => !k.method && k.line === at.line && k.col === at.col) ?? (c.method ? null : c);
if (!cls) return null;
return byName.get(cls.name)?.find((x) => x.path === path && x.line === cls.line && x.col === cls.col) ?? null;
};
/** The declarations a subclass overrides: the subclass itself, or its same-named method. */
const subclassDeclarations = async (c: MarkerCandidate, owner: ClassInheritance): Promise<Location[]> => {
const subs = subclassesOf.get(declarationKey(owner)) ?? [];
if (!c.method) return subs.map(classLocation);
const bare = c.symbol.replace(/\s*[(<].*$/, "");
const targets: Location[] = [];
for (const sub of subs) {
const outline = await deps.supers.outline(sub.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, sub, bare);
if (m) targets.push({ path: sub.path, range: m.selection_range });
}
return targets;
};
if (byName.size) {
for (let i = 0; i < down.length; i++) {
const c = down[i]!;
const owner = classOf(c);
if (!owner) continue;
// Merge, never replace: a server that answers sees one root, so its list can miss
// the subclasses living in an attached project while still being non-empty.
implementations[i] = withoutSelf(
path,
c,
mergeLocations(implementations[i] ?? [], await subclassDeclarations(c, owner)),
);
}
}
const supers: SuperMethod[][] = [];
for (const c of up) supers.push(await superMethodTargets(path, c.owner!, c.symbol, deps.supers));
if (byName.size) {
for (let i = 0; i < up.length; i++) {
const c = up[i]!;
const self = classOf(c);
if (!self) continue;
const found = await superMethodsFrom(resolver, self.name, c.symbol, deps);
if (!found.length) continue;
const known = supers[i]!;
// Same merge rule as ↓: add the graph's super methods to what the server answered.
const extra = found.map((f) => f.location).filter((l) => !known.some((s) => sameLocation(s.location, l)));
const owners = [...new Set(found.map((f) => f.owner))].sort((a, b) => a.localeCompare(b));
entry(c).supers = {
kind: "overriding",
line: c.line,
name: c.name,
targets: [...known.map((s) => s.location), ...extra],
tooltip: tx`Overrides method in ${owners.join(", ")}`,
chooserTitle: tx`Choose Super Method of ${c.name} (${known.length + extra.length} found)`,
};
}
}
// Go: an implementation request on a type or method answers the interfaces it satisfies.
let satisfied: Location[][] = [];
if (implicit.length) {
@@ -228,10 +361,195 @@ export async function fillMarkers(
...satisfied.flat().map((l) => l.path),
]);
down.forEach((c, i) => (entry(c).inheritors = inheritorsMarker(c, implementations[i] ?? [], files)));
up.forEach((c, i) => (entry(c).supers = supersMarker(c, supers[i]!, files)));
// A candidate the graph answered already has its marker: don't null it out here.
up.forEach((c, i) => {
if (supers[i]!.length) entry(c).supers = supersMarker(c, supers[i]!, files);
});
implicit.forEach((c, i) => (entry(c).supers = implementsMarker(c, withoutSelf(path, c, satisfied[i] ?? []), files)));
}
// One entry per declaration line: the server and the graph may point at the same
// declaration with different columns (the name vs the whole statement).
const sameLocation = (a: Location, b: Location) => a.path === b.path && a.range.start.line === b.range.start.line;
/** `first`, then the locations of `more` not already in it. */
function mergeLocations(first: readonly Location[], more: readonly Location[]): Location[] {
return [...first, ...more.filter((l) => !first.some((f) => sameLocation(f, l)))];
}
/** Identifies one class declaration in the inheritance graph. */
function declarationKey(cls: ClassInheritance): string {
return `${cls.path}:${cls.line}:${cls.col}`;
}
/**
* The classes a base name names. A bare name is only trusted when it is unique in the
* project, or names a class in the subclass's own file: a `Config` declared in hundreds
* of modules must not make every one of them a subclass of every other. When several
* files declare it, the subclass's own imports decide (`from x.y import Config`).
*/
interface BaseResolver {
/** The graph's classes by name. */
byName: ReadonlyMap<string, ClassInheritance[]>;
/** A base that names one class, or a class of the subclass's own file. */
exact(name: string, from: string): ClassInheritance[];
/** `exact`, else the declaration the file's imports point at (empty when unknown). */
resolve(name: string, from: string): Promise<ClassInheritance[]>;
}
function baseResolver(byName: ReadonlyMap<string, ClassInheritance[]>, deps: MarkerDeps): BaseResolver {
const imports = new Map<string, Promise<Map<string, ImportBinding> | null>>();
const answers = new Map<string, Promise<ClassInheritance[]>>();
const exact = (name: string, from: string): ClassInheritance[] => {
const found = byName.get(name) ?? [];
return found.length <= 1 ? found : found.filter((c) => c.path === from);
};
const bindingsOf = (from: string): Promise<Map<string, ImportBinding> | null> => {
let pending = imports.get(from);
if (!pending) {
pending = deps
.readFiles([from])
.then((files) => {
const lines = files.get(from);
return lines ? importBindings(lines) : null;
})
.catch(() => null);
imports.set(from, pending);
}
return pending;
};
return {
byName,
exact,
resolve: (name, from) => {
const found = exact(name, from);
if (found.length) return Promise.resolve(found);
// No class of that name at all: it may be an import alias (`import X as Y`).
const key = `${from}\u0000${name}`;
let pending = answers.get(key);
if (!pending) {
pending = (async () => {
const binding = (await bindingsOf(from))?.get(name);
if (!binding || !deps.moduleFile) return [];
// `from . import X` names the package itself: resolve its `__init__`.
const module = binding.module;
const named = /^\.+$/.test(module) ? `${module.endsWith(".") ? module : `${module}.`}__init__` : module;
const file = await deps.moduleFile(named, from).catch(() => null);
// The declaration carries the imported (pre-alias) name.
return file ? (byName.get(binding.name) ?? []).filter((c) => c.path === file) : [];
})();
answers.set(key, pending);
}
return pending;
},
};
}
/**
* Where a name written in a file comes from: the module of a `from` import and the
* name it is declared under there (equal unless the import aliases it).
*/
export interface ImportBinding {
module: string;
name: string;
}
/**
* The local name -> declaration bindings of a file's `from` imports:
* `from a.b import X as Y` binds `Y` to (`a.b`, `X`). Plain `import a.b` statements
* are skipped: a base written through them keeps its qualifier, which this graph
* does not store.
*/
export function importBindings(lines: readonly string[]): Map<string, ImportBinding> {
const out = new Map<string, ImportBinding>();
for (let i = 0; i < lines.length; i++) {
const line = (lines[i] ?? "").replace(/#.*$/, "");
const from = /^\s*from\s+(\.*[\w.]*)\s+import\s+(.*)$/.exec(line);
if (!from) continue;
let body = from[2]!.trim();
if (body.startsWith("(")) {
// The names may span lines inside the parentheses.
let text = body.slice(1);
while (!text.includes(")") && i + 1 < lines.length) text += ` ${(lines[++i] ?? "").replace(/#.*$/, "")}`;
body = text.slice(0, text.indexOf(")") < 0 ? undefined : text.indexOf(")"));
}
for (const part of body.split(",")) {
const [name, alias] = part.trim().split(/\s+as\s+/);
const declared = (name ?? "").trim();
if (!declared || declared === "*" || !/^\w+$/.test(declared)) continue;
const local = (alias ?? declared).trim();
if (!/^\w+$/.test(local)) continue;
out.set(local, { module: from[1]!, name: declared });
}
}
return out;
}
/** The class declaration itself as a navigation target (its name identifier). */
function classLocation(cls: ClassInheritance): Location {
const start = { line: cls.line, col: cls.col };
return { path: cls.path, range: { start, end: start } };
}
/** The method `method` (bare name) directly inside the class at `cls`'s position. */
function methodInOutline(outline: readonly OutlineItem[], cls: ClassInheritance, method: string): OutlineItem | null {
const at = cls;
const find = (items: readonly OutlineItem[]): OutlineItem | null => {
for (const it of items) {
if (it.kind === "class" && it.selection_range.start.line === at.line && it.selection_range.start.col === at.col) {
return it.children.find((ch) => ch.kind === "method" && baseName(ch.name) === method) ?? null;
}
const deeper = find(it.children);
if (deeper) return deeper;
}
return null;
};
return find(outline);
}
/**
* Super methods of `method` declared by a class in `byName`, walking the inheritance
* graph's bases up to a few levels. Empty when no base declares the method.
*/
async function superMethodsFrom(
resolver: BaseResolver,
start: string,
method: string,
deps: MarkerDeps,
depth = 3,
): Promise<{ location: Location; owner: string }[]> {
const bare = method.replace(/\s*[(<].*$/, "");
const seen = new Set<string>([start]);
let level = [start];
for (let d = 0; d < depth && level.length; d++) {
const next: string[] = [];
const found: { location: Location; owner: string }[] = [];
for (const name of level) {
for (const cls of resolver.byName.get(name) ?? []) {
for (const base of cls.bases) {
if (!seen.add(base)) continue;
// Same rule as the graph: a base the imports name, else a unique one.
const declarations = await resolver.resolve(base, cls.path);
let answered = false;
for (const baseCls of declarations) {
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, baseCls, bare);
if (m) {
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
answered = true;
}
}
// Not found in a base that declares nothing: keep walking its own bases.
if (!answered) next.push(base);
}
}
}
if (found.length) return found;
level = next;
}
return [];
}
/**
* Overriders of a type's methods from one walk of its subtypes and their outlines, instead of one
* implementation request per method: jdtls builds the type hierarchy again for every implementation
@@ -575,6 +893,12 @@ function markerDeps(ctx: EditorDocContext, items: OutlineItem[], request: Reques
},
},
readFiles: readManyFileLines,
// Python servers answer no type hierarchy (basedpyright, pyrefly): the IDE's
// own index knows every `class X(Base)` of the project, attached roots included.
inheritance: ctx.language === "python" ? inheritanceGraph : undefined,
// A base name several modules declare is resolved through the file's imports.
moduleFile:
ctx.language === "python" ? (name, from) => lspRequest(() => commands.navResolveModule(name, from)) : undefined,
};
}
+250 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
IpcError,
type ClassInheritance,
type HierarchyItem,
type Location,
type OutlineItem,
@@ -27,6 +28,7 @@ import {
emptyCache,
enabledGroups,
fillMarkers,
importBindings,
markerBatches,
markersOf,
noteOtherChanges,
@@ -208,8 +210,9 @@ function server(
impls: Record<string, Location[]>,
supers: Record<string, HierarchyItem[]>,
subtypes: Record<string, HierarchyItem[]> = {},
inheritance?: ClassInheritance[],
) {
const calls = { implementations: [] as Pos[][], supertypes: 0, subtypes: 0 };
const calls = { implementations: [] as Pos[][], supertypes: 0, subtypes: 0, inheritance: 0 };
const outlines: Record<string, OutlineItem[]> = {
[SHAPE_PATH]: SHAPE_OUTLINE,
"/p/Circle.java": CIRCLE_OUTLINE,
@@ -234,6 +237,44 @@ function server(
outline: async (p) => outlines[p] ?? [],
},
readFiles: async (paths) => new Map(paths.map((p) => [p, FILES[p] ?? null])),
inheritance: inheritance
? async () => {
calls.inheritance++;
return inheritance;
}
: undefined,
});
return { calls, deps };
}
/** A Python project: the server answers neither implementations nor a type hierarchy. */
function pythonServer(
inheritance: ClassInheritance[],
outlines: Record<string, OutlineItem[]>,
files: Record<string, string[]> = {},
modules: Record<string, string> = {},
) {
const calls = { implementations: 0, inheritance: 0, modules: [] as string[] };
const deps = (): MarkerDeps => ({
implementations: async () => {
calls.implementations++;
throw new IpcError({ kind: "unavailable", message: "basedpyright doesn't support implementation" });
},
supers: {
supertypes: async () => {
throw new IpcError({ kind: "unavailable", message: "basedpyright doesn't support type hierarchy" });
},
outline: async (p) => outlines[p] ?? [],
},
readFiles: async (paths) => new Map(paths.map((p) => [p, files[p] ?? null])),
moduleFile: async (module, from) => {
calls.modules.push(`${module}@${from}`);
return modules[`${module}@${from}`] ?? null;
},
inheritance: async () => {
calls.inheritance++;
return inheritance;
},
});
return { calls, deps };
}
@@ -637,3 +678,211 @@ describe("overriders of a type's methods from its subtypes", () => {
]);
});
});
describe("python inheritance fallback", () => {
// a.py: `class A` (line 0) with `m` (line 1), then `class B(A)` (line 3) with `m` (line 4).
const outline = [
item("A", "class", 0, 2, [item("m", "method", 1, 1)], 6),
item("B", "class", 3, 5, [item("m", "method", 4, 4)], 6),
];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "A", bases: [] },
{ path: "/p/a.py", line: 3, col: 6, name: "B", bases: ["A"] },
];
it("marks the subclass and the overridden method with no type hierarchy", async () => {
const { deps, calls } = pythonServer(graph, { "/p/a.py": outline });
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
const markers = cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.targets.map((t) => t.path)]);
expect(markers).toEqual([
// The class B subclasses A...
[0, "overridden", ["/p/a.py"]],
// ...and its `m` overrides A's `m`.
[1, "overridden", ["/p/a.py"]],
[4, "overriding", ["/p/a.py"]],
]);
// The graph is asked once per cache, not once per candidate.
expect(calls.inheritance).toBe(1);
});
it("survives an unavailable implementation provider (the fallback keeps its candidates)", async () => {
const { deps, calls } = pythonServer(graph, { "/p/a.py": outline });
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
// The server said "unavailable", but the graph still answered ↓ and ↑.
expect(calls.implementations).toBeGreaterThan(0);
expect(cache.unsupported.size).toBe(0);
});
it("adds the graph's cross-project subclasses to a non-empty server answer", async () => {
// The server (single root) answers the local subclass only; the attached-project
// subclass is known to the IDE's graph and must join the list.
const outline = [item("A", "class", 0, 2, [], 6), item("B", "class", 3, 5, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "A", bases: [] },
{ path: "/p/a.py", line: 3, col: 6, name: "B", bases: ["A"] },
{ path: "/p/attached/a.py", line: 0, col: 6, name: "C", bases: ["A"] },
];
const { deps } = server({ "/p/a.py:0": [loc("/p/a.py", 3)] }, {}, {}, graph);
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps("/p/a.py"), cache);
const targets = cachedMarkers(candidates, ALL, cache)
.filter((m) => m.line === 0)
.flatMap((m) => m.targets.map((t) => t.path));
expect(targets).toEqual(["/p/a.py", "/p/attached/a.py"]);
});
it("ignores a bare base name that many classes in the project share", async () => {
// `Config` is declared in hundreds of modules: no edge, so no marker.
const outline = [item("Child", "class", 0, 2, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 0, col: 6, name: "Child", bases: ["Config"] },
];
const { deps } = pythonServer(graph, { "/p/c.py": outline });
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/c.py", candidates, ALL, deps(), cache);
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
});
it("trusts a shared base name when the subclass's own file declares it", async () => {
const outline = [item("Config", "class", 0, 1, [], 6), item("Child", "class", 3, 5, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/c.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/other.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 3, col: 6, name: "Child", bases: ["Config"] },
];
const { deps } = pythonServer(graph, { "/p/c.py": outline });
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/c.py", candidates, ALL, deps(), cache);
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
});
it("resolves an ambiguous base name through the subclass file's imports", async () => {
// Two modules declare `Config`; `from pkg.b import Config` picks one of them, so
// only b.py's Config is marked as subclassed.
const child = [item("Child", "class", 3, 4, [], 6)];
const parentOutline = [item("Config", "class", 0, 1, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 3, col: 6, name: "Child", bases: ["Config"] },
];
const files = { "/p/c.py": ["from pkg.b import Config", "", "", "class Child(Config):"] };
const modules = { "pkg.b@/p/c.py": "/p/b.py" };
const { deps, calls } = pythonServer(graph, { "/p/c.py": child, "/p/b.py": parentOutline }, files, modules);
const candidates = markerCandidates(parentOutline, () => "");
const cache = emptyCache();
await fillMarkers("/p/b.py", candidates, ALL, deps(), cache);
expect(calls.modules).toEqual(["pkg.b@/p/c.py"]);
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.targets.map((t) => t.path)])).toEqual([
[0, "overridden", ["/p/c.py"]],
]);
});
it("resolves a base through an aliased import", async () => {
// c.py: `class Child(Cfg)` (line 3) with `m` (line 4); b.py's Config declares `m` too.
const outline = [item("Child", "class", 3, 5, [item("m", "method", 4, 4)], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 3, col: 6, name: "Child", bases: ["Cfg"] },
];
const files = {
"/p/c.py": ["from pkg.b import Config as Cfg", "", "", "class Child(Cfg):", " def m(self): ..."],
};
const outlines = {
"/p/c.py": outline,
"/p/a.py": [item("Config", "class", 0, 2, [item("m", "method", 1, 1)], 6)],
"/p/b.py": [item("Config", "class", 0, 2, [item("m", "method", 1, 1)], 6)],
};
const { deps } = pythonServer(graph, outlines, files, { "pkg.b@/p/c.py": "/p/b.py" });
const candidates = markerCandidates(outline, () => "");
const cache = emptyCache();
await fillMarkers("/p/c.py", candidates, ALL, deps(), cache);
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.targets.map((t) => t.path)])).toEqual([
[4, "overriding", ["/p/b.py"]],
]);
});
it("reads no other file's imports for a shared base this file does not declare", async () => {
const outline = [item("Other", "class", 0, 1, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 3, col: 6, name: "Child", bases: ["Config", "BaseModel"] },
{ path: "/p/d.py", line: 0, col: 6, name: "Other", bases: [] },
];
const files = { "/p/c.py": ["from pkg.b import Config", "", "", "class Child(Config, BaseModel):"] };
const { deps, calls } = pythonServer(graph, { "/p/d.py": outline }, files, { "pkg.b@/p/c.py": "/p/b.py" });
const cache = emptyCache();
await fillMarkers(
"/p/d.py",
markerCandidates(outline, () => ""),
ALL,
deps(),
cache,
);
expect(calls.modules).toEqual([]);
});
it("keeps ignoring a shared base name when no import names it", async () => {
const outline = [item("Child", "class", 0, 2, [], 6)];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
{ path: "/p/c.py", line: 0, col: 6, name: "Child", bases: ["Config"] },
];
// No import of `Config`: the name stays ambiguous and no edge is invented.
const files = { "/p/c.py": ["import os", "", "class Child(Config):"] };
const { deps } = pythonServer(graph, { "/p/c.py": outline }, files);
const cache = emptyCache();
await fillMarkers(
"/p/c.py",
markerCandidates(outline, () => ""),
ALL,
deps(),
cache,
);
expect(
cachedMarkers(
markerCandidates(outline, () => ""),
ALL,
cache,
),
).toEqual([]);
});
it("reads plain, aliased and parenthesized imports", () => {
const bindings = importBindings([
"from pkg.mod import A, B as Bee",
"from pkg import (",
" C,",
" D as Dee,",
")",
"import x.y as xy",
"if TYPE_CHECKING:",
]);
expect(Object.fromEntries(bindings)).toEqual({
A: { module: "pkg.mod", name: "A" },
Bee: { module: "pkg.mod", name: "B" },
C: { module: "pkg", name: "C" },
Dee: { module: "pkg", name: "D" },
});
});
it("keeps the existing server path when no inheritance graph is injected", async () => {
const { deps } = server({}, {});
const candidates = markerCandidates([item("Foo", "class", 0, 2, [item("m", "method", 1, 1)], 6)], () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps("/p/a.py"), cache);
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
});
});
+34
Переглянути файл
@@ -189,6 +189,40 @@
.modelEffortPopup .modelList {
max-height: 216px;
}
.catalogFooter {
margin-top: 6px;
padding: 8px 12px 2px;
border-top: 1px solid var(--border);
}
.catalogNote,
.catalogError {
margin: 0;
padding: 6px 12px;
color: var(--fg-muted);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.catalogError {
color: var(--danger);
}
.catalogFooter .catalogError {
padding: 0 0 8px;
}
.refreshModels {
padding: 4px 0;
border: 0;
background: transparent;
color: var(--fg);
font: inherit;
cursor: pointer;
}
.refreshModels:hover:not(:disabled) {
color: var(--fg-strong);
}
.refreshModels:disabled {
color: var(--fg-muted);
cursor: default;
}
.effortHeader {
display: flex;
align-items: baseline;
+12
Переглянути файл
@@ -133,6 +133,8 @@ export interface ComposerProps {
onSubmit: (now: boolean) => void;
disabled?: boolean;
autoFocus?: boolean;
/** A request from this host to focus its input without changing the selection. */
focusRequest?: number;
/** Left of the bottom row: agent / model / mode pickers. */
toolbar?: ReactNode;
/** Right of the bottom row: send / stop buttons. */
@@ -346,6 +348,16 @@ export function Composer(props: ComposerProps) {
});
}, [focus]);
const previousFocusRequest = useRef(props.focusRequest);
useEffect(() => {
if (previousFocusRequest.current === props.focusRequest) return;
previousFocusRequest.current = props.focusRequest;
const view = viewRef.current;
if (!props.focusRequest || props.disabled || !view) return;
view.focus();
view.dispatch({ scrollIntoView: true });
}, [props.focusRequest, props.disabled]);
// `@` completion: project file search, mapped into the task's directory.
useEffect(() => {
if (completion?.kind !== "file") return;
+73 -11
Переглянути файл
@@ -4,7 +4,7 @@
* list and an effort slider; with a mode and an on/off permissions option (Allow All),
* the mode menu carries the switch. Names and descriptions are the agent's own.
*/
import { useRef, useState, type CSSProperties } from "react";
import { useEffect, useRef, useState, type CSSProperties } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -48,25 +48,45 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
interface ModelRefresh {
refreshing: boolean;
retryAtMs: number | null;
error: string | null;
onRefresh: () => void;
}
export function ConfigPickers({
config,
values,
onChange,
modelRefresh,
}: {
config: readonly AgentConfigOption[];
/** Chosen values that override `current`, by option id. */
values?: Record<string, string>;
onChange: (option: string, value: string) => void;
/** Only New Task supplies catalog discovery; session pickers retain their own settings. */
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const anchor = useRef<HTMLButtonElement>(null);
const options = mainOptions(config);
if (modelRefresh && !options.some((o) => o.category === "model"))
options.unshift({
id: "model",
name: "Model",
category: "model",
description: null,
current: null,
values: [],
via: "option",
});
const valueOf = (o: AgentConfigOption) => values?.[o.id] ?? o.current ?? null;
const model = options.find((o) => o.category === "model");
const effort = config.find((o) => o.category === "thought_level" && o.values.length > 0);
const modelConfigs = modelConfigOptions(config);
const combinedModel = model && (effort || modelConfigs.length > 0);
const combinedModel = model && (modelRefresh || effort || modelConfigs.length > 0);
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
@@ -92,6 +112,7 @@ export function ConfigPickers({
modelConfigs={modelConfigs}
valueOf={valueOf}
onChange={onChange}
modelRefresh={modelRefresh}
/>
) : o === mode && allowAll ? (
<ModePicker
@@ -206,6 +227,7 @@ function ModelEffortPicker({
modelConfigs,
valueOf,
onChange,
modelRefresh,
}: {
model: AgentConfigOption;
modelValue: string | null;
@@ -214,11 +236,15 @@ function ModelEffortPicker({
modelConfigs: AgentConfigOption[];
valueOf: (o: AgentConfigOption) => string | null;
onChange: (option: string, value: string) => void;
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const anchor = useRef<HTMLButtonElement>(null);
const modelName = selected(model, modelValue)?.name ?? tx("Default");
const unavailable = modelRefresh && modelValue !== null && !selected(model, modelValue);
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selected(model, modelValue)?.name ?? tx("Default"));
const effortName = effort ? (selected(effort, effortValue)?.name ?? tx("Default")) : null;
const modelConfigSummary = modelConfigs
.map((o) => {
@@ -266,6 +292,11 @@ function ModelEffortPicker({
aria-label={tx("Model & effort settings")}
className={styles.modelEffortPopup}
>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{effort && (
<div className={styles.effortBlock}>
<div className={styles.effortHeader}>
@@ -281,19 +312,50 @@ function ModelEffortPicker({
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model)}
searchable
listClassName={styles.modelList}
onChoose={(v) => onChange(model.id, v)}
/>
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model)}
searchable
listClassName={styles.modelList}
onChoose={(v) => onChange(model.id, v)}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</Popup>
</>
);
}
function ModelRefreshFooter({ refreshing, retryAtMs, error, onRefresh }: ModelRefresh) {
const tx = useTx();
const [now, setNow] = useState(Date.now);
const remaining = retryAtMs == null ? 0 : Math.max(0, Math.ceil((retryAtMs - now) / 1000));
const coolingDown = remaining > 0;
useEffect(() => {
if (!coolingDown) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [retryAtMs, coolingDown]);
return (
<div className={styles.catalogFooter}>
{error && (
<p className={styles.catalogError} role="alert">
{tx`Could not refresh models: ${error}`}
</p>
)}
<button type="button" className={styles.refreshModels} disabled={refreshing || coolingDown} onClick={onRefresh}>
{refreshing ? tx("Refreshing…") : coolingDown ? tx`Refresh in ${remaining}s` : tx("Refresh models")}
</button>
</div>
);
}
/** A stepped slider over the agent's effort levels, in the order the agent lists them. */
function EffortSlider({
option,
+13 -2
Переглянути файл
@@ -3,7 +3,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentConfigOption, AgentProvider, NewAgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { HomeEditor } from "./HomeEditor";
import { HOME, savedDraft, updateComposer, useAgents } from "./store";
import { HOME, disconnect, savedDraft, updateComposer, useAgents } from "./store";
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn() }));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok", data });
@@ -11,6 +11,16 @@ vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
agentProviders: () => ok(backend.providers),
agentRefreshModels: (provider: string) =>
ok({
provider,
config: backend.providers.find((p) => p.id === provider)?.config ?? [],
thoughtLevels: backend.providers.find((p) => p.id === provider)?.thoughtLevels ?? {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
}),
agentProbe: () => ok(null),
vcsBranchInfo: () => ok({ head: "main" }),
vcsBranches: () => ok([]),
@@ -34,6 +44,7 @@ const option = (id: string, category: string, values: string[], current: string)
});
beforeEach(() => {
disconnect();
backend.create.mockReset().mockImplementation((req: NewAgentTask) => ok({ id: "new", config: req.config }));
backend.providers = [
{
@@ -95,7 +106,7 @@ it("switches model-specific levels and restores each draft effort before startin
it.each(["plain", "unknown"])("hides effort for %s models and sends no stale effort", async (model) => {
render(<HomeEditor />);
await chooseModel(model);
expect(screen.getByRole("button", { name: "Model" })).toHaveAttribute("aria-haspopup", "listbox");
expect(screen.getByRole("button", { name: "Model" })).toHaveAttribute("aria-haspopup", "dialog");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: model }]);
+46 -11
Переглянути файл
@@ -20,6 +20,7 @@ import {
NO_COMMANDS,
draftConfig,
refreshProviders,
refreshModels,
setDraftOption,
startTask,
updateDraft,
@@ -81,6 +82,24 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command);
const catalog = useAgents((s) => s.modelCatalogs.get(provider?.id ?? ""));
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
const launch = provider && JSON.stringify([provider.program, provider.args, provider.env, provider.command]);
useEffect(() => {
if (!provider?.installed) return;
const refresh = () => void refreshModels(provider.id, false);
refresh();
window.addEventListener("focus", refresh);
return () => window.removeEventListener("focus", refresh);
}, [provider?.id, provider?.installed, launch, project?.root]);
const defaults = useAgentSettings().defaults;
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
const unavailableModel = config.some(
(o) =>
o.category === "model" &&
draft.config[o.id] !== undefined &&
!o.values.some((v) => v.value === draft.config[o.id]),
);
const agentCommands = useAgentCommands(provider?.id, null, provider?.commands ?? NO_COMMANDS);
const providerOptions: SelectOption[] = agentOptions(providers, tx, providerIcon);
// Without git under the project there are no worktrees: force the local checkout.
@@ -88,7 +107,11 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
const isolation = isGit ? draft.isolation : "local";
const base = draft.base ?? current;
const canStart =
canSend(composer) && !!provider?.installed && !starting && (!project?.workspace || repoState?.root === root);
canSend(composer) &&
!!provider?.installed &&
!unavailableModel &&
!starting &&
(!project?.workspace || repoState?.root === root);
const start = () => {
if (!canStart) return;
@@ -98,8 +121,6 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)))
.finally(() => setStarting(false));
};
const defaults = useAgentSettings().defaults;
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
return (
<div className={clsx(styles.home, docked && styles.docked)}>
@@ -209,7 +230,21 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
id === ADD_AGENT ? void executeAction("agents.addAgent") : updateDraft({ provider: id, config: {} })
}
/>
<ConfigPickers config={config} onChange={setDraftOption} />
<ConfigPickers
key={provider?.id}
config={config}
onChange={setDraftOption}
modelRefresh={
provider?.installed
? {
refreshing: requestingModels || (catalog?.refreshing ?? false),
retryAtMs: catalog?.retryAtMs ?? null,
error: catalog?.error ?? null,
onRefresh: () => void executeAction("agents.refreshModels"),
}
: undefined
}
/>
</>
}
actions={
@@ -223,6 +258,11 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
/>
{/* Notes under the box don't take part in centring, so the box stays put as they come and go. */}
<div className={styles.notes}>
{unavailableModel && (
<p className={styles.warning} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{probe && (!docked || probe.error) && (
<p className={probe.error ? styles.warning : styles.note}>
{probe.error
@@ -230,17 +270,12 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
: [probe.name, probe.version, probe.protocol].filter(Boolean).join(" · ")}
</p>
)}
{(error || (provider && !provider.installed) || (provider && !provider.config.length)) && (
{(error || (provider && !provider.installed)) && (
<p
className={error || !provider?.installed ? styles.warning : styles.note}
role={error ? "alert" : undefined}
>
{error ??
(provider && !provider.installed ? (
txTemplate(`${provider.command} was not found on PATH`)
) : (
<T>Models and modes appear after this agent's first task.</T>
))}
{error ?? txTemplate(`${provider?.command ?? ""} was not found on PATH`)}
</p>
)}
</div>
+41 -21
Переглянути файл
@@ -201,23 +201,36 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
const openSubagent = useCallback((sub: string) => setPath((p) => [...p, sub]), []);
const [finding, setFinding] = useState(false);
const [findFocus, setFindFocus] = useState(0);
const [session] = useState<FocusedSession>(() => ({
openFind: () => {
setFinding(true);
setFindFocus((n) => n + 1);
},
}));
useEffect(
() => () => {
if (focusedSession() === session) setFocusedSession(null);
},
[session],
const [inputFocus, setInputFocus] = useState(0);
const sessionRoot = useRef<HTMLDivElement>(null);
const canFocusInput = shown && !!task && task.status !== "archived" && !view;
const session = useMemo<FocusedSession>(
() => ({
openFind: () => {
setFinding(true);
setFindFocus((n) => n + 1);
},
focusInput: canFocusInput
? () => {
if (docked) setChangesOpen(false);
setInputFocus((n) => n + 1);
}
: undefined,
}),
[canFocusInput, docked, setChangesOpen],
);
useLayoutEffect(() => {
if (shown && sessionRoot.current?.contains(document.activeElement)) setFocusedSession(session);
return () => {
if (focusedSession() === session) setFocusedSession(null);
};
}, [session, shown]);
if (!task) return <EmptyState title="This agent task no longer exists" />;
return (
<div
ref={sessionRoot}
className={clsx(styles.session, docked && styles.docked)}
onFocusCapture={() => setFocusedSession(session)}
onFocusCapture={() => shown && setFocusedSession(session)}
onBlurCapture={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null) && focusedSession() === session) {
setFocusedSession(null);
@@ -248,6 +261,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
<QuestionCard task={task} entries={entries ?? null} />
<SessionComposer
task={task}
focusRequest={inputFocus}
entries={entries ?? null}
head={head}
changes={changes ?? null}
@@ -2680,6 +2694,7 @@ function PendingPermission({ task, entry }: { task: AgentTask; entry: Permission
function SessionComposer({
task,
focusRequest,
entries,
head,
changes,
@@ -2689,6 +2704,7 @@ function SessionComposer({
onOpenSubagent,
}: {
task: AgentTask;
focusRequest: number;
entries: AgentEntry[] | null;
head: string | null;
changes: AgentChange[] | null;
@@ -2766,6 +2782,7 @@ function SessionComposer({
</Tray>
<Composer
id={task.id}
focusRequest={focusRequest}
placeholder={
!busy
? "Reply to the agent"
@@ -2906,15 +2923,18 @@ function useChangesOpen(
open: docked ? false : loadChangesOpen()[task],
}));
const chosen = state.task === task ? state.open : docked ? false : loadChangesOpen()[task];
const set = (open: boolean) => {
setState({ task, open });
if (docked) return;
try {
globalThis.localStorage?.setItem(CHANGES_OPEN_KEY, JSON.stringify({ ...loadChangesOpen(), [task]: open }));
} catch {
/* storage unavailable */
}
};
const set = useCallback(
(open: boolean) => {
setState({ task, open });
if (docked) return;
try {
globalThis.localStorage?.setItem(CHANGES_OPEN_KEY, JSON.stringify({ ...loadChangesOpen(), [task]: open }));
} catch {
/* storage unavailable */
}
},
[task, docked],
);
return [chosen ?? (changes?.length ?? 0) > 0, set];
}
+12
Переглянути файл
@@ -20,6 +20,18 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
agentCommands: (provider: string, task: string | null) => agentCommands(provider, task),
agentCreate: (request: unknown) => agentCreate(request),
agentRefreshModels: async (provider: string) => ({
status: "ok",
data: {
provider,
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
},
}),
clipboardImage: () => clipboardImage(),
vcsBranchInfo: (root: string | null) => vcsBranchInfo(root),
vcsBranches: (root: string | null) => vcsBranches(root),
+12
Переглянути файл
@@ -40,6 +40,18 @@ vi.mock("@/platform/ipc", async (original) => ({
agentPrompt: backend.prompt,
agentSubscribe: async () => ({ status: "ok", data: [] }),
agentProviders: async () => ({ status: "ok", data: [provider] }),
agentRefreshModels: async (id: string) => ({
status: "ok",
data: {
provider: id,
config: provider.config,
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
},
}),
agentProbe: async () => ({ status: "ok", data: null }),
agentEntries: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
+26 -1
Переглянути файл
@@ -35,7 +35,16 @@ import {
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession } from "./sessionFocus";
import { closeActiveTask, closeAndNewTask, connect, disconnect, openHome, refreshProviders, useAgents } from "./store";
import {
closeActiveTask,
closeAndNewTask,
connect,
disconnect,
openHome,
refreshModels,
refreshProviders,
useAgents,
} from "./store";
import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
import { replyActions } from "./replyActions";
@@ -191,6 +200,15 @@ export function activate(): () => void {
when: "agentSessionFocus",
run: () => focusedSession()?.openFind(),
},
{
id: "agents.focusInput",
title: "Focus Agent Input",
description: "Focuses the message input of the current agent task without moving the caret.",
category: "Agents",
when: "agentSessionFocus && agentInputAvailable",
keyWhen: "agentSessionFocus && !popupOpen",
run: () => focusedSession()?.focusInput?.(),
},
{
id: "agents.newTask",
title: "New Agent Task",
@@ -201,6 +219,13 @@ export function activate(): () => void {
keywords: ["agent", "claude", "codex", "gemini", "ai"],
run: ({ arg }) => openHome(typeof arg === "string" ? arg : undefined),
},
{
id: "agents.refreshModels",
title: "Refresh models",
category: "Agents",
when: "projectOpen",
run: () => refreshModels(),
},
{
id: "agents.closeTask",
title: "Close Agent Task",
+348
Переглянути файл
@@ -0,0 +1,348 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { clearMocks, mockIPC, mockWindows } from "@tauri-apps/api/mocks";
import type {
AgentConfigOption,
AgentEvent,
AgentModelCatalog,
AgentProvider,
NewAgentTask,
ProjectInfo,
} from "@/bindings";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { HomeEditor } from "./HomeEditor";
import { activate } from "./index";
import { HOME, connect, savedDraft, updateComposer, useAgents } from "./store";
const backend = vi.hoisted(() => ({
providers: [] as AgentProvider[],
channel: null as { onmessage: (event: AgentEvent) => void } | null,
refresh: vi.fn(),
create: vi.fn(),
notify: vi.fn(),
}));
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
agentSubscribe: async (channel: typeof backend.channel) => {
backend.channel = channel;
return ok([]);
},
agentProviders: async () => ok(backend.providers),
agentRefreshModels: (provider: string, force: boolean) => backend.refresh(provider, force),
agentProbe: async () => ok(null),
agentCommands: async () => ok([]),
vcsBranchInfo: async () => ok({ head: "main" }),
vcsBranches: async () => ok([]),
agentCreate: (request: NewAgentTask) => backend.create(request),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ activePath: () => null }),
editorService: () => ({
activePath: () => null,
activeInput: () => null,
openTabs: () => [],
closeInput: () => false,
}),
notifications: () => ({ notify: backend.notify }),
}));
const option = (id: string, category: string, values: string[], current = values[0] ?? null): AgentConfigOption => ({
id,
name: id === "model" ? "Model" : "Reasoning",
description: null,
category,
current,
via: "option",
values: values.map((value) => ({ value, name: value, description: null })),
});
const provider = (id: string): AgentProvider => ({
id,
name: id,
command: id,
program: id,
args: [],
defaultProgram: null,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "custom" },
config: [option("model", "model", ["big", "small"])],
thoughtLevels: { big: [option("effort", "thought_level", ["low", "high"], "high")] },
});
function catalog(id = "first", patch: Partial<AgentModelCatalog> = {}): AgentModelCatalog {
const offered = backend.providers.find((p) => p.id === id)!;
return {
provider: id,
config: offered.config,
thoughtLevels: offered.thoughtLevels ?? {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
...patch,
};
}
type CatalogReply = { status: "ok"; data: AgentModelCatalog };
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
const emit = (snapshot: AgentModelCatalog) =>
act(() => backend.channel!.onmessage({ type: "modelCatalog", catalog: snapshot }));
let dispose: () => void;
let previousProject: ProjectInfo | null;
beforeEach(async () => {
vi.clearAllMocks();
mockWindows("main");
mockIPC(() => undefined, { shouldMockEvents: true });
previousProject = useProject.getState().project;
useProject.setState({ project: { root: "/models", trusted: true } as ProjectInfo });
setContext("projectOpen", true);
backend.providers = [provider("first"), provider("second")];
backend.refresh.mockReset().mockImplementation(async (id: string) => ok(catalog(id)));
backend.create
.mockReset()
.mockImplementation(async (request: NewAgentTask) => ok({ id: "new", config: request.config }));
dispose = activate();
await connect();
useAgents.setState({ draft: savedDraft({ provider: "first", config: {} }) });
updateComposer(HOME, { text: "Check the project" });
});
afterEach(async () => {
await vi.dynamicImportSettled();
cleanup();
dispose();
useProject.setState({ project: previousProject });
setContext("projectOpen", false);
vi.useRealTimers();
await vi.dynamicImportSettled();
clearMocks();
});
it("keeps cached choices usable while refreshing and shares the completion/cooldown from another window", async () => {
backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true })));
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("button", { name: "Refreshing…" })).toBeDisabled();
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
emit(catalog("first", { retryAtMs: Date.now() + 30_000 }));
expect(screen.getByRole("button", { name: /Refresh in \d+s/ })).toBeDisabled();
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: "small" }]);
});
it("uses the same popup for model-only agents and coalesces repeated manual action invocations", async () => {
backend.providers[0]!.thoughtLevels = {};
await connect();
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
await screen.findByRole("button", { name: "Refresh models" });
expect(backend.refresh).toHaveBeenCalledExactlyOnceWith("first", false);
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
expect(screen.getByRole("button", { name: "Refreshing…" })).toBeDisabled();
await act(async () => {
await executeAction("agents.refreshModels");
await executeAction("agents.refreshModels");
});
expect(backend.refresh).toHaveBeenCalledTimes(2);
expect(backend.refresh).toHaveBeenLastCalledWith("first", true);
await act(async () => pending.resolve(ok(catalog("first", { refreshing: true }))));
await act(async () => executeAction("agents.refreshModels"));
expect(backend.refresh).toHaveBeenCalledTimes(2);
emit(catalog("first", { retryAtMs: Date.now() + 30_000 }));
await act(async () => executeAction("agents.refreshModels"));
expect(backend.refresh).toHaveBeenCalledTimes(2);
expect(screen.getByRole("button", { name: /Refresh in \d+s/ })).toBeDisabled();
});
it("shows initial loading and inline discovery failure/retry without blocking a model-less agent", async () => {
backend.providers[0]!.config = [];
backend.providers[0]!.thoughtLevels = {};
await connect();
backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true })));
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByText("Loading models…")).toBeVisible();
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
emit(catalog("first", { error: "offline" }));
expect(screen.getByRole("alert")).toHaveTextContent("Could not refresh models: offline");
expect(screen.getByText("No models reported by this agent.")).toBeVisible();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
expect(backend.refresh).toHaveBeenLastCalledWith("first", true);
expect(screen.getByRole("button", { name: "Refreshing…" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.notify).not.toHaveBeenCalled();
});
it("retains cached model and effort choices after a command failure and retries inline", async () => {
backend.refresh.mockRejectedValueOnce(new Error("connection lost"));
useAgents.setState({
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
expect(screen.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "low");
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
expect(backend.notify).not.toHaveBeenCalled();
});
it("preserves a valid remembered model and effort when discovery changes the defaults", async () => {
useAgents.setState({
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
backend.refresh.mockResolvedValueOnce(
ok(
catalog("first", {
config: [option("model", "model", ["small", "big", "new"])],
thoughtLevels: { big: [option("effort", "thought_level", ["low", "high", "max"], "max")] },
}),
),
);
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("biglow");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
expect(screen.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "low");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
{ id: "model", value: "big" },
{ id: "effort", value: "low" },
]);
});
it("keeps a removed explicit model visibly unavailable until another model is chosen", async () => {
useAgents.setState({ draft: savedDraft({ provider: "first", config: { model: "big" } }) });
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
emit(catalog("first", { config: [option("model", "model", ["small"])], thoughtLevels: {} }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big (unavailable)");
expect(screen.getByRole("button", { name: "Start" })).toBeDisabled();
expect(screen.getByRole("alert")).toHaveTextContent("Choose another model before starting.");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: "small" }]);
});
it("keeps the unavailable selection when the agent stops advertising models altogether", async () => {
useAgents.setState({ draft: savedDraft({ provider: "first", config: { model: "big" } }) });
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
emit(catalog("first", { config: [], thoughtLevels: {} }));
backend.providers[0]!.config = [];
await act(async () => backend.channel!.onmessage({ type: "providers" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big (unavailable)");
expect(screen.getByRole("button", { name: "Start" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByText("No models reported by this agent.")).toBeVisible();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
});
it("ignores a delayed refresh after switching agents and preserves the new draft", async () => {
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Agent" }));
fireEvent.click(screen.getByRole("option", { name: "second" }));
await waitFor(() => expect(backend.refresh).toHaveBeenLastCalledWith("second", false));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: "small" }));
await act(async () => pending.resolve(ok(catalog("first", { config: [option("model", "model", ["obsolete"])] }))));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
expect(screen.queryByRole("option", { name: "obsolete" })).not.toBeInTheDocument();
expect(useAgents.getState().modelCatalogs.has("first")).toBe(false);
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
});
it("ignores old project responses and events when the project connection changes", async () => {
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
render(<HomeEditor />);
const oldChannel = backend.channel!;
await act(async () => {
useProject.setState({ project: { root: "/another", trusted: true } as ProjectInfo });
await connect();
pending.resolve(ok(catalog("first", { config: [option("model", "model", ["old-project"])] })));
});
act(() => oldChannel.onmessage({ type: "modelCatalog", catalog: catalog("first", { error: "old error" }) }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.queryByRole("option", { name: "old-project" })).not.toBeInTheDocument();
expect(screen.queryByText(/old error/)).not.toBeInTheDocument();
expect(screen.getByRole("option", { name: "small" })).toBeVisible();
});
it("does not let a delayed command snapshot replace a newer catalog event", async () => {
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
render(<HomeEditor />);
emit(catalog("first", { config: [option("model", "model", ["latest"])] }));
await act(async () => pending.resolve(ok(catalog("first", { refreshing: true }))));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "latest" })).toBeVisible();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
backend.providers[0]!.config = [option("model", "model", ["older-session"])];
await act(async () => backend.channel!.onmessage({ type: "providers" }));
expect(screen.getByRole("option", { name: "latest" })).toBeVisible();
expect(screen.queryByRole("option", { name: "older-session" })).not.toBeInTheDocument();
});
it("requests freshness on focus without a retry timer, and counts down only the displayed cooldown", async () => {
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
fireEvent.focus(window);
await waitFor(() => expect(backend.refresh).toHaveBeenCalledTimes(2));
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
vi.useFakeTimers();
emit(catalog("first", { retryAtMs: Date.now() + 2_000, error: "offline" }));
expect(screen.getByRole("button", { name: "Refresh in 2s" })).toBeDisabled();
act(() => vi.advanceTimersByTime(1_000));
expect(screen.getByRole("button", { name: "Refresh in 1s" })).toBeDisabled();
act(() => vi.advanceTimersByTime(1_000));
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
act(() => vi.advanceTimersByTime(60_000));
expect(backend.refresh).toHaveBeenCalledTimes(2);
});
+3 -1
Переглянути файл
@@ -1,8 +1,9 @@
/** The agent session tab holding focus, for actions that act on it (Find in Conversation). */
/** The agent session holding focus, for actions scoped to that task view. */
import { setContext } from "@/platform/context";
export interface FocusedSession {
openFind(): void;
focusInput?: () => void;
}
let focused: FocusedSession | null = null;
@@ -10,6 +11,7 @@ let focused: FocusedSession | null = null;
export function setFocusedSession(session: FocusedSession | null) {
focused = session;
setContext("agentSessionFocus", !!session);
setContext("agentInputAvailable", !!session?.focusInput);
}
export const focusedSession = () => focused;
+26 -1
Переглянути файл
@@ -24,7 +24,7 @@ import { replyActions } from "./replyActions";
import { focusedSession } from "./sessionFocus";
import styles from "./Session.module.css";
import chipStyles from "./ReferenceChip.module.css";
import { textOf, typeIn } from "./composerTesting";
import { caretOf, textOf, typeIn } from "./composerTesting";
const backend = vi.hoisted(() => ({
entries: new Map<string, AgentEntry[]>(),
@@ -1564,6 +1564,31 @@ describe("conversation loading", () => {
});
describe("session state across tasks and hosts", () => {
it("updates input focus availability while the task changes status without losing its draft caret", async () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const message = screen.getByRole("textbox", { name: "Message" });
typeIn(message, "Draft to keep", 3);
const conversation = stream();
act(() => conversation.focus());
act(() =>
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status: "archived" }),
})),
);
act(() => focusedSession()?.focusInput?.());
expect(conversation).toHaveFocus();
act(() =>
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status: "running" }),
})),
);
act(() => focusedSession()?.focusInput?.());
await waitFor(() => expect(message).toHaveFocus());
expect(textOf(message)).toBe("Draft to keep");
expect(caretOf(message)).toBe(3);
});
it("leaves a task unread while its kept-alive tab is hidden, and reads it once shown", () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
useAgents.setState({ unread: new Set(["A"]) });
+131 -7
Переглянути файл
@@ -13,6 +13,7 @@ import type {
AgentEvent,
AgentImage,
AgentLimit,
AgentModelCatalog,
AgentProvider,
AgentTask,
ExternalSession,
@@ -93,6 +94,8 @@ interface AgentsState {
/** Scroll position and follow-output preference by conversation, shared by both hosts. */
scrollPositions: Map<string, { top: number; stick: boolean }>;
providers: AgentProvider[];
modelCatalogs: Map<string, AgentModelCatalog>;
modelRequests: Set<string>;
/** The usage limits each agent last reported for its account, by provider. */
limits: Map<string, AgentLimit[]>;
draft: Draft;
@@ -171,6 +174,8 @@ export const useAgents = create<AgentsState>(() => ({
groupedChanges: new Map(),
providers: [],
limits: new Map(),
modelCatalogs: new Map(),
modelRequests: new Set(),
draft: savedDraft(load<Partial<Draft>>(DRAFT_KEY, {})),
composers: new Map(),
lastComposer: HOME,
@@ -191,6 +196,7 @@ export const useAgents = create<AgentsState>(() => ({
export function updateDraft(patch: Partial<Draft>) {
const current = useAgents.getState().draft;
if (patch.provider && patch.provider !== current.provider) draftGeneration++;
const draft = {
...current,
...(patch.provider && patch.provider !== current.provider ? { thoughtLevels: {} } : {}),
@@ -205,27 +211,40 @@ export const providerDefaults = (provider: string | undefined): Record<string, s
(provider && useProject.getState().settings?.agents?.defaults?.[provider]) || {};
/**
* Config for the selected model, with only supported choices applied: the draft's, else
* the agent's defaults from Settings › Agents.
* New Task settings use the authoritative catalog, retaining an explicitly selected
* model even if it disappears so the user must choose its replacement.
*/
export function draftConfig(
provider: AgentProvider | undefined,
draft: Draft,
defaults: Record<string, string> = providerDefaults(provider?.id),
): AgentConfigOption[] {
const config = (provider?.config ?? [])
const catalog = provider && useAgents.getState().modelCatalogs.get(provider.id);
const offered = catalog?.config ?? provider?.config ?? [];
const priorModel = provider?.config.find((o) => o.category === "model");
const source =
priorModel && draft.config[priorModel.id] !== undefined && !offered.some((o) => o.category === "model")
? [...offered, { ...priorModel, values: [] }]
: offered;
const config = source
.filter((o) => o.category !== "thought_level")
.map((o) => {
const choice = draft.config[o.id] ?? defaults[o.id];
const explicit = draft.config[o.id];
const choice = explicit ?? defaults[o.id];
return {
...o,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
current:
o.category === "model" && explicit !== undefined
? explicit
: choice !== undefined && o.values.some((v) => v.value === choice)
? choice
: o.current,
};
});
const model = config.find((o) => o.category === "model")?.current;
if (model) {
config.push(
...(provider?.thoughtLevels?.[model] ?? []).map((o) => {
...((catalog ?? provider)?.thoughtLevels?.[model] ?? []).map((o) => {
const choice = draft.thoughtLevels?.[model]?.[o.id] ?? defaults[o.id];
return {
...o,
@@ -314,6 +333,84 @@ export function markVisible(task: string): () => void {
}
let generation = 0;
let draftGeneration = 0;
const modelFlights = new Map<string, { launch: string; generation: number; draftGeneration: number }>();
const selectedProvider = () => {
const { providers, draft } = useAgents.getState();
return providers.find((p) => p.id === draft.provider) ?? providers[0];
};
const launchKey = (provider: AgentProvider) =>
JSON.stringify([provider.program, provider.args, provider.env, provider.installed]);
function applyModelCatalog(catalog: AgentModelCatalog) {
useAgents.setState((s) => {
const previous = s.modelCatalogs.get(catalog.provider);
const model = (previous?.config ?? s.providers.find((p) => p.id === catalog.provider)?.config)?.find(
(o) => o.category === "model",
);
const config =
model && !catalog.config.some((o) => o.category === "model")
? [...catalog.config, { ...model, current: null, values: [] }]
: catalog.config;
return { modelCatalogs: new Map(s.modelCatalogs).set(catalog.provider, { ...catalog, config }) };
});
}
/** Refreshes only the New Task agent; discovery failures stay beside the cached choices. */
export async function refreshModels(provider = selectedProvider()?.id, force = true): Promise<void> {
const selected = selectedProvider();
if (!provider || !selected?.installed || selected.id !== provider || useProject.getState().project?.trusted === false)
return;
const state = useAgents.getState();
const catalog = state.modelCatalogs.get(provider);
const launch = launchKey(selected);
const pending = modelFlights.get(provider);
if (
(pending?.launch === launch && pending.generation === generation && pending.draftGeneration === draftGeneration) ||
catalog?.refreshing ||
(force && catalog?.retryAtMs != null && catalog.retryAtMs > Date.now())
)
return;
const gen = generation;
const draftGen = draftGeneration;
const root = useProject.getState().project?.root;
const flight = { launch, generation: gen, draftGeneration: draftGen };
modelFlights.set(provider, flight);
useAgents.setState((s) => ({ modelRequests: new Set(s.modelRequests).add(provider) }));
const current = () =>
gen === generation &&
root === useProject.getState().project?.root &&
draftGen === draftGeneration &&
selectedProvider()?.id === provider &&
launchKey(selectedProvider()!) === launch;
try {
const result = await call(commands.agentRefreshModels(provider, force));
// A streamed status/completion is newer than the snapshot returned by the command.
if (current() && useAgents.getState().modelCatalogs.get(provider) === catalog) applyModelCatalog(result);
} catch (e) {
if (current() && useAgents.getState().modelCatalogs.get(provider) === catalog)
applyModelCatalog({
provider,
config: catalog?.config ?? selected.config,
thoughtLevels: catalog?.thoughtLevels ?? selected.thoughtLevels ?? {},
refreshedAtMs: catalog?.refreshedAtMs ?? null,
retryAtMs: catalog?.retryAtMs ?? null,
refreshing: false,
error: e instanceof Error ? e.message : String(e),
});
} finally {
if (modelFlights.get(provider) === flight) {
modelFlights.delete(provider);
useAgents.setState((s) => {
const modelRequests = new Set(s.modelRequests);
modelRequests.delete(provider);
return { modelRequests };
});
}
}
}
/** Subscribes this window to the project's agents (again after the project changed). */
export async function connect(): Promise<void> {
@@ -403,6 +500,7 @@ export function disconnect() {
generation++;
arrivedWhileLoading.clear();
streamingReply.clear();
modelFlights.clear();
useAgents.setState({
loaded: false,
error: null,
@@ -412,6 +510,8 @@ export function disconnect() {
entryLoads: new Map(),
changes: new Map(),
groupedChanges: new Map(),
modelCatalogs: new Map(),
modelRequests: new Set(),
organize: EMPTY_ORGANIZE,
organizeRoot: null,
docked: null,
@@ -470,6 +570,10 @@ function onEvent(e: AgentEvent) {
scheduleChanges(e.task);
break;
}
case "modelCatalog": {
if (s.providers.some((p) => p.id === e.catalog.provider)) applyModelCatalog(e.catalog);
break;
}
case "providers": {
void refreshProviders();
break;
@@ -637,8 +741,19 @@ export function scheduleChanges(task: string) {
/** Reloads the agent list (custom and registry agents are re-read). */
export async function refreshProviders() {
const gen = generation;
const root = useProject.getState().project?.root;
const providers = await call(commands.agentProviders()).catch(() => null);
if (providers) useAgents.setState({ providers });
if (!providers || gen !== generation || root !== useProject.getState().project?.root) return;
useAgents.setState((s) => {
const modelCatalogs = new Map(s.modelCatalogs);
for (const [id] of modelCatalogs) {
const previous = s.providers.find((p) => p.id === id);
const provider = providers.find((p) => p.id === id);
if (!provider || (previous && launchKey(previous) !== launchKey(provider))) modelCatalogs.delete(id);
}
return { providers, modelCatalogs };
});
}
export const NO_COMMANDS: readonly AgentCommand[] = [];
@@ -801,6 +916,15 @@ export async function startTask(
providers.find((p) => p.id === draft.provider),
draft,
);
if (
options.some(
(o) =>
o.category === "model" &&
draft.config[o.id] !== undefined &&
!o.values.some((v) => v.value === draft.config[o.id]),
)
)
return;
const askForApprovals = useProject.getState().settings?.agents?.newTaskApprovals === "ask";
const defaults = {
...cursorModelDefaults(draft.provider, options),
+5 -1
Переглянути файл
@@ -440,7 +440,11 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
const treeView = (
<div className={styles.body}>
<SplitGroup orientation="horizontal" id="maven-dependency-analyzer-split">
<SplitGroup
orientation="horizontal"
id="maven-dependency-analyzer-split"
storageKey="openidea.dependencyAnalyzer.split"
>
<SplitPanel id="dependencies" minSize={200} className={styles.panel}>
<Tree<Node>
aria-label="Dependencies"
+6 -1
Переглянути файл
@@ -339,7 +339,12 @@ export function BuildView() {
}
return (
<div className={styles.view}>
<SplitGroup orientation="horizontal" className={styles.split} id="build-view-split">
<SplitGroup
orientation="horizontal"
className={styles.split}
id="build-view-split"
storageKey="openidea.build.split"
>
<SplitPanel id="build-tree" defaultSize="38%" minSize="120px" className={styles.pane}>
<BuildTree />
</SplitPanel>
+1 -1
Переглянути файл
@@ -410,7 +410,7 @@ export function ProblemsView() {
<div className={styles.view}>
<div className={styles.body} onKeyDownCapture={onKeyDownCapture}>
{options.preview ? (
<SplitGroup orientation="horizontal" id="problems-preview-split">
<SplitGroup orientation="horizontal" id="problems-preview-split" storageKey="openidea.problems.previewSplit">
<SplitPanel id="problems" minSize={120} className={styles.panel}>
{list}
</SplitPanel>
+1 -1
Переглянути файл
@@ -401,7 +401,7 @@ function UsagesSplit({ preview, children }: { preview: ReactNode; children: Reac
const show = useUsagesOptions((s) => s.preview);
if (!show) return children;
return (
<SplitGroup orientation="horizontal" id="usages-preview-split">
<SplitGroup orientation="horizontal" id="usages-preview-split" storageKey="openidea.usages.previewSplit">
<SplitPanel id="usages" minSize={160} className={styles.panel}>
{children}
</SplitPanel>
+19
Переглянути файл
@@ -38,6 +38,7 @@ import {
loadDatabases,
listsDatabases,
sourceById,
newConsole,
openConsole,
openHistory,
openSourceDialog,
@@ -198,6 +199,24 @@ export function activate(): () => void {
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
},
{
id: "db.newConsole",
title: "New Query Console",
category: "Tools",
icon: "db-console",
keywords: ["database", "sql console"],
when: "projectOpen",
run: async ({ arg }) => {
const current = projectRequest();
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
const { sources, selectedSource } = useDatabase.getState();
const node = arg && typeof arg === "object" && "kind" in arg ? nodeTarget(arg as DbNode) : null;
const id = node ?? selectedSource ?? (sources.length === 1 ? sources[0]!.id : null);
if (id) await newConsole(id);
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
},
{
id: "db.execute",
title: "Execute SQL Statement",
+23
Переглянути файл
@@ -906,6 +906,29 @@ export async function openConsole(id: string): Promise<void> {
}
}
/** The query console files of data source `id`: `console.sql`, then `console_1.sql`, `console_2.sql`… */
export function consoleFiles(id: string): Promise<string[]> {
return call(commands.dbConsoles(id, false));
}
/** Opens one of the query consoles of data source `id`. */
export async function openConsoleFile(id: string, path: string): Promise<void> {
bindConsole(path, id);
await editorService().openFile(path, { focus: true });
}
/** Creates and opens another query console of data source `id` (DataGrip's New › Query Console). */
export async function newConsole(id: string): Promise<void> {
try {
const before = new Set(await consoleFiles(id));
const after = await call(commands.dbConsoles(id, true));
const path = after.find((p) => !before.has(p)) ?? after[after.length - 1];
if (path) await openConsoleFile(id, path);
} catch (e) {
notifications().notify({ level: "error", title: "Cannot open the query console", body: message(e) });
}
}
let nextTab = 1;
let nextRun = 1;
let nextLine = 1;
+16 -1
Переглянути файл
@@ -22,7 +22,10 @@ import {
loadSchemas,
loadSources,
loadTables,
consoleFiles,
newConsole,
openConsole,
openConsoleFile,
openConsoleWith,
openDdl,
openObjectDdl,
@@ -42,6 +45,7 @@ import {
} from "./store";
import { tableInput } from "./tableInput";
import { tx } from "@/platform/i18n";
import { chooseItem } from "@/workbench/inputDialogs";
import { databaseRequest } from "./requests";
/** Context key: the Database tree has focus. */
@@ -279,7 +283,7 @@ export function registerDatabaseTreeActions(): () => void {
const id = n ? nodeTarget(n) : null;
const { sources } = useDatabase.getState();
const target = id ?? (sources.length === 1 ? (sources[0]!.id ?? null) : null);
if (target) void openConsole(target);
if (target) void jumpToConsole(target);
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
}),
@@ -524,3 +528,14 @@ export function registerDatabaseTreeActions(): () => void {
}),
]);
}
/** One console opens directly; with several, DataGrip's list of them plus New Query Console. */
async function jumpToConsole(id: string): Promise<void> {
const files = await consoleFiles(id).catch(() => []);
if (files.length <= 1) return openConsole(id);
const names = files.map((f) => (f.split(/[\\/]/).pop() ?? f).replace(/\.sql$/, ""));
const create = tx("New Query Console");
const picked = await chooseItem({ title: "Query Consoles", items: [...names, create] });
if (picked === create) await newConsole(id);
else if (picked) await openConsoleFile(id, files[names.indexOf(picked)]!);
}
+2 -2
Переглянути файл
@@ -66,7 +66,7 @@ async function sourceFromClipboard() {
/** The toolbar's "+" menu (IDEA: New). */
export function newMenu(): MenuItem[] {
return [{ kind: "action", action: "db.openConsole", label: "Query Console" }, sep, ...dataSourceItems()];
return [{ kind: "action", action: "db.newConsole", label: "Query Console" }, sep, ...dataSourceItems()];
}
function sqlScripts(n: DbNode, table: boolean): MenuItem {
@@ -88,7 +88,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
const driver = sourceById(id)?.driver ?? "sqlite";
const o = objectOf(n);
const t = tableOf(n);
const newConsole = act("db.openConsole", n, { label: "Query Console", icon: "db-console" });
const newConsole = act("db.newConsole", n, { label: "Query Console", icon: "db-console" });
const refresh = act("db.refresh", n);
const quickDoc = act("db.quickDoc", n);
const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) });
+10 -1
Переглянути файл
@@ -98,6 +98,15 @@ describe("run config → launch config", () => {
});
});
it("cargo run under lldb-dap builds the same way and passes the environment as strings", () => {
const l = launchConfigFor(
rc({ kind: "cargo", command: "cargo", args: ["run"], env: { RUST_LOG: "debug" }, debugAdapter: "lldb-dap" }),
"/p",
)!;
expect(l.adapter).toBe("lldb-dap");
expect(extra(l)).toEqual({ cargo: { args: ["build"], filter: { kind: "bin" } }, env: ["RUST_LOG=debug"] });
});
it("cargo test builds test binaries without running", () => {
const l = launchConfigFor(
rc({ kind: "cargo", command: "cargo", args: ["test", "--workspace"], debugAdapter: "codelldb" }),
@@ -113,7 +122,7 @@ describe("run config → launch config", () => {
)!;
expect(script.program).toBe("/p/manage.py");
expect(script.args).toEqual(["runserver"]);
expect(extra(script)).toMatchObject({ python: "/p/.venv/bin/python", django: true, console: "internalConsole" });
expect(extra(script)).toMatchObject({ python: "/p/.venv/bin/python", django: true, console: "integratedTerminal" });
const mod = launchConfigFor(
rc({ kind: "python", command: "python3", args: ["-m", "app", "-v"], debugAdapter: "debugpy" }),
+37
Переглянути файл
@@ -71,6 +71,7 @@ import { setLocale } from "@/platform/i18n";
import { ToolWindowShownProvider } from "@/workbench/contributions";
import { handleDebugEvent, setVariableValue, useDebug, type DebugSession } from "../state";
import { DebugTabs, DebugToolWindow } from "../ui/DebugToolWindow";
import { hideContextMenu, useContextMenuStore } from "@/ui/Menu";
import { DebuggerOverlays } from "../ui/Overlays";
import { useOverlays } from "../ui/popoverStore";
@@ -157,6 +158,16 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: "Memory" })).toBeTruthy();
});
it("shows the Memory tab of a JVM session while it starts, before its capabilities arrive", () => {
const starting = { ...session, adapter: "java-debug", status: "starting" as const, caps: null };
useDebug.setState({ sessions: { 1: starting }, active: 1 });
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Memory" }));
expect(screen.getByText("The Memory view is available once the program has started.")).toBeTruthy();
act(() => useDebug.setState({ sessions: { 1: { ...starting, adapter: "debugpy" } } }));
expect(screen.queryByRole("tab", { name: "Memory" })).toBeNull();
});
it("keeps the Memory tab selected when the session pauses", async () => {
const caps = { jvmMemory: true } as DebugSession["caps"];
useDebug.setState({ sessions: { 1: { ...session, caps, status: "running" } }, active: 1 });
@@ -230,6 +241,32 @@ describe("debug tool window", () => {
expect(console.getAttribute("aria-selected")).toBe("true");
});
it("keeps the chosen tab on a breakpoint hit when Focus On Breakpoint is off", () => {
const settings = useProject.getState().settings;
useDebug.setState({ sessions: { 1: { ...session, status: "running" } }, active: 1 });
render(<DebugToolWindow />);
const variables = screen.getByRole("tab", { name: "Threads & Variables" });
fireEvent.contextMenu(variables);
const item = useContextMenuStore.getState().menu?.items[0];
expect(item).toMatchObject({ label: "Focus On Breakpoint", checked: true });
act(() => hideContextMenu());
try {
act(() =>
useProject.setState({
settings: { debugger: { variablesOnBreakpoint: false } } as ReturnType<
typeof useProject.getState
>["settings"],
}),
);
const console = screen.getByRole("tab", { name: "Console" });
fireEvent.click(console);
act(() => useDebug.setState({ sessions: { 1: session } }));
expect(console.getAttribute("aria-selected")).toBe("true");
} finally {
act(() => useProject.setState({ settings }));
}
});
it("opens on Console for a running session, and on the view last picked when shown again", () => {
useDebug.setState({ sessions: { 1: { ...session, status: "running" } }, active: 1 });
const first = render(<DebugToolWindow />);
+10 -5
Переглянути файл
@@ -67,7 +67,12 @@ function cargoLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
return {
...base(rc, adapter, cwd),
args: programArgs,
extraJson: JSON.stringify({ cargo: filter ? { args, filter } : { args }, sourceLanguages: ["rust"] }),
extraJson: JSON.stringify({
cargo: filter ? { args, filter } : { args },
...(adapter === "codelldb" ? { sourceLanguages: ["rust"] } : {}),
// lldb-dap takes the environment as `KEY=VALUE` strings.
...(adapter === "lldb-dap" ? { env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`) } : {}),
}),
};
}
@@ -95,10 +100,11 @@ function debugpyLaunch(rc: RunConfig, cwd: string): LaunchConfig {
const dbg = workflowSettings().debugger;
const extra: Record<string, unknown> = {
python: pythonFor(rc, cwd),
console: "internalConsole",
// On a terminal the program reads what is typed in the debug console (`input()`); its
// output reaches the console from there, so debugpy doesn't capture it a second time.
console: "integratedTerminal",
justMyCode: dbg.skipLibraryCode,
subProcess: dbg.python.attachSubprocess,
redirectOutput: true,
};
if (dbg.python.gevent) extra.gevent = true;
const name = (rc.command.split("/").pop() ?? rc.command).replace(/\.exe$/, "");
@@ -181,8 +187,7 @@ function jsDebugLaunch(rc: RunConfig, cwd: string): LaunchConfig {
const out = base(rc, "js-debug", cwd);
const extra: Record<string, unknown> = {
type: "pwa-node",
console: "internalConsole",
outputCapture: "std",
console: "integratedTerminal",
skipFiles: workflowSettings().debugger.skipLibraryCode ? ["<node_internals>/**", "**/node_modules/**"] : [],
autoAttachChildProcesses: true,
};
+45 -6
Переглянути файл
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
import { call, commands, type Scope, type Variable } from "@/platform/ipc";
import { call, commands, isTauri, type Scope, type Variable } from "@/platform/ipc";
import {
EmptyState,
Icon,
@@ -109,6 +109,14 @@ type Tab = "variables" | "console" | "memory" | "network";
/** The view the user last picked; the tool window opens on it again (Console until one is picked). */
let chosenTab: Tab = "console";
/** Threads & Variables › Focus On Breakpoint: whether a breakpoint hit selects that tab. */
async function setVariablesOnBreakpoint(on: boolean) {
if (!isTauri()) return;
useProject.setState({
settings: await call(commands.settingsSet("global", "debugger.variablesOnBreakpoint", JSON.stringify(on))),
});
}
function statusText(s: DebugSession): string {
if (s.status === "terminated") return s.exitCode != null ? `Finished · exit code ${s.exitCode}` : "Finished";
if (s.status === "starting") return "Starting…";
@@ -160,16 +168,22 @@ export function DebugToolWindow() {
setView({
session: active.startedAt,
status: active.status,
// A breakpoint or exception brings Threads & Variables to the front; finishing a step keeps
// the tab the user is on (e.g. Console, to watch the output while stepping), and so does Memory.
// A breakpoint or exception brings Threads & Variables to the front unless its Focus On Breakpoint
// is off; finishing a step keeps the tab the user is on (e.g. Console, to watch the output while
// stepping), and so does Memory.
tab:
active.status === "starting"
? "console"
: active.status === "paused" && view.tab !== "memory" && active.stopReason !== "step"
: active.status === "paused" &&
view.tab !== "memory" &&
active.stopReason !== "step" &&
workflowSettings().debugger.variablesOnBreakpoint
? "variables"
: view.tab,
});
const hasMemory = !!active && sessionSupports("jvmMemory", active);
// A JVM session shows the Memory tab from the start, before the debugger has reported what it supports.
const memoryPending = !!active && !active.caps && JVM_ADAPTERS.has(rootOf(active).adapter);
const hasMemory = !!active && (sessionSupports("jvmMemory", active) || memoryPending);
const hasNetwork = !!active && sessionSupports("jsPage", active);
// The selected session may be one without the Memory or the Network tab.
const tab: Tab =
@@ -245,6 +259,20 @@ export function DebugToolWindow() {
chosenTab = id;
setView({ session: active.startedAt, status: active.status, tab: id });
}}
onContextMenu={
id === "variables"
? (e) => {
e.preventDefault();
showContextMenu(e, [
{
label: "Focus On Breakpoint",
checked: workflowSettings().debugger.variablesOnBreakpoint,
run: () => void setVariablesOnBreakpoint(!workflowSettings().debugger.variablesOnBreakpoint),
},
]);
}
: undefined
}
>
{tx(label)}
</button>
@@ -255,7 +283,15 @@ export function DebugToolWindow() {
{tab === "variables" ? (
<ThreadsAndVariables session={active} />
) : tab === "memory" ? (
<MemoryView key={active.id} session={active} />
memoryPending ? (
<div className={styles.emptyWrap}>
<EmptyState title="Memory">
<T>The Memory view is available once the program has started.</T>
</EmptyState>
</div>
) : (
<MemoryView key={active.id} session={active} />
)
) : tab === "network" ? (
<NetworkView key={active.id} session={active.id} />
) : (
@@ -266,6 +302,9 @@ export function DebugToolWindow() {
);
}
/** Debug adapters whose sessions have the Memory view (`ide-dap`'s `JVM_MEMORY_ADAPTERS`). */
const JVM_ADAPTERS = new Set(["java-debug", "kotlin-debug-adapter", "kotlin-lsp"]);
// --- threads & frames ----------------------------------------------------------
function ThreadsAndVariables({ session }: { session: DebugSession }) {
+3
Переглянути файл
@@ -401,6 +401,9 @@ describe("pull request helpers", () => {
"ssh://[email protected]/o/r.git",
"ssh://[email protected]:22/o/r.git",
"git://github.com/o/r",
// GitHub's SSH-over-HTTPS host.
"ssh://[email protected]:443/o/r.git",
"[email protected]:o/r.git",
])
expect(parseGitHubRemote(url), url).toEqual({ owner: "o", name: "r" });
expect(parseGitHubRemote("https://gitlab.com/o/r.git")).toBeNull();
+2 -2
Переглянути файл
@@ -413,10 +413,10 @@ export function repositoryDisplayName(
return showOwner ? `${repo.owner}/${repo.name}` : repo.name;
}
/** `owner/name` of a github.com remote URL (https, ssh or scp-like), else null. */
/** `owner/name` of a github.com remote URL (https, ssh or scp-like; SSH also via ssh.github.com), else null. */
export function parseGitHubRemote(url: string): GHRepositoryCoordinates | null {
const m =
/^(?:https?:\/\/(?:[^@/]+@)?|ssh:\/\/(?:[^@/]+@)?|git:\/\/|(?:[^@/]+@)?)(?:www\.)?github\.com(?::\d+(?=\/))?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(
/^(?:(?:https?:\/\/(?:[^@/]+@)?|git:\/\/)(?:www\.)?|(?:ssh:\/\/(?:[^@/]+@)?|(?:[^@/]+@)?)(?:www\.|ssh\.)?)github\.com(?::\d+(?=\/))?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(
url.trim(),
);
return m ? { owner: m[1]!, name: m[2]! } : null;
+9
Переглянути файл
@@ -207,3 +207,12 @@
.pendingMethod {
font-weight: 600;
}
.match {
border-radius: 2px;
color: var(--fg-search-match);
background: var(--bg-search-match);
}
.matchCurrent {
background: var(--bg-search-match-current);
}
+117 -11
Переглянути файл
@@ -3,7 +3,7 @@
* exchange (right): status line, timing, body (pretty-printed JSON / XML /
* HTML or raw), response headers and the request as sent.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { Fragment, useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import type { HttpExchange, HttpHistoryEntry } from "@/platform/ipc";
import {
@@ -18,6 +18,9 @@ import {
T,
useSelectionBoundary,
} from "@/ui";
import { ConsoleFindBar } from "@/ui/ConsoleFindBar";
import { DEFAULT_FIND_OPTIONS, findInLines, type ConsoleMatch, type FindOptions } from "@/ui/consoleFind";
import { formatBinding, hasPrimaryModifier, hostBinding } from "@/platform/keymap";
import { bodyKind, formatMs, formatSize, prettyBody } from "./format";
import { cancelRunning, clearHistory, refreshHistory, selectEntry, useHttpClient } from "./store";
import styles from "./HttpClient.module.css";
@@ -60,6 +63,49 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
const r = ex.response;
const kind = r?.body != null ? bodyKind(r.contentType, r.body) : "text";
const body = useMemo(() => (r?.body == null ? null : raw ? r.body : prettyBody(kind, r.body)), [r, raw, kind]);
const [findOpen, setFindOpen] = useState(false);
const [query, setQuery] = useState("");
const [findOptions, setFindOptions] = useState<FindOptions>(DEFAULT_FIND_OPTIONS);
const [active, setActive] = useState(0);
const findInput = useRef<HTMLInputElement>(null);
const searchable = findOpen && tab === "body" && body != null;
const lines = useMemo(() => (body ?? "").split("\n").map((text, id) => ({ id, text })), [body]);
const found = useMemo(
() => (searchable ? findInLines(lines, query, findOptions) : { matches: [], overflow: false, invalid: false }),
[searchable, lines, query, findOptions],
);
const activeIndex = found.matches.length ? Math.min(active, found.matches.length - 1) : -1;
useEffect(() => {
pane.current?.querySelector("[data-find-current]")?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [activeIndex, found]);
const openFind = () => {
setFindOpen(true);
// The bar mounts with this render; focus it (and select the query) once it has.
requestAnimationFrame(() => findInput.current?.select());
};
const closeFind = () => {
setFindOpen(false);
pane.current?.focus();
};
const goToMatch = (step: number) => {
const n = found.matches.length;
if (n) setActive((activeIndex + step + n) % n);
};
// ⌘F in the response, as in IDEA's response viewer: the find bar of the Run console.
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (
tab === "body" &&
body != null &&
e.key.toLowerCase() === "f" &&
hasPrimaryModifier(e) &&
!e.altKey &&
!e.shiftKey
) {
e.preventDefault();
e.stopPropagation();
openFind();
}
};
return (
<div className={styles.exchange}>
<div className={styles.statusLine}>
@@ -91,18 +137,52 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
{ id: "request", label: "Request" },
]}
trailing={
tab === "body" && kind !== "text" ? (
<IconButton
icon="soft-wrap"
title={raw ? "Show Formatted" : "Show Raw"}
pressed={raw}
onClick={() => setRaw((v) => !v)}
/>
tab === "body" && body != null ? (
<>
<IconButton
icon="search"
title="Find…"
shortcut={formatBinding(hostBinding("Meta+F"))}
pressed={findOpen}
onClick={() => (findOpen ? closeFind() : openFind())}
/>
{kind !== "text" && (
<IconButton
icon="soft-wrap"
title={raw ? "Show Formatted" : "Show Raw"}
pressed={raw}
onClick={() => setRaw((v) => !v)}
/>
)}
</>
) : undefined
}
/>
{searchable && (
<ConsoleFindBar
query={query}
onChange={(q) => {
setQuery(q);
setActive(0);
}}
options={findOptions}
onOptionsChange={(o) => {
setFindOptions(o);
setActive(0);
}}
count={found.matches.length}
active={activeIndex}
overflow={found.overflow}
invalid={found.invalid}
inputRef={findInput}
onNext={() => goToMatch(1)}
onPrevious={() => goToMatch(-1)}
onClose={closeFind}
label="Find in response"
/>
)}
{/* Focusable, so Select All and Copy work on the response like in a read-only editor. */}
<div ref={pane} className={styles.tabBody} tabIndex={0}>
<div ref={pane} className={styles.tabBody} tabIndex={0} onKeyDown={onKeyDown}>
{tab === "body" &&
(r == null ? (
<pre className={styles.pre}>{ex.entry.error}</pre>
@@ -112,7 +192,7 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
</EmptyState>
) : (
<pre className={styles.pre} aria-label={tx("Response body")}>
{body}
{found.matches.length ? highlighted(lines, found.matches, activeIndex) : body}
{r.truncated && (
<span className={styles.truncated}>{`\n… truncated (${formatSize(r.size)} received)`}</span>
)}
@@ -131,6 +211,32 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
);
}
/** The body with its find matches marked, the current one distinctly. */
function highlighted(lines: readonly { text: string }[], matches: readonly ConsoleMatch[], current: number): ReactNode {
const out: ReactNode[] = [];
let m = 0;
lines.forEach(({ text }, line) => {
if (line > 0) out.push("\n");
let at = 0;
for (; m < matches.length && matches[m]!.line === line; m++) {
const { start, end } = matches[m]!;
if (start > at) out.push(text.slice(at, start));
out.push(
<mark
key={m}
className={clsx(styles.match, m === current && styles.matchCurrent)}
data-find-current={m === current ? "" : undefined}
>
{text.slice(start, end)}
</mark>,
);
at = end;
}
if (at < text.length) out.push(text.slice(at));
});
return <Fragment>{out}</Fragment>;
}
function HeaderTable({ headers }: { headers: Array<[string, string]> }) {
return (
<table className={styles.headers}>
@@ -155,7 +261,7 @@ export function HttpClientView() {
void refreshHistory();
}, []);
return (
<SplitGroup orientation="horizontal" className={styles.root}>
<SplitGroup orientation="horizontal" className={styles.root} storageKey="openidea.httpClient.split">
<SplitPanel id="http-history" defaultSize="32%" minSize="160px">
<div className={styles.list} role="list" aria-label={tx("Response history")}>
{running && (
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { Text } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { fileReferenceAt } from "./fileNavigation";
const doc = Text.of([
"POST http://x/api",
"",
"< ./body.json",
"> handler.js",
"> {% client.test('ok', () => {}); %}",
">> out/result.json",
"<> 2026-11-10T135253.200.json",
]);
const at = (line: number, col: number) => fileReferenceAt(doc, doc.line(line).from + col);
describe("fileReferenceAt", () => {
it("finds the file a body, handler, redirect or saved-response line names", () => {
expect(at(3, 4)).toMatchObject({ value: "./body.json", response: false });
expect(at(4, 3)).toMatchObject({ value: "handler.js", response: false });
expect(at(6, 5)).toMatchObject({ value: "out/result.json", response: false });
expect(at(7, 10)).toMatchObject({ value: "2026-11-10T135253.200.json", response: true });
});
it("ignores inline handler scripts, the marker itself and other lines", () => {
expect(at(5, 6)).toBeNull();
expect(at(7, 0)).toBeNull();
expect(at(1, 6)).toBeNull();
});
});
+44
Переглянути файл
@@ -0,0 +1,44 @@
/**
* Navigate › Declaration (⌘-click, ⌘B) on the file a `.http` line names: a request body
* (`< ./body.json`), a response handler script (`> handler.js`), a response redirect
* (`>> out.json`) and a saved response (`<> 2026-11-10T135253.200.json`). Saved responses
* resolve against `.idea/httpRequests/`, where IntelliJ IDEA writes them, then against the
* request file's folder.
*/
import type { Text } from "@codemirror/state";
import { docOf } from "@/editor/lsp/lsp";
import { registerNavigationProvider } from "@/editor/navigationProviders";
import { call, commands } from "@/platform/ipc";
import { HTTP_LANGUAGE } from "./editor";
/** The file named on the line at `offset`, as document offsets; `response` for a `<>` line. */
export function fileReferenceAt(
doc: Text,
offset: number,
): { value: string; from: number; to: number; response: boolean } | null {
const line = doc.lineAt(offset);
const m = /^(\s*(<>|>>!?|<|>)\s+)(\S(?:.*\S)?)\s*$/.exec(line.text);
// `> {% … %}` is an inline handler script, not a file.
if (!m || m[3]!.startsWith("{%")) return null;
const from = line.from + m[1]!.length;
const to = from + m[3]!.length;
return offset >= from && offset <= to ? { value: m[3]!, from, to, response: m[2] === "<>" } : null;
}
export function registerFileNavigation(): () => void {
return registerNavigationProvider(async (view, offset) => {
const doc = docOf(view);
if (!doc || doc.virtual || doc.language !== HTTP_LANGUAGE) return null;
const at = fileReferenceAt(view.state.doc, offset);
if (!at) return null;
const candidates = at.response ? [`/.idea/httpRequests/${at.value}`, at.value] : [at.value];
for (const value of candidates) {
const path = await call(commands.fsResolveReference(doc.path, value)).catch(() => null);
if (path) {
const start = { line: 0, col: 0 };
return { from: at.from, to: at.to, targets: [{ path, range: { start, end: start } }] };
}
}
return { from: at.from, to: at.to, targets: [] };
});
}
+2
Переглянути файл
@@ -17,6 +17,7 @@ import {
registerServiceView,
showServiceView,
} from "@/workbench/contributions";
import { registerFileNavigation } from "./fileNavigation";
import { registerVariableNavigation } from "./variableNavigation";
import { HTTP_LANGUAGE, httpEditorExtension, refreshRequests, requestAtCaret } from "./editor";
import { HttpClientHeaderActions, HttpClientView } from "./HttpClientView";
@@ -134,6 +135,7 @@ export function activate(): () => void {
const disposers = [
registerSpringEndpointProvider(),
registerVariableNavigation(),
registerFileNavigation(),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) resetHttpClient();
}),
+67
Переглянути файл
@@ -0,0 +1,67 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { HttpExchange } from "@/platform/ipc";
vi.mock("./store", async (importOriginal) => ({
...(await importOriginal<typeof import("./store")>()),
refreshHistory: vi.fn(async () => {}),
}));
const { useHttpClient } = await import("./store");
const { HttpClientView } = await import("./HttpClientView");
const exchange: HttpExchange = {
entry: {
id: "e1",
timeMs: 0,
name: null,
method: "GET",
url: "http://x/api",
status: 200,
totalMs: 5,
file: null,
error: null,
},
request: { name: null, method: "GET", url: "http://x/api", headers: [], body: null },
response: {
status: 200,
statusText: "OK",
version: "HTTP/1.1",
headers: [["content-type", "text/plain"]],
contentType: "text/plain",
body: "alpha beta\nbeta gamma\nBeta",
size: 26,
truncated: false,
ttfbMs: 1,
totalMs: 5,
},
};
describe("HTTP response find", () => {
afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null }));
it("opens a find bar with ⌘F in the response and marks the matches", () => {
Element.prototype.scrollIntoView ??= () => {};
useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" });
render(<HttpClientView />);
const body = screen.getByLabelText("Response body");
fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true });
const input = screen.getByLabelText("Find in response", { selector: "input" });
act(() => {
fireEvent.change(input, { target: { value: "beta" } });
});
const marks = body.querySelectorAll("mark");
expect([...marks].map((m) => m.textContent)).toEqual(["beta", "beta", "Beta"]);
expect(screen.getByText("1/3")).toBeTruthy();
expect(body.textContent).toBe("alpha beta\nbeta gamma\nBeta");
fireEvent.keyDown(input, { key: "Enter" });
expect(screen.getByText("2/3")).toBeTruthy();
expect(
marks[1]!.hasAttribute("data-find-current") ||
body.querySelectorAll("mark")[1]!.hasAttribute("data-find-current"),
).toBe(true);
fireEvent.keyDown(input, { key: "Escape" });
expect(screen.queryByLabelText("Find in response", { selector: "input" })).toBeNull();
expect(body.querySelectorAll("mark")).toHaveLength(0);
});
});
+8 -1
Переглянути файл
@@ -56,10 +56,17 @@ it("puts a button on the marker's line that goes to its target", async () => {
expect(calls.navigate).toHaveBeenCalledWith(target);
});
it("hides markers on edit and when the entry goes away", async () => {
it("keeps markers on their lines while typing and hides them when the entry goes away", async () => {
setup();
await vi.waitFor(() => expect(button()).not.toBeNull());
// Typing must not empty the column: it would collapse and shift the text (#3370).
view!.dispatch({ changes: { from: source.indexOf("SELECT"), insert: "x" } });
expect(button()).not.toBeNull();
view!.dispatch({ changes: { from: 0, insert: "\n" } });
expect(button()).not.toBeNull();
// Deleting the marker's line drops it.
const line = view!.state.doc.line(3);
view!.dispatch({ changes: { from: line.from - 1, to: line.to } });
expect(button()).toBeNull();
usePluginMarkers.setState({ entries: new Map() });
await vi.waitFor(() => expect(button()).toBeNull());
+4 -2
Переглянути файл
@@ -1,7 +1,8 @@
/**
* Gutter markers from plugins' document indexers, resolved by the host from
* its cached graph. A click goes to the marker's targets (a chooser when there
* are several); an edit hides the markers until the edited text is indexed.
* are several); an edit keeps them on their lines until the edited text is indexed,
* so the column keeps its width while typing.
*/
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
@@ -52,7 +53,8 @@ const setMarkers = StateEffect.define<RangeSet<GutterMarker>>();
const markersField = StateField.define<RangeSet<GutterMarker>>({
create: () => RangeSet.empty,
update(value, tr) {
if (tr.docChanged) value = RangeSet.empty;
// Markers move with the text; a deleted line drops its own.
if (tr.docChanged) value = value.map(tr.changes);
for (const effect of tr.effects) if (effect.is(setMarkers)) value = effect.value;
return value;
},
+4 -2
Переглянути файл
@@ -66,7 +66,7 @@ import {
} from "@/platform/projectPresentation";
import { relativePath } from "@/platform/project";
import { folderKind } from "./folderKind";
import { PROJECT_TYPES } from "./projectType";
import { PROJECT_TYPES } from "@/platform/projectType";
import { useHomeDir } from "./home";
import { keyLike, memberNodes, nodeKeyFor, visibleInfo, type ProjectNode } from "./model";
import {
@@ -286,7 +286,9 @@ const Row = memo(function Row({
const root = useProjectTree((s) => s.root);
const detected = useDetectedRoots();
const build = useProjectPresentation();
const projectType = useProjectTree((s) => (node.root && !node.icon ? s.projectTypes.get(node.path) : undefined));
const projectType = useProjectTree((s) =>
s.members && node.root && !node.icon ? s.projectTypes.get(node.path) : undefined,
);
const file = useJvmPresentation(node.dir || node.placeholder ? "" : node.path, node.entry?.mtimeMs);
const expanded = useProjectTree((s) => node.dir && s.expanded.has(node.key));
const holdsOpen = useProjectTree((s) => node.dir && holdsOpenFile(node.path, s.openFiles));
+8 -2
Переглянути файл
@@ -3,7 +3,7 @@ import { executeAction, getAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
import { relativePath, useProject } from "@/platform/project";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { currentDetectedRoots, currentRoots } from "@/platform/projectRoots";
import type { MenuItem } from "@/ui";
import { menuGroupItems, toolWindowService, type MenuGroupContext } from "@/workbench/contributions";
@@ -31,6 +31,7 @@ import {
vcsArg,
} from "./operations";
import { isSameOrInside } from "./paths";
import { useProjectTree } from "./store";
import { tx } from "@/platform/i18n";
/** Keys handled by the project view itself (the default keymap has no entries for them). */
@@ -105,7 +106,12 @@ function showProjectView() {
/** File kinds contributed to the `new` menu group (templates, HTTP Request, Scratch File…). */
function contributedNewItems(parent: string | null): MenuItem[] {
const items = menuGroupItems("new", parent ? { paths: [parent], dirs: [true] } : { paths: [] });
const owner = parent ? projectFolder(useProject.getState().project, parent) : null;
const projectType =
parent && owner && isSameOrInside(parent, owner.root)
? useProjectTree.getState().projectTypes.get(owner.root)
: undefined;
const items = menuGroupItems("new", parent ? { paths: [parent], dirs: [true], projectType } : { paths: [] });
return items.length ? [{ kind: "separator" }, ...items] : [];
}
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { hasIcon } from "@/ui/icons";
import { detectProjectType, isProjectMarker, PROJECT_TYPES } from "./projectType";
import { detectProjectType, isProjectMarker, PROJECT_TYPES } from "@/platform/projectType";
describe("project types", () => {
it.each([
+3 -4
Переглянути файл
@@ -45,11 +45,10 @@ describe("automatic project types", () => {
expect([...useProjectTree.getState().projectTypes.values()]).toEqual(Array(9).fill("go"));
expect(backend.fsReadDir).toHaveBeenCalledTimes(9);
});
it("leaves a single project root alone", async () => {
it("detects the type for New menu templates in a single project", async () => {
initProjectTree("/app");
await new Promise((resolve) => setTimeout(resolve, 20));
expect(backend.fsReadDir).not.toHaveBeenCalled();
expect(useProjectTree.getState().projectTypes.size).toBe(0);
await waitFor(() => expect(useProjectTree.getState().projectTypes.get("/app")).toBe("node"));
expect(backend.fsReadDir).toHaveBeenCalledExactlyOnceWith("/app");
});
it("refreshes only affected markers and clears a removed project type", async () => {
initProjectTree("/ws", "Workspace", ["/a", "/b"]);
+5 -4
Переглянути файл
@@ -1,6 +1,6 @@
/** Bounded, read-only detection for workspace members, collapsed ones included; a single project root keeps its own icon. */
/** Bounded, read-only detection for project roots, including collapsed workspace members. */
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { detectProjectType, isProjectMarker } from "./projectType";
import { detectProjectType, isProjectMarker } from "@/platform/projectType";
import { useProjectTree } from "./store";
async function detect(root: string) {
@@ -16,8 +16,9 @@ export function initProjectTypes(): () => void {
let reset: (() => void) | undefined;
const load = () => {
reset?.();
const { root, members: roots } = useProjectTree.getState();
if (!root || !roots || !isTauri()) return;
const { root, members } = useProjectTree.getState();
if (!root || !isTauri()) return;
const roots = members ?? [root];
const pending = new Set(roots);
const versions = new Map<string, number>();
let active = 0;
+1 -1
Переглянути файл
@@ -36,7 +36,7 @@ import {
type TreeOptions,
} from "./model";
import { projectFs } from "./fs";
import { PROJECT_TYPES, type ProjectType } from "./projectType";
import { PROJECT_TYPES, type ProjectType } from "@/platform/projectType";
import {
projectViewRoots,
useProjectViewRoots,
+17 -2
Переглянути файл
@@ -6,13 +6,15 @@ import { registerEditorContribution } from "@/editor/api";
import { executeAction, executeActionOrThrow, getAction, registerActions } from "@/platform/actions";
import { getContext, setContext, useContextKeys } from "@/platform/context";
import { call, commands, onIdeEvent, type RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { projectFolder, useProject } from "@/platform/project";
import { isSameOrInside } from "@/platform/paths";
import { agentRunSettings, onWorkflowSettingsChange } from "@/platform/workflowSettings";
import { showContextMenu, lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import {
menuGroupItems,
useDebugRunSessions,
notifications,
provideRunConfigurationLookup,
provideRunOutput,
registerMenuGroup,
registerOverlay,
@@ -44,6 +46,7 @@ import { invalidateGoModules } from "./goModules";
import { invalidatePythonPackages } from "./pythonPackages";
import { RunWidget } from "./RunWidget";
import { runConfigsRunAnything } from "./runAnything";
import { runDirectory } from "./navigate";
import {
cleanupRemovedProject,
registerRunServiceActions,
@@ -348,7 +351,7 @@ function useRunningCount(): number | null {
}
const CONFIG_FILES =
/(?:^|\/)(?:\.openidea\/run\.toml|package\.json|deno\.jsonc?|Cargo\.toml|build\.gradle(?:\.kts)?|pom\.xml|go\.(?:mod|work)|pyproject\.toml|setup\.cfg|pytest\.ini|manage\.py|Makefile|justfile|CMakeLists\.txt|CMakeCache\.txt|index-[^/]+\.json)$/;
/(?:^|\/)(?:\.openidea\/run(?:\.local)?\.toml|package\.json|deno\.jsonc?|Cargo\.toml|build\.gradle(?:\.kts)?|pom\.xml|go\.(?:mod|work)|pyproject\.toml|setup\.cfg|pytest\.ini|manage\.py|Makefile|justfile|CMakeLists\.txt|CMakeCache\.txt|index-[^/]+\.json)$/;
let reloadTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleReload() {
@@ -765,6 +768,18 @@ export function activate(): () => void {
disposers.push(() => setBeforeLaunchRunner(null));
provideRunOutput({ subscribe: subscribeOutput });
disposers.push(() => provideRunOutput(undefined));
provideRunConfigurationLookup((kind, directory) => {
const { project } = useProject.getState();
if (!project?.trusted) return false;
const owner = projectFolder(project, directory);
if (!owner || !isSameOrInside(directory, owner.root)) return false;
return useRun.getState().configs.some((config) => {
if (config.kind !== kind) return false;
const path = runDirectory(config.module ?? config.cwd);
return isSameOrInside(path, owner.root) && projectFolder(project, path)?.root === owner.root;
});
});
disposers.push(() => provideRunConfigurationLookup(undefined));
if (hasProject()) void loadConfigs();
// Reload when run.toml or build files change on disk (cheap; detection is fast).
+1 -1
Переглянути файл
@@ -1132,7 +1132,7 @@ function elementProduction(input: ContextInput, env: ToolEnv, target: RunTarget)
}
if (/\.zig$/.test(input.path)) {
// `--test-filter` matches a substring of the test's full name.
return zigFile(input, env, s, { name: target.name, filter: target.name.replace(/\\(.)/g, "$1") });
return zigFile(input, env, s, { name: target.name, filter: target.name });
}
const rust = /\.rs$/.test(input.path);
if (rust && !(s.inProject && cargoOwner(rel, input.configs).length)) {
+2 -2
Переглянути файл
@@ -131,8 +131,8 @@ function showTargetMenu(view: EditorView, target: RunTarget, path: string, at: {
showContextMenu(at, targetMenuItems(target, path, view.state.doc.toString()));
}
/** Results of frameworks that root their test tree at the file (jest/vitest, pytest) also match by file. */
const fileRootedResults = (path: string) => /\.(py|[cm]?[jt]sx?)$/.test(path);
/** Results of frameworks that root their test tree at the file (jest/vitest, pytest, Zig's module) also match by file. */
const fileRootedResults = (path: string) => /\.(py|[cm]?[jt]sx?|zig)$/.test(path);
/** Last test result of a gutter target (IDEA: green / red run icons after a test run). */
export function gutterTestState(target: RunTarget, path: string): TestState | null {
+2 -1
Переглянути файл
@@ -361,7 +361,8 @@ export function zigTargets(content: string): RunTarget[] {
if (/^pub\s+fn\s+main\s*\(/.test(line)) out.push({ line: i, kind: "main", name: "main", path: [] });
const test = /^\s*test\s+(?:"((?:[^"\\]|\\.)*)"|([A-Za-z_]\w*))\s*\{/.exec(line);
if (test) {
const name = test[1] ?? test[2]!;
// Unescape for display and for `--test-filter`: the runner reports the raw name.
const name = test[1]?.replace(/\\(.)/g, "$1") ?? test[2]!;
out.push({ line: i, kind: "test", name, path: [name] });
}
});
+32 -2
Переглянути файл
@@ -8,12 +8,23 @@ import { phpunitParser, withTeamcity } from "./phpunit";
import { pytestParser } from "./pytest";
import { rubyParser } from "./ruby";
import { unittestParser } from "./unittest";
import { zigParser } from "./zig";
import type { TestEvent, TestOutputParser } from "./types";
export type { TestEvent, TestOutputParser, TestStatus } from "./types";
export { parseDuration } from "./types";
export { TestResults, nodeOutput, nodeStatus, type TestNode } from "./results";
export { cargoParser, goParser, jsParser, jvmParser, phpunitParser, pytestParser, rubyParser, unittestParser };
export {
cargoParser,
goParser,
jsParser,
jvmParser,
phpunitParser,
pytestParser,
rubyParser,
unittestParser,
zigParser,
};
/** Runs several parsers side by side (unknown tool: e.g. `make test`). */
export function combinedParser(parsers: TestOutputParser[]): TestOutputParser {
@@ -23,7 +34,18 @@ export function combinedParser(parsers: TestOutputParser[]): TestOutputParser {
};
}
export type Framework = "cargo" | "js" | "pytest" | "unittest" | "phpunit" | "go" | "jvm" | "ruby" | "dotnet" | "auto";
export type Framework =
| "cargo"
| "js"
| "pytest"
| "unittest"
| "phpunit"
| "go"
| "jvm"
| "ruby"
| "dotnet"
| "zig"
| "auto";
export function frameworkFor(config: Pick<RunConfig, "kind" | "command" | "args">): Framework {
const cmd = [config.command, ...config.args].join(" ");
@@ -54,6 +76,8 @@ export function frameworkFor(config: Pick<RunConfig, "kind" | "command" | "args"
case "rake":
case "rspec":
return "ruby";
case "zig":
return "zig";
}
if (/(^|[/\\])dotnet(?:\.exe)?$/i.test(config.command) && config.args[0] === "test") return "dotnet";
if (/\bcargo\b/.test(cmd)) return "cargo";
@@ -98,6 +122,10 @@ export function withTestReporting<T extends Pick<RunConfig, "kind" | "command" |
};
}
if (frameworkFor(config) === "phpunit") return { ...config, args: withTeamcity(config.args) };
if (frameworkFor(config) === "zig" && config.args[0] === "build") {
// `zig build test` prints nothing for a passing (or cached) run; the summary reports the counts.
return config.args.includes("--summary") ? config : { ...config, args: [...config.args, "--summary", "all"] };
}
if (frameworkFor(config) === "unittest") {
const chosen = config.args.some((a) => /^(-v|--verbosity)(=?\d)?$/.test(a));
return chosen ? config : { ...config, args: [...config.args, "-v", "2"] };
@@ -131,6 +159,8 @@ export function createTestParser(config: Pick<RunConfig, "kind" | "command" | "a
return jvmParser();
case "ruby":
return rubyParser();
case "zig":
return zigParser();
default:
return combinedParser([
cargoParser(),
+17
Переглянути файл
@@ -180,6 +180,23 @@ describe("rerunFailedConfig", () => {
).toEqual(["test", "-Dtest=com.a.FooTest#bar+baz,com.a.BarTest"]);
});
it("zig: --test-filter per failed test for `zig test`, null for build-based runs", async () => {
expect(
(await rerunFailedConfig(cfg("zig", "zig", ["test", "src/calc.zig"]), [
["calc", "adds"],
["calc", "subs"],
]))!.args,
).toEqual(["test", "src/calc.zig", "--test-filter", "adds", "--test-filter", "subs"]);
// Existing filters are replaced, not stacked.
expect(
(await rerunFailedConfig(cfg("zig", "zig", ["test", "src/calc.zig", "--test-filter", "adds"]), [
["calc", "subs"],
]))!.args,
).toEqual(["test", "src/calc.zig", "--test-filter", "subs"]);
// `zig build` forwards no args to the test binary, so a build-based run can't narrow.
expect(await rerunFailedConfig(cfg("zig", "zig", ["build", "test"]), [["tally", "subs"]])).toBeNull();
});
it("returns null when nothing failed or the framework is unknown", async () => {
expect(await rerunFailedConfig(cfg("cargo", "cargo", ["test"]), [])).toBeNull();
expect(await rerunFailedConfig(cfg("make", "make", ["test"]), [["x"]])).toBeNull();
+15
Переглянути файл
@@ -249,6 +249,21 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
case "go":
args = goArgs(config.args, paths, config.params?.scope === "file" ? config.params.target : undefined);
break;
case "zig": {
// Only a standalone `zig test <file>` can filter: `zig build` forwards no args to the test binary.
const file = config.args[0] === "test" ? config.args[1] : undefined;
const names = unique(paths.map((p) => p[p.length - 1]!).filter(Boolean));
args =
file && names.length
? [
config.args[0]!,
file,
...dropFlag(config.args.slice(2), ["--test-filter"]),
...names.flatMap((n) => ["--test-filter", n]),
]
: null;
break;
}
case "jvm":
args = jvmArgs(config, paths);
break;
+13
Переглянути файл
@@ -58,6 +58,19 @@ describe("test states for the run gutter", () => {
expect(testState({ path: ["QTests", "test_a"], file: "/work/app/città/tests.py" })).toBe("passed");
});
it("matches Zig results rooted at the module stem of the file", () => {
run([
{ type: "result", path: ["tally", "adds"], status: "passed" },
{ type: "result", path: ["tally", "subs"], status: "failed" },
{ type: "result", path: ["other", "adds"], status: "failed" },
]);
expect(testState({ path: ["adds"], file: "src/tally.zig" })).toBe("passed");
expect(testState({ path: ["subs"], file: "/work/app/src/tally.zig" })).toBe("failed");
// Same-named tests of another module don't bleed over.
expect(testState({ path: ["adds"], file: "src/other.zig" })).toBe("failed");
expect(testState({ path: ["adds"], file: "src/tally/main.zig" })).toBeNull();
});
it("newer runs win and listeners hear about changes", () => {
const listener = vi.fn();
const off = onTestStatesChanged(listener);
+4
Переглянути файл
@@ -69,6 +69,8 @@ function segmentMatches(result: string, target: string): boolean {
const cleanPath = (p: string) => p.replace(/\\/g, "/").replace(/^\.\//, "");
const stemOf = (p: string) => p.replace(/.*\//, "").replace(/\.[^.]+$/, "");
function sameFile(resultRoot: string, relPath: string): boolean {
const b = cleanPath(relPath);
// unittest / Django results are rooted at the dotted module (`polls.tests`).
@@ -80,6 +82,8 @@ function sameFile(resultRoot: string, relPath: string): boolean {
const module = resultRoot.replace(/\./g, "/");
return [`${module}.py`, `${module}/__init__.py`].some((f) => b === f || b.endsWith(`/${f}`));
}
// Zig results are rooted at the module stem (`tally` for `src/tally.zig`).
if (/^[\p{L}_][\p{L}\p{N}_]*$/u.test(resultRoot) && stemOf(b) === resultRoot) return true;
const a = cleanPath(resultRoot);
return a === b || b.endsWith(`/${a}`) || a.endsWith(`/${b}`);
}
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more