feat(plugins): expose database table menus and read-only schema (#7372)

Plugin API 1.20 adds wit/database.wit with describe-table behind the database.schema capability: a read-only view of a connected source's table (columns, keys, indexes) through DbManager::connected_table_details. Plugins can contribute database.table.context menu entries (needs_api 20) that receive the non-secret table identity and the when keys databaseDriver, databaseObjectKind, databaseSchema, databaseTable and databaseSelectionCount.

Co-authored-by: gejun123456 <[email protected]>
Цей коміт міститься в:
葛俊таgejun123456 authored and GitHub committed 2026-12-02 14:25:35 +08:00
1 джерело abc5b2b2c6
коміт b7c2d4eacb
201 files changed
+1180 -176

No files matched your search

+19
Переглянути файл
@@ -1355,6 +1355,25 @@ impl DbManager {
Self::table_details_on(&pool, Some(catalog), schema, table).await
}
/// Read metadata using an existing connection only. A concurrent disconnect must not
/// cause a read-only extension request to reopen a source or prompt for credentials.
pub async fn connected_table_details(
&self,
id: &str,
catalog: Option<&str>,
schema: &str,
table: &str,
) -> IdeResult<TableDetails> {
if catalog.is_some() {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
}
}
let pool = self.connected_pool(id)?;
Self::table_details_on(&pool, catalog, schema, table).await
}
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
let pool = self.pool(id).await?;
Self::table_details_on(&pool, None, schema, table).await
+11
Переглянути файл
@@ -165,6 +165,17 @@ impl DbManager {
.collect()
}
/// Snapshot an existing connection without allocating a slot or opening a route.
pub(super) fn connected_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
self.pools
.lock()
.get(id)
.and_then(|slot| slot.value.get())
.filter(|connection| !connection.is_closed())
.map(|connection| connection.pool.clone())
.ok_or_else(|| IdeError::invalid("Connect the data source in the Database tool window first"))
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
+23
Переглянути файл
@@ -24,6 +24,8 @@ pub enum Capability {
IdeCommands,
/// Manage only its own project database sources and write their credentials.
DatabaseSources,
/// Read table metadata of connected project sources; never rows or credentials.
DatabaseSchema,
VcsRead,
VcsWrite,
/// The Maven / Gradle dependency graph the IDE resolved.
@@ -93,6 +95,7 @@ impl Capability {
}
Self::EditorWrite
| Self::DatabaseSources
| Self::DatabaseSchema
| Self::VcsWrite
| Self::Net(_)
| Self::NetAsk
@@ -130,6 +133,7 @@ impl Capability {
Self::EditorWrite => "Change text in the editor".into(),
Self::ProjectWrite => "Create and change files in the open project".into(),
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
Self::VcsRead => "Read version control state".into(),
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
@@ -289,6 +293,7 @@ impl fmt::Display for Capability {
Self::ProjectWrite => f.write_str("project.write"),
Self::IdeCommands => f.write_str("ide.commands"),
Self::DatabaseSources => f.write_str("database.sources"),
Self::DatabaseSchema => f.write_str("database.schema"),
Self::VcsRead => f.write_str("vcs.read"),
Self::VcsWrite => f.write_str("vcs.write"),
Self::BuildRead => f.write_str("build.read"),
@@ -383,6 +388,7 @@ impl FromStr for Capability {
"project.write" => Self::ProjectWrite,
"ide.commands" => Self::IdeCommands,
"database.sources" => Self::DatabaseSources,
"database.schema" => Self::DatabaseSchema,
"vcs.read" => Self::VcsRead,
"vcs.write" => Self::VcsWrite,
"build.read" => Self::BuildRead,
@@ -677,6 +683,23 @@ mod net_setting_tests {
mod database_tests {
use super::*;
#[test]
fn database_schema_is_a_separate_medium_risk_grant_requiring_api20() {
let cap: Capability = "database.schema".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSchema);
assert_eq!(cap.to_string(), "database.schema");
assert_eq!(cap.risk(), Risk::Medium);
assert!(!cap.auto_migrates());
for other in [Capability::ProjectRead, Capability::DatabaseSources] {
assert!(!other.covers(&cap));
}
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
let text = format!(
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.schema']"
);
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
}
}
#[test]
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
let cap: Capability = "database.sources".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSources);
+4 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.19.0";
pub const ENGINE_VERSION: &str = "1.20.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
@@ -426,6 +426,9 @@ impl Manifest {
if matches!(cap, Capability::ClipboardRead) {
self.needs_api(&format!("capability `{cap}`"), 11)?;
}
if matches!(cap, Capability::DatabaseSchema) {
self.needs_api(&format!("capability `{cap}`"), 20)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
+25
Переглянути файл
@@ -1746,6 +1746,31 @@ impl PluginApi {
}
impl HostApi for PluginApi {
fn database_table_schema(
&self,
root: &Path,
client: Option<&str>,
table: &ide_plugin::PluginDatabaseTableRef,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
self.require_api("database table schema", 20)?;
let (host, fallback) = self.database_host(root)?;
// Connections belong to windows, even when several windows open the same root.
// Prefer the invoking window; background calls may use any connected instance.
let db = client
.and_then(|client| host.project(client).ok())
.filter(|project| project.root == root)
.map(|project| project.db.clone())
.or_else(|| {
host.projects()
.into_iter()
.find(|project| project.root == root && project.db.is_connected(&table.source_id))
.map(|project| project.db.clone())
})
.unwrap_or(fallback);
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
}
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
let (host, db) = self.database_host(root)?;
let id = source.id.clone();
+64
Переглянути файл
@@ -189,6 +189,70 @@ pub(super) fn error(e: IdeError) -> HostError {
}
}
/// Schema inspection is deliberately separate from ownership/credential management.
pub(super) async fn table_schema(
db: &ide_db::DbManager,
table: &ide_plugin::PluginDatabaseTableRef,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
if table.source_id.is_empty()
|| table.table.is_empty()
|| [&table.source_id, &table.schema, &table.table]
.into_iter()
.chain(table.catalog.iter())
.any(|v| v.len() > 4096 || v.contains('\0'))
{
return Err(HostError::Invalid("invalid database table reference".into()));
}
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let read = db.connected_table_details(&table.source_id, table.catalog.as_deref(), &table.schema, &table.table);
let details = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(HostError::Cancelled),
result = tokio::time::timeout(timeout, read) => result
.map_err(|_| HostError::Failed("Database schema request timed out".into()))?.map_err(error)?,
};
if details.columns.is_empty() {
return Err(HostError::NotFound("table has no visible columns".into()));
}
if details.columns.len() > 4096 || details.indexes.len() > 4096 || details.foreign_keys.len() > 4096 {
return Err(HostError::Invalid("table schema exceeds 4096 columns, indexes or foreign keys".into()));
}
Ok(ide_plugin::PluginDatabaseTableSchema {
comment: details.comment,
columns: details
.columns
.into_iter()
.map(|c| ide_plugin::PluginDatabaseColumn {
name: c.name,
data_type: c.data_type,
nullable: c.nullable,
default_value: c.default,
primary_key: c.primary_key,
comment: c.comment,
})
.collect(),
indexes: details
.indexes
.into_iter()
.map(|i| ide_plugin::PluginDatabaseIndex { name: i.name, unique: i.unique, columns: i.columns })
.collect(),
foreign_keys: details
.foreign_keys
.into_iter()
.map(|f| ide_plugin::PluginDatabaseForeignKey {
columns: f.columns,
referenced_schema: f.ref_schema,
referenced_table: f.ref_table,
referenced_columns: f.ref_columns,
})
.collect(),
})
}
#[cfg(test)]
mod tests {
use super::*;
+21 -1
Переглянути файл
@@ -119,7 +119,9 @@ const COMMIT_MESSAGE_MENU: &str = "commit.message";
const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
/// The Open In › submenu of the editor, editor tab and project view menus: the command gets the file.
const OPEN_IN_MENU: &str = "openIn";
const MENU_IDS: [&str; 13] = [
/// Context menu of tables/views in the Database tool window (API 1.20).
const DATABASE_TABLE_MENU: &str = "database.table.context";
const MENU_IDS: [&str; 14] = [
"editor.context",
"projectView.context",
"editorTab.context",
@@ -133,6 +135,7 @@ const MENU_IDS: [&str; 13] = [
SERVICES_MENUS[0],
SERVICES_MENUS[1],
OPEN_IN_MENU,
DATABASE_TABLE_MENU,
];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
@@ -200,6 +203,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if SERVICES_MENUS.contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?;
}
if d.menu == DATABASE_TABLE_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {DATABASE_TABLE_MENU}"), 20)?;
}
if d.menu == OPEN_IN_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {OPEN_IN_MENU}"), 19)?;
}
@@ -1372,6 +1378,20 @@ pub(super) fn locales(pkg: &Package, _decl: toml::Value) -> Result<UiDecl, Strin
#[cfg(test)]
mod tests {
#[test]
fn database_table_menu_requires_api20_and_a_declared_command() {
use ide_extension::{Manifest, Package};
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
let source = format!(
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='generate'\ntitle='Generate Mapper'"
);
let pkg = Package::new(Manifest::parse(&source).unwrap(), std::path::PathBuf::from("/unused"));
let decl=toml::from_str("menu='database.table.context'\ncommand='generate'\nsubmenu='Generate'\nwhen='databaseObjectKind == table'").unwrap();
assert_eq!(super::menu(&pkg, decl).is_ok(), valid);
let undeclared = toml::from_str("menu='database.table.context'\ncommand='unknown'").unwrap();
assert!(super::menu(&pkg, undeclared).is_err());
}
}
use super::*;
#[test]
+68 -1
Переглянути файл
@@ -1,4 +1,4 @@
//! Database and MCP calls through a real sandboxed API 1.4 component.
//! Database and MCP calls through a real sandboxed component.
mod common;
use ide_core::{CancellationToken, IdeEvent, event::McpUiRequest};
@@ -355,3 +355,70 @@ fn eventually(mut ready: impl FnMut() -> bool) -> bool {
}
false
}
#[tokio::test(flavor = "multi_thread")]
async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grants() {
let f = Harness::with_timeout(Duration::from_secs(10));
let table =
serde_json::json!({"sourceId":"user-source","catalog":null,"schema":"main","table":"users"}).to_string();
assert!(f.run("table-schema", Some(&table)).is_err(), "untrusted projects are refused");
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let db = f.host.project("main").unwrap().db.clone();
db.save_sources(vec![ide_db::DataSource {
id: "user-source".into(),
name: "User-owned SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err(), "inspection never connects implicitly");
assert!(!db.is_connected("user-source"));
let cancel = CancellationToken::new();
for sql in [
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL DEFAULT 'guest', manager_id INTEGER REFERENCES users(id))",
"CREATE INDEX users_name ON users(name)",
"INSERT INTO users(name) VALUES ('private-row-value')",
] {
db.execute("user-source", sql, 100, &cancel).await.unwrap();
}
assert!(!f.host.project("second").unwrap().db.is_connected("user-source"));
assert!(
f.plugins
.run_command(
ID,
"table-schema",
Some(&table),
Invocation { client: Some("second".into()), ..f.invocation() }
)
.is_err(),
"a disconnected window cannot borrow another window's connection"
);
let response = f.run("table-schema", Some(&table)).unwrap().unwrap();
let schema: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(schema["columns"][0]["name"], "id");
assert_eq!(schema["columns"][0]["primaryKey"], true);
assert_eq!(schema["columns"][1]["nullable"], false);
assert_eq!(schema["columns"][1]["defaultValue"], "'guest'");
assert!(schema["indexes"].as_array().unwrap().iter().any(|i| i["name"] == "users_name"));
assert!(schema["foreignKeys"].as_array().unwrap().iter().any(|k| k["referencedTable"] == "users"));
let menu_argument = serde_json::json!({ "tables": [{
"sourceId": "user-source", "catalog": null, "schema": "main", "table": "users",
"kind": "table", "driver": "sqlite",
}] })
.to_string();
assert_eq!(f.run("table-schema", Some(&menu_argument)).unwrap().unwrap(), response);
assert!(!response.contains("private-row-value"));
assert!(schema.get("password").is_none() && schema.get("url").is_none() && schema.get("host").is_none());
f.plugins.set_capability(ID, "database.schema", false).unwrap();
let denied = f.run("table-schema", Some(&table)).unwrap_err();
assert!(denied.message.contains("database.schema"));
assert!(db.is_connected("user-source"), "revoking inspection leaves user connections alone");
f.plugins.set_capability(ID, "database.schema", true).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err());
db.disconnect("user-source").await;
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
}
+12 -1
Переглянути файл
@@ -64,7 +64,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
use views_bindings::openidea::plugin::view_types as wit_vt;
/// The API version of the world above, `major.minor` of [`host_api`].
pub const API_VERSION: &str = "1.19";
pub const API_VERSION: &str = "1.20";
const EPOCH_TICK: Duration = Duration::from_millis(10);
pub(crate) const MAX_TEXT: usize = 1 << 20;
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
@@ -87,6 +87,17 @@ pub enum SettingsTarget {
}
pub trait HostApi: Send + Sync {
/// Read only the schema of a connected project table; database.schema was checked.
fn database_table_schema(
&self,
_root: &Path,
_client: Option<&str>,
_table: &crate::PluginDatabaseTableRef,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<crate::PluginDatabaseTableSchema, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Creates/replaces this plugin's non-secret project connection settings.
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
/// Removes only an owned data source and its credentials.
+44
Переглянути файл
@@ -1166,3 +1166,47 @@ pub struct RunConfigCompletion {
pub replace_start: u32,
pub replace_end: u32,
}
/// Identifies a table in an already connected project data source (API 1.20).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseTableRef {
pub source_id: String,
pub catalog: Option<String>,
pub schema: String,
pub table: String,
}
/// Read-only column metadata. No row values or connection settings.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseColumn {
pub name: String,
pub data_type: String,
pub nullable: bool,
pub default_value: Option<String>,
pub primary_key: bool,
pub comment: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseIndex {
pub name: String,
pub unique: bool,
pub columns: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseForeignKey {
pub columns: Vec<String>,
pub referenced_schema: String,
pub referenced_table: String,
pub referenced_columns: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseTableSchema {
pub comment: Option<String>,
pub columns: Vec<PluginDatabaseColumn>,
pub indexes: Vec<PluginDatabaseIndex>,
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
}
+54
Переглянути файл
@@ -3282,6 +3282,60 @@ pub(crate) mod injections_bindings {
}
impl bindings::openidea::plugin::database::Host for StoreData {
fn describe_table(
&mut self,
project: Resource<ProjectRes>,
table: bindings::openidea::plugin::database::TableRef,
) -> Fallible<bindings::openidea::plugin::database::TableSchema> {
if let Err(e) = self.require(Capability::DatabaseSchema) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let table = crate::PluginDatabaseTableRef {
source_id: table.source_id,
catalog: table.catalog,
schema: table.schema,
table: table.table,
};
let result =
self.host.database_table_schema(&root, self.client(), &table, &self.cancel.token(), self.io_timeout());
if result.is_err() {
self.grant_io_error_grace();
}
use bindings::openidea::plugin::database as db;
Ok(result
.map(|s| db::TableSchema {
comment: s.comment,
columns: s
.columns
.into_iter()
.map(|c| db::ColumnSchema {
name: c.name,
data_type: c.data_type,
nullable: c.nullable,
default_value: c.default_value,
primary_key: c.primary_key,
comment: c.comment,
})
.collect(),
indexes: s
.indexes
.into_iter()
.map(|i| db::IndexSchema { name: i.name, unique: i.unique, columns: i.columns })
.collect(),
foreign_keys: s
.foreign_keys
.into_iter()
.map(|f| db::ForeignKeySchema {
columns: f.columns,
referenced_schema: f.referenced_schema,
referenced_table: f.referenced_table,
referenced_columns: f.referenced_columns,
})
.collect(),
})
.map_err(to_wit))
}
fn upsert_source(
&mut self,
project: Resource<ProjectRes>,
+5 -4
Переглянути файл
@@ -98,7 +98,7 @@ fn the_sdk_carries_the_hosts_wit() {
#[test]
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
let host = v("1.19.0");
let host = v("1.20.0");
for ok in [
"1.0.0",
"1.3.0",
@@ -118,15 +118,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
"1.17.0",
"1.18.0",
"1.19.0",
"1.20.0",
"1.0.0-rc.1",
] {
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
}
let newer = check_api(&v("1.20.0"), &host).unwrap_err();
assert!(newer.contains("1.20") && newer.contains("update OpenIDEA"), "{newer}");
let newer = check_api(&v("1.21.0"), &host).unwrap_err();
assert!(newer.contains("1.21") && newer.contains("update OpenIDEA"), "{newer}");
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
let older = check_api(&v("0.2.0"), &host).unwrap_err();
assert!(older.contains("rebuild it with the 1.19 SDK"), "{older}");
assert!(older.contains("rebuild it with the 1.20 SDK"), "{older}");
// 0.x: every minor is its own API.
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8da08e3230812e4f7cf875362c095ac4885c3262636e51b111e95f2fd962e08a
daf3ed46b1e98c6b416c0092a10a02579d2cf97959cedd03df1851a5e76d675d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9ebd066471e76d6261ab1b4b1e057a85bfdd9abb9f596149798d573336a6d1af
b54f16ce7e7caf877ea464b50014117fc10f30b761236e5ddcb19ad07254ea13
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cb058e76b7f4d12ea56b157481874f076fd7d549ae15b11cf914e9af56417331
56e088be4df2db66a03060d388890ff9b68c354e36851ad46665b26bd27ea817
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
58b531185ceaefbfcd78c62663717d0875aefc20b7f63bcd9cd2f412defbf9a9
eefdb2d5e0b1fcf96d3ba03e5494513577f43f877d675873d4b922ee71bd3cc5
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
89e515fce0e0cd4029a46c066a2b65592a22178ea77907c520beba447b6bb502
00c70c0584a32dacdaee29379b805815d17e6d9cb209e1c21d72fbfc18020498
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4e9714318c72fd137fb71234b00f48378256a7558328414aee1911f9eca640bf
e08f776a59706399eca922a324f21835208740a16c2e87911f0c338dd8e25cb2
+10 -2
Переглянути файл
@@ -1,12 +1,12 @@
id = "test.data-tools"
name = "Data tools fixture"
version = "0.1.0"
engines.openidea = "^1.4"
engines.openidea = "^1.20"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
[capabilities]
required = ["project.read"]
optional = ["database.sources"]
optional = ["database.sources", "database.schema"]
[[contributes.commands]]
id = "upsert"
@@ -66,3 +66,11 @@ description = "Fixture denied"
inputSchema = "arguments.json"
readOnly = true
destructive = false
[[contributes.commands]]
id = "table-schema"
title = "Read table schema"
[[contributes.menus]]
menu = "database.table.context"
command = "table-schema"
+10
Переглянути файл
@@ -14,6 +14,16 @@ impl Plugin for DataTools {
p.upsert_data_source(&source)?;
}
"remove" => p.remove_data_source(arg.unwrap_or("local"))?,
"table-schema" => {
let value: serde_json::Value = serde_json::from_str(arg.ok_or("table reference required")?)
.map_err(|e| Error::Invalid(e.to_string()))?;
// Accept both the table-menu selection and a direct reference for callers/tests.
let table =
serde_json::from_value(value.get("tables").and_then(|v| v.get(0)).unwrap_or(&value).clone())
.map_err(|e| Error::Invalid(e.to_string()))?;
let schema = p.database_table_schema(&table)?;
return Ok(Some(serde_json::to_string(&schema).unwrap()));
}
"sources" => return Ok(Some(serde_json::to_string(&p.data_sources()?).unwrap())),
"credential" => p.set_data_source_credential("local", arg.unwrap_or("secret"))?,
"connect" => p.connect_data_source(arg.unwrap_or("local"))?,
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
37f6ac9b07a333793798fd909fec9940fdffadd305a0ae1f15d50a918a6e738b
43bc34ad3aafd1d2869cf8f745dbaa0e8fce05ae6e39bf91ab39660cbcfc4740
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
46b9a5d0dd6670ae30c5c35909c02bc583e6ce4368aaa0df9aaaf917f141ccbe
b4d92a22c5ebadc47284a22be1de2beec6deeffcc2f60c55173b924322588844
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c029e8c5d44bd10bfc962747643033ad661406a4e71266060b83b479528ac62f
452aed5f05ac3cc3d299afd74427fd58c5934dec6ca5a239e2a1e347ba036044
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
df74de6fd1067530b30e32dc9955d2540cc11a84ab366c1d55286b1f666171d3
2abcea42de506e9e28a0970ba2a8615c7cc88d769cb5fa47fe3bb57e03af5258
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
010115b90cf7c62b304a419a85d2bf1e87a08cf8b71a22b83db7228c74fc879c
60e1a1925b3d83ea34be69727b9e8804ba3a1db767b7a06f87bcad6ab326a604
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4d64d801f5b861964a90907eb2d35fcfaac0fd5bba32f6fa739d419370ad34bb
92d626a131d5b8b82781a3cb7d87a293ddb0e5e81450bef17dc505c12f2a4f57
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
91dbf215e6388c1c4c8f09a8194d66888b0060bb44ee590b63a25aa3f8b1cdf8
86ec4a4ebc1d770b0e6973d9169544111fce24485f3eed8b7040d7dce8280dcd
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b83536a1c2620edaddc9712ebfcc284d83fd59054f17b4e10c99f3d55fe0a8bf
254dddbf9c67f00451fc173602532e2e4fe92a6fd8d3d91824c950a403c7583c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2af8aa827092f59d6faa02d4084f79a66bda9ef5211a1450542361702d04e7ae
49e66ff2b91e070477c272ac1c5c60367148b274d75bb7d92efca0b1d5092f6a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
93c276cf31b807543d700c2010a128741b269d897993882ff378061b1ed0b56d
cfb61fe65b344d86bf71a821c1216963d9ab7789206a292450b1d66222d6cbc5
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ed76d43bce1e0801aac9010ccbb6d6e5cb680283df6467961156d3ae7a6c3177
706e69379855967f598abbcc3bcc955cb5581ca4b009d5220f4785ccb05dda0f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c2c601d62f588a9618844e46e62998e26389a4eaaba1f3be90d0c70c6c19050a
118c6f4870e99d57acfc9fbb265031a3a7d1dfc03b4408be8c8b5eade33e4f38
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
10eeb474973e8dea250698a0322ce19705ec86beef29730500ebe611d3f796fa
19b04c02c5230c0700bdc8fe8a3cae266422aa23e8d7e932b7dafd546e41846d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3d65392e8a6723b33061b243deace1e6ede4d6d258c4c16719ed7533a2b1e3b1
14e46bbf68efaacaff75627814be666dcf00460656ba7e66b7fb088317ce6c79
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
33396b01be200316e5922b6db22e0bd498aad4c77a52254b24134c31c1f7a256
55afdbdb4db919c59a38b14eb6483c911934d64d433ef19106098bfde4830a91
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7a98500c653f18188570c91cadc4fc3c7e2bed2fcdd2ba8945a98bc13b7c5af4
99099a7f01295188bade661777d926fd12ba434ec4ff36035ee1b13523d63ae8
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7ac9e871f691e989cdef0d4ac3baf8fa338114ad906befd229a124e50897898d
ff6ecc3baa94d7cd4447f3d9f2a3f819ee44dac3564fdfba3a5f88a0637c0af0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e6bfa4a44f635fafd16103235424e40b8cd6849ed83f582af84fc9baac800882
45990bb70318e04cb69c8ffa5c980b85e65bd860559b10507061762f8ecb38b3
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7eccc42692e9d289e15fe131195ed67ebe9102f387cef02da19a581f37d729dc
cb21ced740ff159017a96075e41b31782c062db10596e4286327fb4d002b6ebf
+3 -3
Переглянути файл
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
inline: "
package fixture:misbehave;
world misbehave {
include openidea:plugin/plugin-syntax@1.19.0;
export openidea:plugin/providers@1.19.0;
export openidea:plugin/file-actions@1.19.0;
include openidea:plugin/plugin-syntax@1.20.0;
export openidea:plugin/providers@1.20.0;
export openidea:plugin/file-actions@1.20.0;
}
",
path: "../../../../../wit",
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a09c1f93e121b27d71bb6ac717a1222e240799f2bc0a6def8805ab4a62bed1a6
9bdc92f81b7985bec88bd2b3929771df22f1d31945e575a3a71ca705aad4d1dc
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8d34f0080002a1a68df23ba8fefb5cec34a986ca4610866f99007c6c62792ff5
3cbfd56bef0062d1fb25854efe256c34c7de23ddf1ae4611e05119410a487f4b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f1f0d0d2d8c45fe4ce0c948a129c68e433f2d4ae068deb8bd7cbceb0ea015f27
87c9742d4700629243bbfd544d227c64bbb478a0607bd21b1a16072eb50b6b8e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8d107d10fbb8916cce95a4e2291830449f2dc9d6341e3dbba51a5ae7642d17d5
8bdf895f76e7615b03cd8d2e50ee8272e9598a6f21426a4ec86e124fbaf86741
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
966ae3021ee93af461d19c78053d42918917e7a754dac5becda21fba3e8b9ddd
63cc4ad099d6c383b78e46dddc5b578c899cfc42e4b9dc5726704f1d6c8da83a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
161ef690cbb2b0c4aadcc0719f9dbe58a5ee0235895427f8137816d270d0ba6a
213bdb00682f6e573f54ad07698e5090f9bc1ccd3ebfc9cf7f703b2fdce9f30a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3f1cdd40349346eab3ba5f175d674a202fc6237b5c83388767e3667bea51515f
1facc9f2d4e26f87e8a80719b560b61d7e6a3c953753cfe20bc2eba9b31934d1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
429ffc70da72af8532d68ebb741fb4a694465b5460567c42ceeb76f66ca02165
7fbe4b0ac9d49efd8300867d9b447bced49a7f3d9ab7bcebd74b11c7c8ff546f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e7141ca998b249cbc0a4dc0565fa621119f25c9a213ccfdbd6d3b62378c47239
2c4cc949885b3d1d0f4a9dbc44c239d55ed4e43f71c8b09a8da3e9f31a439841
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5cae8da91f43fa48fa84b0a7c71530f0629cdac20bbbda4cd0d1f405e9d3fb72
23c9187f4deb89351de32a52e8f08b4933d2bbe72fcf3c9a7c9b29ae20bbdb44
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b1f943eb3661ec38eed856269d30009738ec833a75e7a7a0da09358afa6dff36
e7159f2069bbfbdb68b8770040772949013b733e16513d57333664d6a945a326
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5f525aeb82bde5016791285b92674347b303edd27770d67028f32dd8071e4ee1
29f64f3236c46cd1b0e7915736fdb41f3826161c4d950aac7ed7b6b0767786be
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a803720da55b706875485399f700cc6d8d6b7e9adca74dc9931052b4143b4e27
072c75538a1e36064fafd69f66e7d40024b4f5909f3d6acf8191071dbe195c92
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8dd5fd56707cf120f1bcddec5093c5d5a075faae8dcb4ad17b6797efdcee9621
ecc4f6f73209bd2d4d10353ed73a3a8629381cf6c8901673ae8ce19541136b96
+1
Переглянути файл
@@ -69,6 +69,7 @@ Later:
| `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 |
| `net.http:<host>` | Medium | Unencrypted HTTP to that host | 1.4 |
| `database.sources` | Medium | Manage only the plugin's own project database sources and write their credentials; trusted projects only | 1.4 |
| `database.schema` | Medium | Read table schema from connected project data sources, including user-created sources; trusted projects only. No credentials or row data. | 1.20 |
| `fs.read:<path>` | High | `host::fs` reads outside the projects, under that path | 1.0 (the `fs` interface: 1.3) |
| `fs.write:<path>` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 |
| `process:<program>` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 |
+84 -2
Переглянути файл
@@ -6,8 +6,9 @@ description: "Create and manage plugin-owned data sources in the Database tool w
A plugin that starts or knows about a database (a local dev stack, a cloud tool, a
container runner) can add a data source to the project's **Database** tool window, so the
user doesn't have to type the connection settings. The plugin manages only the sources it
created; it never sees user-created sources, other plugins' sources or any stored
password. Once a source exists, the user works with it through the normal
created through `database.sources`; it never reads stored passwords. API 1.20
adds a separate `database.schema` permission for reading table metadata from connected
project data sources, including user-created sources. Once a source exists, the user works with it through the normal
[Database tools](/en/guide/database).
This is the `database` host interface (`database.wit`, API 1.4).
@@ -103,3 +104,84 @@ seconds, and the call can be cancelled.
The [`data-tools` fixture](https://github.com/l0ng-ai/openidea/tree/main/crates/ide-plugin/tests/fixtures/data-tools)
calls every function from commands.
## Table menus and schema inspection (API 1.20)
A code generator can contribute commands to `database.table.context`. The menu is
available on table, view and materialized-view nodes. An optional `when` expression
must match every selected table. Mixed selections containing folders or columns do
not show these commands. Right-clicking outside the selection targets that table alone.
```toml
engines.openidea = "^1.20"
[capabilities]
required = ["project.read"]
optional = ["database.schema", "project.write"]
[[contributes.commands]]
id = "generate"
title = "Generate mapper"
[[contributes.menus]]
menu = "database.table.context"
command = "generate"
when = "databaseObjectKind == table"
```
The command argument is a JSON string with `tables`, in selection order:
```json
{
"tables": [
{
"sourceId": "pg:inventory",
"catalog": null,
"schema": "public",
"table": "users",
"kind": "table",
"driver": "postgres"
}
]
}
```
`sourceId` is an opaque host identifier; pass it back unchanged. `catalog` is
present for catalog-aware tables (for example, attached DuckDB databases).
The menu provides `databaseDriver`, `databaseObjectKind` (`table`, `view`,
`materializedView`), `databaseSchema`, `databaseTable`, and
`databaseSelectionCount` to `when`. These keys are local to this menu.
Read each selected table with the Rust SDK:
```rust
use openidea_plugin::{DatabaseTableRef, Error, Invocation};
fn inspect(ctx: &Invocation, argument: &str) -> Result<(), Error> {
let project = ctx.project().ok_or("Open a project first")?;
let value: serde_json::Value = serde_json::from_str(argument)
.map_err(|e| Error::Invalid(e.to_string()))?;
let tables: Vec<DatabaseTableRef> = serde_json::from_value(value["tables"].clone())
.map_err(|e| Error::Invalid(e.to_string()))?;
for table in tables {
let schema = project.database_table_schema(&table)?;
// Generate files from schema.columns, schema.indexes and schema.foreign_keys.
// Writing project files requires project.write separately.
let _ = schema;
}
Ok(())
}
```
`Project::database_table_schema` maps to WIT `database.describe-table(project, table)`.
It returns the table comment; columns with type, nullability, default, primary-key
flag and comment; indexes with uniqueness and column names; and foreign-key
references. Availability and detail depend on the database driver.
Every call requires `database.schema` and a trusted, open project. This permission
does not grant `database.sources`, and source ownership is not required. The source
must already be connected through the Database tool window; inspection does not
connect it or request credentials. No SQL execution, connection settings, passwords
or row data are exposed. Requests respect cancellation and the host I/O deadline;
missing or invisible tables fail, and each metadata collection is limited to 4096
entries. Remote projects use the project's existing Database subsystem.
+3 -2
Переглянути файл
@@ -1,9 +1,9 @@
---
title: "API versions and compatibility"
description: "engines.openidea, the plugin API versions from 1.0 to 1.19, and the rules that keep released plugins loading in newer IDEs."
description: "engines.openidea, the plugin API versions from 1.0 to 1.20, and the rules that keep released plugins loading in newer IDEs."
---
The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.19.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files.
The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.20.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files.
<Note>
The plugin system is a preview. The compatibility rules below hold for released 1.x versions; what is still unreleased
@@ -34,6 +34,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette |
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself |
| 1.19.0 | In development on `main` | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view |
| 1.20.0 | In development | Database table context menus and read-only table schema inspection (`database.schema`). |
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
+1
Переглянути файл
@@ -69,6 +69,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
| `net:ask` | 中 | 第一次请求未声明的 HTTPS 主机时询问用户 | 1.5 |
| `net.http:<host>` | 中 | 通过未加密的 HTTP 访问该主机 | 1.4 |
| `database.sources` | 中 | 只管理插件自己的项目数据源并写入其凭据;仅限受信任项目 | 1.4 |
| `database.schema` | 中 | 读取已连接的项目数据源(包括用户创建的数据源)的表结构;仅限受信任项目,不返回凭据或表数据。 | 1.20 |
| `fs.read:<path>` | 高 | 通过 `host::fs` 读取项目外、该路径下的文件 | 1.0(`fs` interface:1.3) |
| `fs.write:<path>` | 高 | 通过 `host::fs` 写入项目外、该路径下的文件;不包含读权限 | 1.3 |
| `process:<program>` | 高 | 运行该程序:`run_process`、`run_command`、`start`、终端、语言服务器、调试适配器、运行配置 | 1.0 |
+58 -2
Переглянути файл
@@ -4,8 +4,8 @@ description: "在数据库工具窗口中创建和管理插件自有的数据源
---
如果插件会启动或知道某个数据库(本地开发环境、云工具、容器运行器等),可以把数据源直接加到项目的 **数据库**
工具窗口中,省得用户手动填写连接设置。插件只能管理它自己创建的数据源:看不到用户创建的数据源、其他插件的数据源,
也看不到任何已保存的密码。数据源创建后,用户就通过常规的 [数据库工具](/zh/guide/database) 使用它。
工具窗口中,省得用户手动填写连接设置。`database.sources` 只能管理插件自己创建的数据源,无法读取已保存的密码。API 1.20 新增独立的
`database.schema` 权限,用于读取已连接的项目数据源(包括用户创建的数据源)的表结构。数据源创建后,用户就通过常规的 [数据库工具](/zh/guide/database) 使用它。
这就是 `database` 宿主接口(`database.wit`,API 1.4)。
@@ -90,3 +90,59 @@ fn run_command(&mut self, _id: &str, ctx: &Invocation, _arg: Option<&str>) -> Re
[`data-tools` 测试插件](https://github.com/l0ng-ai/openidea/tree/main/crates/ide-plugin/tests/fixtures/data-tools)
在命令中调用了全部函数。
## 表右键菜单与表结构读取(API 1.20)
代码生成插件可以向 `database.table.context` 添加命令,目标包括表、视图和物化视图节点。
多选时,`when` 条件必须对每个节点都成立;选区混有文件夹或列时不显示插件菜单。
右键点击选区之外的表时,仅以该表为目标。
```toml
engines.openidea = "^1.20"
[capabilities]
required = ["project.read"]
optional = ["database.schema", "project.write"]
[[contributes.commands]]
id = "generate"
title = "生成 Mapper"
[[contributes.menus]]
menu = "database.table.context"
command = "generate"
when = "databaseObjectKind == table"
```
命令收到 JSON 字符串参数,`tables` 按选中顺序排列:
```json
{
"tables": [
{
"sourceId": "pg:inventory",
"catalog": null,
"schema": "public",
"table": "users",
"kind": "table",
"driver": "postgres"
}
]
}
```
`sourceId` 是不透明的宿主标识,调用接口时原样传回。`catalog` 用于区分支持 catalog 的表,
例如 DuckDB 的附加数据库。菜单的局部条件键为 `databaseDriver`、`databaseObjectKind`
(`table`、`view`、`materializedView`)、`databaseSchema`、`databaseTable` 和
`databaseSelectionCount`。
将 `tables` 反序列化为 `Vec<openidea_plugin::DatabaseTableRef>`,逐个调用
`ctx.project().ok_or("请打开项目")?.database_table_schema(&table)`。
Rust SDK 对应的 WIT 函数是 `database.describe-table(project, table)`。
返回表注释,列的名称、类型、可空性、默认值、主键标记和注释,以及索引和外键引用。
具体元数据取决于数据库驱动。写入生成文件仍需要单独的 `project.write` 权限。
每次调用都需要 `database.schema` 和受信任的已打开项目;它不授予 `database.sources`,
也不要求数据源归插件所有。数据源必须已通过数据库工具窗口连接:接口不会自动连接或请求凭据,
不提供 SQL 执行、连接设置、密码或行数据。调用支持取消并遵守宿主 I/O 超时;不存在或不可见的表
会返回错误,每类元数据最多 4096 项。远程项目使用项目现有的数据库子系统。
+3 -2
Переглянути файл
@@ -1,9 +1,9 @@
---
title: "API 版本与兼容"
description: "engines.openidea、插件 API 从 1.0 到 1.19 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。"
description: "engines.openidea、插件 API 从 1.0 到 1.20 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。"
---
插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.19.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。
插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.20.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。
<Note>插件系统目前是预览版。下面的兼容规则适用于已发布的 1.x 版本;`main` 上尚未发布的内容在发布前仍可能变化。</Note>
@@ -31,6 +31,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.19 的各个版本,
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 |
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 |
| 1.19.0 | `main` 上开发中 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 |
| 1.20.0 | `main` 上开发中 | Database table context menus and read-only table schema inspection (`database.schema`). |
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
+80
Переглянути файл
@@ -0,0 +1,80 @@
import { expect, stubDesktop, test } from "./fixtures";
test("table menu contributions preserve selected table identities", async ({ workbench: page }, info) => {
await stubDesktop(page);
await page.evaluate(async () => {
const storePath = "/src/features/database/store.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { useDatabase } = await import(storePath);
const { toolWindowService } = await import(contributionsPath);
useDatabase.setState({
sources: [{ id: "local", name: "Inventory", driver: "sqlite", file: "inventory.sqlite" }],
loaded: true,
connected: new Set(["local"]),
schemas: { local: { status: "ok", value: ["main"] } },
foldersLoaded: true,
tables: {
["local\u0000main"]: {
status: "ok",
value: [
{ name: "users", kind: "table" },
{ name: "orders", kind: "table" },
],
},
},
});
toolWindowService().show("database", true);
});
const panel = page.locator('section[aria-label="Database"]');
const source = panel.getByRole("treeitem").filter({ hasText: "Inventory" });
await source.locator("[data-tree-toggle]").click();
const schema = panel.getByRole("treeitem").filter({ hasText: /^main/ });
if (await schema.count()) await schema.locator("[data-tree-toggle]").click();
await panel
.getByRole("treeitem")
.filter({ hasText: /^tables/ })
.locator("[data-tree-toggle]")
.click();
const users = panel.getByRole("treeitem").filter({ hasText: /^users/ });
await expect(users).toBeVisible();
await users.click({ button: "right" });
await expect(page.getByRole("menu").last()).toBeVisible();
await page.screenshot({ path: info.outputPath("before.png"), animations: "disabled" });
await page.keyboard.press("Escape");
await page.evaluate(async () => {
const actionsPath = "/src/platform/actions.ts";
const projectionPath = "/src/features/plugins/projection.ts";
const { registerAction } = await import(actionsPath);
const { syncUiContributions } = await import(projectionPath);
registerAction({
id: "plugin.mapper.generate",
title: "Generate MyBatis mapper",
run: ({ arg }: { arg?: unknown }) => {
Object.assign(window, { __tableSelection: arg });
},
});
syncUiContributions(
[
{
pluginId: "mapper",
point: "menus",
key: "database.table.context/generate",
decl: { menu: "database.table.context", command: "generate", when: "databaseObjectKind == table" },
},
],
[{ id: "mapper", name: "Mapper generator", enabled: true, status: "active", icon: null }],
);
});
await users.click({ button: "right" });
const generate = page.getByRole("menuitem", { name: "Generate MyBatis mapper" });
await expect(generate).toBeVisible();
await page.screenshot({ path: info.outputPath("after.png"), animations: "disabled" });
await generate.click();
await expect
.poll(() => page.evaluate(() => (window as unknown as { __tableSelection?: string }).__tableSelection))
.toBeTruthy();
const selection = await page.evaluate(() => (window as unknown as { __tableSelection: string }).__tableSelection);
expect(JSON.parse(selection)).toEqual({
tables: [{ sourceId: "local", catalog: null, schema: "main", table: "users", kind: "table", driver: "sqlite" }],
});
});
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more