feat(plugins): add clone sources to the Clone Repository dialog (#7948)

[[contributes.cloneSources]] (API 1.21) adds an entry to the Get from VCS source list whose required web page lists repositories and hands the chosen one to the dialog with {"op": "clone-url", "url": …}. The page is served and messaged like other plugin web UI under the key cloneSources/<id>; the dialog fills its URL and directory and git only runs what the user confirms. The standalone Get from VCS window registers only this contribution point. plugin_web_page and plugin_view_event now also run in projectless windows (outside_restricted); Restricted Mode still runs no plugin UI or code. Docs list the point under API 1.21.

Fixes #5572

Co-authored-by: arookieofc-ai <[email protected]>
Цей коміт міститься в:
arookieofc-ai[bot]таarookieofc-ai authored and GitHub committed 2026-12-04 20:46:11 +08:00
1 джерело 896ec3b924
коміт 67c00a986a
21 files changed
+480 -14

No files matched your search

+1
Переглянути файл
@@ -99,6 +99,7 @@ pub fn register_builtin_points(
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
registry.register(Arc::new(UiPoint::new(p::RUN_CONFIG_TYPES, ui.clone(), p::run_config_type)))?;
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
registry.register(Arc::new(UiPoint::new(p::CLONE_SOURCES, ui.clone(), p::clone_source)))?;
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
+46 -1
Переглянути файл
@@ -110,8 +110,11 @@ pub const OVERLAYS: &str = "overlays";
pub const DIALOGS: &str = "dialogs";
pub const RUN_CONFIG_TYPES: &str = "runConfigTypes";
pub const RUN_ANYTHING: &str = "runAnything";
/// Entries of the Clone Repository dialog's source list, each a web page.
pub const CLONE_SOURCES: &str = "cloneSources";
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
pub const WEB_POINTS: [&str; 6] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES];
pub const WEB_POINTS: [&str; 7] =
[VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES, CLONE_SOURCES];
pub const FILE_ICONS: &str = "fileIcons";
pub const MARKER_ICONS: &str = "markerIcons";
pub const FILE_TEMPLATES: &str = "fileTemplates";
@@ -1537,6 +1540,48 @@ pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result<UiDecl
Ok(out)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct CloneSourceDecl {
id: String,
label: String,
/// An IDE icon name (`branch`, `git-pull`) or a package SVG (`icons/gitee.svg`),
/// as on a view: the pane lists the service's own logo.
#[serde(default, skip_serializing_if = "Option::is_none")]
icon: Option<String>,
/// The page that lists repositories and posts the chosen clone URL.
/// Required: the dialog has nothing else to show for a source.
web: String,
}
pub(super) fn clone_source(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: CloneSourceDecl = decode(CLONE_SOURCES, decl)?;
pkg.manifest.needs_api(&format!("contributes.{CLONE_SOURCES}"), 21)?;
validate_item_id(&d.id, "clone source id")?;
title(CLONE_SOURCES, &d.label)?;
let what = format!("clone source {:?}", d.id);
if d.icon.as_ref().is_some_and(|i| i.len() > 64) {
return Err(format!("clone source {:?}: icon names are up to 64 bytes", d.id));
}
let files = super::web::web_files(pkg, &d.web, &what)?;
// The key is namespaced with the point: a source's page is served, messaged
// and sent view events under it, and it cannot collide with a view's id.
let mut out = UiDecl::new(format!("{CLONE_SOURCES}/{}", d.id), d.label.clone(), json(&d)?);
out.files = files;
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
let path = std::path::PathBuf::from(icon);
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
out.assets.push((clone_source_icon_asset(&d.id), svg));
out.files.push(path);
}
Ok(out)
}
/// Asset id of a clone source's SVG icon, fetched by the workbench for the dialog.
pub fn clone_source_icon_asset(id: &str) -> String {
format!("cloneSourceIcon/{id}")
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FileIconDecl {
+2 -1
Переглянути файл
@@ -61,8 +61,9 @@ pub async fn plugin_view_render(
}
/// A user action in a plugin view or custom editor (`doc`, `editor`: as for rendering).
/// Clone-source pages live in projectless Get from VCS windows; Restricted Mode still runs no plugin code.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn plugin_view_event(
host: &crate::Host,
plugins: &Arc<PluginHost>,
+74
Переглянути файл
@@ -8460,3 +8460,77 @@ title = "Prepare"
f.host.set_enabled("jobs", false).unwrap();
assert!(f.host.web_page("jobs", "jobs").is_err());
}
/// A clone source is a page the Clone Repository dialog lists: its key carries
/// the point's name, its page is served like a view's, and it needs a `web`
/// entry plus API 1.21.
#[test]
fn clone_sources_are_web_pages_under_a_namespaced_key() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("gitee-demo");
std::fs::create_dir_all(pkg.join("clone")).unwrap();
std::fs::write(pkg.join("clone/index.html"), "<!doctype html><html><body>repos</body></html>").unwrap();
std::fs::write(
pkg.join("plugin.toml"),
r#"id = "gitee-demo"
name = "Gitee Demo"
version = "1.0.0"
engines.openidea = "^1.21"
[[contributes.cloneSources]]
id = "gitee"
label = "Gitee"
icon = "branch"
web = "clone/index.html"
"#,
)
.unwrap();
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
let item = f.host.ui_items("cloneSources").into_iter().find(|i| i.plugin_id == "gitee-demo").expect("the source");
assert_eq!(item.key, "cloneSources/gitee");
assert_eq!((item.decl["label"].as_str(), item.decl["icon"].as_str()), (Some("Gitee"), Some("branch")));
// A source is not a tool window.
assert!(f.host.ui_items("views").iter().all(|i| i.plugin_id != "gitee-demo"));
let page = f.host.web_page("gitee-demo", "cloneSources/gitee").unwrap();
let (rev, entry) = page.path.strip_prefix("gitee-demo/").unwrap().split_once('/').unwrap();
assert_eq!(entry, "clone/index.html");
assert!(f.host.web_file("gitee-demo", &format!("{rev}/clone/index.html")).is_ok());
assert!(f.host.web_page("gitee-demo", "cloneSources/nope").is_err());
// Refused: no page, a bad id, and an engine older than the point.
for (name, body, message) in [
("no-page", "id = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/missing.html\"", "no such file"),
("bad-id", "id = \"Gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"", "invalid clone source id"),
("no-web", "id = \"gitee\"\nlabel = \"Gitee\"", "missing field `web`"),
] {
let dir = tempfile::tempdir().unwrap();
let pkg = dir.path().join(name);
std::fs::create_dir_all(pkg.join("clone")).unwrap();
std::fs::write(pkg.join("clone/index.html"), "<p>repos</p>").unwrap();
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"gitee-{name}\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.cloneSources]]\n{body}\n"
),
)
.unwrap();
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains(message), "{name}: {}", err.message);
}
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("old");
std::fs::create_dir_all(old.join("clone")).unwrap();
std::fs::write(old.join("clone/index.html"), "<p>repos</p>").unwrap();
std::fs::write(
old.join("plugin.toml"),
"id = \"gitee-old\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.20\"\n\n[[contributes.cloneSources]]\nid = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"\n",
)
.unwrap();
let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.21"), "{}", err.message);
}
+1
Переглянути файл
@@ -122,6 +122,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
| `runConfigTypes` | `id`, `label`, `web`, `layout?`, `prepareCommand?`, `matchConfigPrefix?`, `ownsBeforeLaunch?` (API 1.20; `ownsBeforeLaunch`: 1.21) | no | [README: Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) |
| `cloneSources` | `id`, `label`, `icon?`, `web` (API 1.21; the page posts the chosen URL) | no | [README: Clone sources](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#clone-sources-api-121) |
| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) |
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) |
| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) |
+2 -2
Переглянути файл
@@ -35,7 +35,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
| 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 | OpenIDEA 0.1.56 | `[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 | OpenIDEA 0.1.57 | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. |
| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. |
| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `cloneSources`: plugin pages in the Clone Repository dialog's source list. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. |
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
@@ -58,7 +58,7 @@ engines.openidea = "^1.4"
| `net.http:`, `ipc:`, `ide.commands`, `database.sources`; the `file-closed`, `settings-changed`, `input-mode-changed`, `run-exited`, `terminal-exited` and `content-tab-action` events; `runConfigurations`, `snippets`, `mcpTools`, command `icon`, run detector `framework`; the API 1.4 provider kinds and injections; the API 1.4 menu locations | `^1.4` |
| `net:ask` | `^1.5` |
| `on-event:websocket-ready` and background WebSockets | `^1.6` |
| settings `presentation`, `enumOptions` and `when` | `^1.21` |
| settings `presentation`, `enumOptions` and `when`; `cloneSources` | `^1.21` |
## The component's own version
+1
Переглянути файл
@@ -122,6 +122,7 @@ optional = ["net:api.openai.com", "secrets"]
| `runAnything` | `prefix`、`title?`(API 1.18) | 否 | [README:Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
| `dialogs` | `id`、`title`、`web`、`width`、`height`(API 1.18) | 否 | [README:Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
| `runConfigTypes` | `id`、`label`、`web`、`layout?`、`prepareCommand?`、`matchConfigPrefix?`、`ownsBeforeLaunch?`(API 1.20;`ownsBeforeLaunch` 为 1.21) | 否 | [README:Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) |
| `cloneSources` | `id`、`label`、`icon?`、`web`(API 1.21;页面提交所选 URL) | 否 | [README:Clone sources](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#clone-sources-api-121) |
| `fileIcons` | `id`、`patterns`、`icon`、`iconDark?` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
| `fileTemplates` | `id`、`name`、`extension`、`path`;API 1.3:`fileName`、`variables` | 否 | [文件操作](/zh/plugins/guides/file-actions) |
| `snippets` | `language`、`path`(API 1.4) | 否 | [语言功能](/zh/plugins/guides/language-features) |
+2 -2
Переглянути файл
@@ -32,7 +32,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.21 的各个版本,
| 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 | OpenIDEA 0.1.56 | `[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 | OpenIDEA 0.1.57 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 |
| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。 |
| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。`cloneSources`:Clone Repository 对话框来源列表中的插件页面。 |
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
@@ -55,7 +55,7 @@ engines.openidea = "^1.4"
| `net.http:`、`ipc:`、`ide.commands`、`database.sources`;`file-closed`、`settings-changed`、`input-mode-changed`、`run-exited`、`terminal-exited` 和 `content-tab-action` 事件;`runConfigurations`、`snippets`、`mcpTools`、命令 `icon`、运行检测器的 `framework`;API 1.4 的 provider kind 和嵌入语言;API 1.4 新增的菜单位置 | `^1.4` |
| `net:ask` | `^1.5` |
| `on-event:websocket-ready` 和后台 WebSocket | `^1.6` |
| 设置的 `presentation`、`enumOptions` 和 `when` | `^1.21` |
| 设置的 `presentation`、`enumOptions` 和 `when`;`cloneSources` | `^1.21` |
## 组件本身的版本
+55
Переглянути файл
@@ -161,6 +161,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no |
| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no |
| `runConfigTypes` | `id`, `label`, `web`, `layout?` (`embedded` / `full`), `height?`, `icon?`, `iconDark?`, `group?`, `command?`, `args?`, `prepareCommand?`, `matchConfigPrefix?`, `defaults?` — a custom Run/Debug Configurations form (`openidea.runConfig`; API 1.20; _Custom run configuration forms_) | no |
| `cloneSources` | `id`, `label`, `icon?` (icon name or package SVG), `web` — an entry of the Clone Repository dialog whose page posts the chosen URL (API 1.21; _Clone sources_) | no |
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no |
| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes |
@@ -438,6 +439,19 @@ are always available. Calling a gated function without its capability returns
## 3. Writing code (Rust SDK)
### API 1.21
API 1.21.0 is in development on `main`. Use `engines.openidea = "^1.21"` and the
matching SDK. Plugins for 1.20 and earlier keep working. New in 1.21:
- **Clone sources (`[[contributes.cloneSources]]`).** An entry in the Clone
Repository dialog's source list: `id`, `label`, `icon?` (an icon name or a
package SVG) and a required `web` page, served and messaged like a web view
under the key `cloneSources/<id>`. The page lists the service's repositories
and posts `{ "op": "clone-url", "url": … }` when one is picked; the dialog
fills its URL field and switches to its normal form, so git runs only when the
user confirms. See _Clone sources_.
### API 1.19
API 1.19.0 shipped with OpenIDEA 0.1.56. Use `engines.openidea = "^1.19"` and the
@@ -2269,6 +2283,47 @@ the global choice for runs, process handles, terminals and log panes. Resetting
a choice verifies its fallback, or revokes the grant if that is unavailable.
The plugin continues to call its declared program name.
### Clone sources (API 1.21)
`[[contributes.cloneSources]]` adds an entry to the source list of **Get from
VCS** — the Clone Repository dialog of the welcome screen and of
`File › New` — so a hosting service the plugin knows can list its repositories
next to the built-in GitHub one.
```toml
engines.openidea = "^1.21"
[[contributes.cloneSources]]
id = "gitee"
label = "Gitee"
icon = "branch"
web = "clone/index.html"
```
`label` is localized through `locales/<tag>.json` like other contribution titles,
and `icon` takes an IDE icon name or a package SVG (`icon = "icons/gitee.svg"`),
as on a view.
`web` is required: a source without a page would show an empty pane, so
`openidea-plugin check` rejects it. The page lives in a directory of the
package, like a view's `web`, and may load only the files in it (4096 files,
256 MiB, no links leaving the package).
The page runs in the same sandboxed frame as a web view — an opaque origin with
no network and no IDE API — and talks to the plugin's code with
`openidea.postMessage` / `openidea.onMessage`. The plugin receives that text as
a `message` view event for the key `cloneSources/<id>` (so
`register_plugin!(MyPlugin, views)` handles it like any view event) and answers
with `views.post_message("cloneSources/<id>", …)`. To hand a repository to the
dialog:
```js
openidea.postMessage(JSON.stringify({ op: "clone-url", url: "https://gitee.com/acme/widgets.git" }));
```
The dialog fills its URL field with it and switches to its normal form (target
directory, shallow clone), so git only runs what the user confirms. Any other
text reaches the plugin unchanged.
### Views and custom editors
A view is data: a toolbar, a body — `Tree`, `List`, `Form`, `Table`,
+3 -2
Переглянути файл
@@ -405,8 +405,9 @@ pub(crate) async fn plugin_event_kinds(window: tauri::Window) -> Vec<EventKind>
kinds.await.unwrap_or_default()
}
/// The page of a plugin's web view or custom editor (`web = …`).
#[desktop_command(trust = trusted)]
/// The page of a plugin's web view or custom editor (`web = …`). Projectless
/// Get from VCS windows show clone-source pages; Restricted Mode still runs no plugin UI.
#[desktop_command(trust = outside_restricted)]
#[tauri::command]
#[specta::specta]
pub fn plugin_web_page(
+2 -2
Переглянути файл
@@ -632,9 +632,9 @@ plugin_terminal_session_spawn trusted project_host bin
plugin_uninstall outside_restricted desktop bindings async
plugin_unlink trusted desktop bindings async
plugin_unpack_package always desktop bindings async
plugin_view_event trusted project_host bindings async
plugin_view_event outside_restricted project_host bindings async
plugin_view_render trusted project_host bindings async
plugin_web_page trusted desktop bindings sync
plugin_web_page outside_restricted desktop bindings sync
plugin_web_pty_spawn trusted desktop bindings async
plugin_web_read_file trusted desktop bindings async
plugin_web_save_file trusted desktop bindings async
+8 -2
Переглянути файл
@@ -1771,7 +1771,10 @@ export const commands = {
pluginUnlink: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_unlink", { id })),
/** Unpacks a package file (`.oiplugin` or `.zip`); returns the folder for the install page. */
pluginUnpackPackage: (path: string) => typedError<string, IdeError>(__TAURI_INVOKE("plugin_unpack_package", { path })),
/** A user action in a plugin view or custom editor (`doc`, `editor`: as for rendering). */
/**
* A user action in a plugin view or custom editor (`doc`, `editor`: as for rendering).
* Clone-source pages live in projectless Get from VCS windows; Restricted Mode still runs no plugin code.
*/
pluginViewEvent: (pluginId: string, view: string, event: ViewEvent, doc: number | null, editor: {
path: string,
language: string,
@@ -1793,7 +1796,10 @@ export const commands = {
/** First and last document line on screen (0-based, inclusive); absent from older clients. */
visibleLines?: [number, number] | null,
} | null) => typedError<View, IdeError>(__TAURI_INVOKE("plugin_view_render", { pluginId, view, viewport, doc, editor })),
/** The page of a plugin's web view or custom editor (`web = …`). */
/**
* The page of a plugin's web view or custom editor (`web = …`). Projectless
* Get from VCS windows show clone-source pages; Restricted Mode still runs no plugin UI.
*/
pluginWebPage: (pluginId: string, view: string) => typedError<WebPage, IdeError>(__TAURI_INVOKE("plugin_web_page", { pluginId, view })),
pluginWebPtySpawn: (pluginId: string, view: string, command: WebPtyCommand, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("plugin_web_pty_spawn", { pluginId, view, command, onOutput })),
/**
+2
Переглянути файл
@@ -1,6 +1,7 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { githubCloneSource } from "./features/github/clone/source";
import { startCloneSourcePlugins } from "./features/plugins/cloneSource";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activateCloneLaunches, CloneWindow } from "./features/vcs/cloneWindow";
import { provideEmbeddedTerminal, registerCloneSource } from "./workbench/contributions";
@@ -24,6 +25,7 @@ export function bootCloneWindow(parent: string): ComponentType {
["settings", trackRuntimeSettings],
["terminal", embeddedTerminal],
["github", () => registerCloneSource(githubCloneSource)],
["plugin clone sources", startCloneSourcePlugins],
["dialog", () => activateDialogWindow(parent)],
["launch", activateCloneLaunches],
]);
+96
Переглянути файл
@@ -0,0 +1,96 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { PluginInfo, UiContribution } from "@/bindings";
import { useCloneSources } from "@/workbench/contributions";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { clonePickFromMessage, startCloneSourcePlugins } from "../cloneSource";
import { clearUiContributions, syncUiContributions } from "../projection";
import { defineViewUiPoints } from "../uiPoints";
const plugins = [{ id: "gitee", status: "inactive" }] as PluginInfo[];
const source = (extra: Record<string, unknown> = {}): UiContribution => ({
pluginId: "gitee",
point: "cloneSources",
key: "cloneSources/gitee",
decl: { id: "gitee", label: "Gitee", web: "clone/index.html", ...extra },
});
const registered = () => useCloneSources.getState().sources.get("plugin:gitee/gitee");
let stop: () => void;
beforeEach(() => {
clearUiContributions();
stop = defineViewUiPoints();
});
afterEach(() => {
clearUiContributions();
stop();
setPluginsBackend(null);
});
it("reads the repository a page picked", () => {
expect(clonePickFromMessage('{"op":"clone-url","url":"https://gitee.com/acme/widgets.git"}')).toEqual({
url: "https://gitee.com/acme/widgets.git",
clone: false,
});
expect(clonePickFromMessage('{"op":"clone-url","url":" [email protected]:acme/widgets.git "}')).toEqual({
url: "[email protected]:acme/widgets.git",
clone: false,
});
// A double click asks the dialog to clone right away, like the built-in sources.
expect(clonePickFromMessage('{"op":"clone-url","url":"https://gitee.com/a/b.git","clone":true}')).toEqual({
url: "https://gitee.com/a/b.git",
clone: true,
});
});
it("leaves everything else to the plugin", () => {
for (const text of [
"",
"not json",
"[]",
"null",
'{"op":"other","url":"https://gitee.com/a/b.git"}',
'{"op":"clone-url"}',
'{"op":"clone-url","url":42}',
'{"op":"clone-url","url":" "}',
// A URL with a space is not a clone URL: the dialog's field takes one token.
'{"op":"clone-url","url":"https://gitee.com/a b"}',
]) {
expect(clonePickFromMessage(text), text).toBeNull();
}
});
it("registers the source with the dialog as the plugin declared it", () => {
syncUiContributions([source({ icon: "branch" })], plugins);
expect(registered()).toMatchObject({ id: "plugin:gitee/gitee", label: "Gitee", icon: "branch" });
});
it("falls back to a generic icon, and disposes with the plugin", () => {
syncUiContributions([source()], plugins);
expect(registered()?.icon).toBe("branch");
syncUiContributions([], plugins);
expect(registered()).toBeUndefined();
});
it("shows a package SVG as the source's icon", async () => {
setPluginsBackend({
...createMemoryPluginsBackend([]),
assets: async () => [["cloneSourceIcon/gitee", '<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>']],
});
syncUiContributions([source({ icon: "icon.svg" })], plugins);
// The asset arrives asynchronously; the source is registered once it does.
await vi.waitFor(() => expect(registered()?.icon).toContain("pluginIcon/gitee"));
});
it("loads only clone sources in the standalone Get from VCS window", async () => {
stop();
stop = () => {};
setPluginsBackend({
...createMemoryPluginsBackend([]),
list: async () => ({ plugins, activeTheme: null, ui: [source({ icon: "branch" })] }),
});
const stopStandalone = startCloneSourcePlugins();
await vi.waitFor(() => expect(registered()).toMatchObject({ id: "plugin:gitee/gitee", label: "Gitee" }));
stopStandalone();
expect(registered()).toBeUndefined();
});
+10
Переглянути файл
@@ -0,0 +1,10 @@
.pane {
height: 100%;
min-width: 0;
}
/* Cloning: the page stays visible but takes no input, like the built-in sources. */
.pane[aria-disabled="true"] {
opacity: 0.6;
pointer-events: none;
}
+152
Переглянути файл
@@ -0,0 +1,152 @@
/**
* Clone sources contributed by plugins (`[[contributes.cloneSources]]`).
*
* The declaration's page is a web view of the plugin: it lists repositories and
* posts the one the user picks. The dialog's own `registerCloneSource` handles
* everything else — ordering, the disabled state while cloning, double-click to
* clone right away — so the dialog itself needs to know nothing about plugins.
*/
import type { ComponentType } from "react";
import type { CloneSourceProps } from "@/workbench/contributions";
import { notifications, registerCloneSource } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { errorText, refreshPlugins, syncPluginsAcrossWindows } from "./store";
import { pluginsBackend } from "./backend";
import { defineUiPoint } from "./projection";
import { syncPluginProjection } from "./themeRuntime";
import { pluginIconName } from "./pluginIcon";
import styles from "./cloneSource.module.css";
import { WebView } from "./views/WebView";
import { bumpView, deliverViewMessage } from "./views/viewStore";
/** What the page declares (`[[contributes.cloneSources]]`), already validated by the host. */
export interface CloneSourceDecl {
id: string;
label: string;
/** An IDE icon name, or a package SVG (`icons/gitee.svg`). */
icon?: string;
web: string;
}
/** The repository a page asked for, or null when the message is the plugin's own. */
export function clonePickFromMessage(text: string): { url: string; clone: boolean } | null {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object") return null;
const message = parsed as { op?: unknown; url?: unknown; clone?: unknown };
if (message.op !== "clone-url" || typeof message.url !== "string") return null;
const url = message.url.trim();
// A single line and no spaces: the dialog's field takes a clone URL, not a command.
if (!url || /\s/.test(url)) return null;
return { url, clone: message.clone === true };
}
/** The pane: the plugin's page, with its `clone-url` taken off the message stream. */
export function PluginCloneSource({
pluginId,
view,
label,
disabled,
onUrl,
onClone,
}: CloneSourceProps & { pluginId: string; view: string; label: string }) {
return (
<div className={styles.pane} aria-disabled={disabled || undefined} inert={disabled || undefined}>
<WebView
pluginId={pluginId}
view={view}
label={label}
header="none"
onText={(text) => {
const picked = clonePickFromMessage(text);
if (!picked) return false;
if (picked.clone) onClone(picked.url);
else onUrl(picked.url);
return true;
}}
/>
</div>
);
}
/**
* Registers a plugin's source with the dialog, icon first (a package SVG is an
* asset of the plugin, so it arrives asynchronously), and returns the disposer.
*/
export function projectCloneSource(pluginId: string, decl: CloneSourceDecl): () => void {
let disposed = false;
let undo: (() => void) | undefined;
const component: ComponentType<CloneSourceProps> = (props) => (
<PluginCloneSource pluginId={pluginId} view={`cloneSources/${decl.id}`} label={decl.label} {...props} />
);
const register = (icon: string) => {
if (disposed) return;
undo = registerCloneSource({
// Namespaced: two plugins may both call theirs "gitee".
id: `plugin:${pluginId}/${decl.id}`,
label: decl.label,
icon,
component,
});
};
const icon = decl.icon?.trim();
if (icon?.endsWith(".svg")) {
void pluginsBackend()
.assets(pluginId, `cloneSourceIcon/${decl.id}`)
.then((assets) => {
const svg = assets.find(([id]) => id === `cloneSourceIcon/${decl.id}`)?.[1];
register(svg ? pluginIconName(pluginId, { light: svg, dark: null }) : "branch");
})
.catch((e: unknown) => {
notifications().notify({
group: "plugins",
level: "warning",
title: tx`Could not load the ${decl.label} icon`,
body: tx`plugin ${pluginId}: ${errorText(e)}`,
});
register("branch");
});
} else {
register(icon || "branch");
}
return () => {
disposed = true;
undo?.();
};
}
/** Registers the client side of `cloneSources`; shared by the workbench and its standalone window. */
export function defineCloneSourceUiPoint(): () => void {
return defineUiPoint<CloneSourceDecl>("cloneSources", {
title: "Clone Sources",
project: ({ pluginId, decl }) => projectCloneSource(pluginId, decl),
});
}
/**
* Registers plugin clone sources in a window that is not the workbench (the
* standalone Get from VCS window): only this point, not every plugin surface.
*/
export function startCloneSourcePlugins(): () => void {
const undefine = defineCloneSourceUiPoint();
const stopProjection = syncPluginProjection();
const stopWindowSync = syncPluginsAcrossWindows();
const stopEvents = pluginsBackend().onEvent((e) => {
if (e.type === "commandsChanged") void refreshPlugins();
else if (e.type === "viewChanged") bumpView(e.pluginId, e.view);
else if (e.type === "viewMessage") deliverViewMessage(e.pluginId, e.view, e.message);
});
void refreshPlugins();
return () => {
stopEvents();
stopWindowSync();
stopProjection();
undefine();
};
}
+1
Переглянути файл
@@ -90,6 +90,7 @@ const TEXT_KEYS: Record<string, readonly string[]> = {
iconThemes: ["label"],
themes: ["name"],
secrets: ["label", "description"],
cloneSources: ["label"],
};
function localizeDecl(decl: unknown, keys: readonly string[], t: PluginTranslate): unknown {
+3
Переглянути файл
@@ -13,6 +13,7 @@
* - `editorPanels`: a web page at the right edge of every editor group, following its text editor;
* - `overlays`: a web page floating over the workbench that never takes the focus;
* - `dialogs`: a web page in a modal, resizable dialog that `views.reveal(id)` opens;
* - `cloneSources`: an entry of the Clone Repository dialog's source list, whose page picks a repository;
* - `fileIcons`: icons for the files a plugin knows, whatever icon theme is in use;
* - `fileTemplates`: entries of the New menu;
* - `commitChecks`: before-commit checks listed in Commit Options, run by the plugin's code.
@@ -84,6 +85,7 @@ import { pluginServiceProvider } from "./views/serviceProvider";
import { WebView } from "./views/WebView";
import { registerLogActions } from "./views/logActions";
import { projectSettings, type SettingsDecl } from "./settings";
import { defineCloneSourceUiPoint } from "./cloneSource";
// --- menus ------------------------------------------------------------------------
@@ -624,6 +626,7 @@ export function defineViewUiPoints(): () => void {
title: "Tool Windows",
project: ({ pluginId, decl }, { index }) => projectView(pluginId, decl, index),
}),
defineCloneSourceUiPoint(),
defineUiPoint<CustomEditorDecl>("customEditors", {
title: "Editors",
project: ({ pluginId, decl }) => {
+11
Переглянути файл
@@ -304,6 +304,11 @@ export interface WebViewProps {
pluginDialog?: FrameDialog | null;
/** A custom run-configuration form (`[[contributes.runConfigTypes]]`). */
runConfig?: FrameRunConfig | null;
/**
* Text the page posted. Returning true means it was handled here and does not
* reach the plugin's code (the Clone dialog's sources use it for `clone-url`).
*/
onText?: (text: string) => boolean;
}
export function WebView({
@@ -318,6 +323,7 @@ export function WebView({
overlay = null,
pluginDialog = null,
runConfig = null,
onText,
}: WebViewProps) {
const plugin = usePlugins((s) => s.plugins.find((p) => p.id === pluginId));
const page = usePageUrl(pluginId, view, plugin);
@@ -337,6 +343,10 @@ export function WebView({
anyActionRef.current = anyAction;
}, [anyAction]);
const frame = useRef<HTMLIFrameElement>(null);
const onTextRef = useRef(onText);
useEffect(() => {
onTextRef.current = onText;
}, [onText]);
const post = useCallback((message: object, transfer: Transferable[] = []) => {
frame.current?.contentWindow?.postMessage({ tag: FRAME_TAG, ...message }, "*", transfer);
@@ -607,6 +617,7 @@ export function WebView({
(err: unknown) => post({ reply: id, error: errorText(err) }),
);
} else if (typeof m.text === "string") {
if (onTextRef.current?.(m.text)) return;
if (handleLogTabMessage(m.text)) return;
if (handleContentTabMessage(m.text)) return;
if (handleDiffMessage(m.text)) return;
+4 -1
Переглянути файл
@@ -5656,5 +5656,8 @@
"{count} fields": "{count} fields",
"Included changes": "Included changes",
"Changelist": "Changelist",
"Changelist:": "Changelist:"
"Changelist:": "Changelist:",
"Clone Sources": "Clone Sources",
"Could not load the {label} icon": "Could not load the {label} icon",
"plugin {pluginId}: {e}": "plugin {pluginId}: {e}"
}
+4 -1
Переглянути файл
@@ -12560,5 +12560,8 @@
"Question": "问题",
"{count} questions": "{count} 个问题",
"{count} fields": "{count} 个字段",
"Included changes": "包含的更改"
"Included changes": "包含的更改",
"Clone Sources": "克隆来源",
"Could not load the {label} icon": "无法加载 {label} 图标",
"plugin {pluginId}: {e}": "插件 {pluginId}:{e}"
}