();
- return { ...actual, listPlugins };
+ return { ...actual, listPlugins, invokePlugin };
});
+vi.mock("@/components/plugins/PluginWorkbenchHost.vue", () => ({ default: { props: ["plugin", "contribution", "context"], template: '{{ contribution.id }}:{{ context.id }}
' } }));
import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";
import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
const connection = {
id: "conn-1",
@@ -73,7 +75,7 @@ async function mountHost() {
mountedApps.push(app);
await flush();
expect(host.value).not.toBeNull();
- return { host: host as unknown as { value: { buildContextMenu(node: TreeNode): ContextMenuItem[] } }, container };
+ return { host: host as unknown as { value: { buildContextMenu(node: TreeNode): ContextMenuItem[]; resolveContextMenu(node: TreeNode, items: ContextMenuItem[]): Promise | ContextMenuItem[] } }, container };
}
function menuLabels(items: ContextMenuItem[]): string[] {
@@ -84,6 +86,127 @@ describe("SidebarTreeRuntimeHost plugin context-menu refresh", () => {
beforeEach(() => {
listPlugins.mockReset();
listPlugins.mockResolvedValue([]);
+ invokePlugin.mockReset();
+ });
+
+ it("resolves connection-specific second-level items on each open and dispatches the selected id", async () => {
+ listPlugins.mockResolvedValue([
+ {
+ compatibility: { compatible: true },
+ manifest: {
+ id: "com.example.tunnels",
+ name: "Tunnels",
+ version: "1.0.0",
+ drivers: [],
+ contributions: [{ type: "context-menu", id: "tunnels", label: "Tunnels", menu: "connection", dynamic: true }],
+ },
+ },
+ ]);
+ invokePlugin.mockResolvedValue({});
+ invokePlugin.mockResolvedValueOnce({ items: [{ label: "Tunnels", children: [{ label: "Start saved", action: { type: "invoke", id: "start-all" } }] }] });
+ const { host } = await mountHost();
+ const first = await host.value.resolveContextMenu(connectionNode(), host.value.buildContextMenu(connectionNode()));
+ expect(menuLabels(first)).toContain("Start saved");
+ expect(invokePlugin).toHaveBeenCalledWith("com.example.tunnels", "contextMenu/resolve/tunnels", { connection: { id: "conn-1", dbType: "mysql", name: "Test MySQL", database: "" }, locale: expect.any(String) }, 500);
+ first.find((item) => item.label === "Tunnels")?.children?.[0].action?.();
+ await flush();
+ expect(invokePlugin).toHaveBeenCalledWith("com.example.tunnels", "contextMenu/tunnels", expect.objectContaining({ itemId: "start-all" }));
+
+ invokePlugin.mockResolvedValueOnce({ items: [{ label: "Tunnels", children: [{ label: "Stop all", action: { type: "invoke", id: "stop-all" } }] }] });
+ const second = await host.value.resolveContextMenu(connectionNode(), host.value.buildContextMenu(connectionNode()));
+ expect(menuLabels(second)).toContain("Stop all");
+ expect(menuLabels(second)).not.toContain("Start saved");
+ });
+
+ it("opens a declared plugin workbench in a dialog without creating a tab", async () => {
+ listPlugins.mockResolvedValue([
+ {
+ compatibility: { compatible: true },
+ manifest: {
+ id: "com.example.forwards",
+ name: "Port forwards",
+ version: "1.0.0",
+ drivers: [],
+ contributions: [
+ { type: "context-menu", id: "forwards", label: "Port forwards", menu: "connection", dynamic: true },
+ { type: "workbench", id: "com.example.forwards.manager", label: "Port forwards" },
+ ],
+ },
+ },
+ ]);
+ invokePlugin.mockResolvedValue({ items: [{ label: "Port forwards", children: [{ label: "Manage port forwards", action: { type: "open-workbench", workbench: "com.example.forwards.manager", presentation: "dialog" } }] }] });
+ const { host } = await mountHost();
+ const openTab = vi.spyOn(useQueryStore(), "openPluginWorkbench");
+ const items = await host.value.resolveContextMenu(connectionNode(), host.value.buildContextMenu(connectionNode()));
+ items.find((item) => item.label === "Port forwards")?.children?.[0].action?.();
+ await flush();
+ expect(document.querySelector('[data-test="plugin-dialog-workbench"]')?.textContent).toContain("com.example.forwards.manager:conn-1");
+ expect(openTab).not.toHaveBeenCalled();
+ });
+
+ it("passes canonical table context to dynamic menu resolvers", async () => {
+ listPlugins.mockResolvedValue([
+ {
+ compatibility: { compatible: true },
+ manifest: {
+ id: "com.example.table",
+ name: "Table",
+ version: "1.0.0",
+ drivers: [],
+ contributions: [{ type: "context-menu", id: "table.actions", label: "Actions", menu: "table", dynamic: true }],
+ },
+ },
+ ]);
+ invokePlugin.mockResolvedValue({ items: [{ label: "Inspect" }] });
+ const { host } = await mountHost();
+ const items = await host.value.resolveContextMenu(tableNode(), host.value.buildContextMenu(tableNode()));
+ expect(menuLabels(items)).toContain("Inspect");
+ expect(invokePlugin).toHaveBeenCalledWith("com.example.table", "contextMenu/resolve/table.actions", { table: { connectionId: "conn-1", database: "app", table: "users" }, locale: expect.any(String) }, 500);
+ });
+
+ it("restores an inactive plugin connection before retrying an opted-in menu action", async () => {
+ listPlugins.mockResolvedValue([
+ {
+ compatibility: { compatible: true },
+ manifest: {
+ id: "com.example.tunnels",
+ name: "Tunnels",
+ version: "1.0.0",
+ drivers: [],
+ contributions: [{ type: "context-menu", id: "tunnels", label: "Tunnels", menu: "connection", dynamic: true }],
+ },
+ },
+ ]);
+ invokePlugin.mockResolvedValueOnce({ items: [{ label: "Tunnels", children: [{ label: "Start saved", action: { type: "invoke", id: "start-all", reopenConnectionOnMissing: true } }] }] });
+ invokePlugin.mockRejectedValueOnce(new Error("Connection is not active; reopen it from DBX"));
+ invokePlugin.mockResolvedValueOnce({ message: "Started 1 tunnel" });
+ const { host } = await mountHost();
+ const reconnect = vi.spyOn(useConnectionStore(), "reopenPluginConnection").mockResolvedValue(undefined);
+ const items = await host.value.resolveContextMenu(connectionNode(), host.value.buildContextMenu(connectionNode()));
+ items.find((item) => item.label === "Tunnels")?.children?.[0].action?.();
+ await flush();
+ expect(reconnect).toHaveBeenCalledWith("conn-1", "com.example.tunnels");
+ expect(invokePlugin.mock.calls.filter((call) => call[1] === "contextMenu/tunnels")).toHaveLength(2);
+ });
+
+ it("passes plugin ownership to a dynamic connection resolver", async () => {
+ listPlugins.mockResolvedValue([
+ {
+ compatibility: { compatible: true },
+ manifest: {
+ id: "com.example.tunnels",
+ name: "Tunnels",
+ version: "1.0.0",
+ drivers: [],
+ contributions: [{ type: "context-menu", id: "tunnels", label: "Tunnels", menu: "connection", dynamic: true }],
+ },
+ },
+ ]);
+ invokePlugin.mockResolvedValue({ items: [] });
+ const { host } = await mountHost();
+ useConnectionStore().connections = [{ ...connection, db_type: "plugin", plugin_id: "com.example.tunnels" }];
+ await host.value.resolveContextMenu(connectionNode(), host.value.buildContextMenu(connectionNode()));
+ expect(invokePlugin).toHaveBeenCalledWith("com.example.tunnels", "contextMenu/resolve/tunnels", expect.objectContaining({ ownerPluginId: "com.example.tunnels" }), 500);
});
afterEach(() => {
diff --git a/apps/desktop/src/lib/plugins/dynamicContextMenu.spec.ts b/apps/desktop/src/lib/plugins/dynamicContextMenu.spec.ts
new file mode 100644
index 0000000000..116d053096
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/dynamicContextMenu.spec.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from "vitest";
+import { parseDynamicMenuResponse, renderDynamicMenuEntries } from "./dynamicContextMenu";
+
+describe("dynamic plugin context menus", () => {
+ it("renders a state-dependent native submenu and dispatches only validated actions", () => {
+ const entries = parseDynamicMenuResponse({
+ items: [
+ {
+ label: "Tunnels",
+ children: [
+ { label: "Manage", action: { type: "open-workbench", workbench: "ssh.tunnels", presentation: "dialog" } },
+ { label: "Start saved", action: { type: "invoke", id: "start-all" } },
+ { label: "Hidden", visible: false },
+ ],
+ },
+ ],
+ });
+ expect(entries).not.toBeNull();
+ const activate = vi.fn();
+ const items = renderDynamicMenuEntries(entries!, activate);
+ expect(items[0].children?.map((child) => child.label)).toEqual(["Manage", "Start saved"]);
+ items[0].children?.[1].action?.();
+ expect(activate).toHaveBeenCalledWith({ type: "invoke", id: "start-all" }, "Start saved");
+ items[0].children?.[0].action?.();
+ expect(activate).toHaveBeenCalledWith({ type: "open-workbench", workbench: "ssh.tunnels", presentation: "dialog" }, "Manage");
+ });
+
+ it("rejects nested menus, arbitrary methods, invalid types and oversized responses", () => {
+ expect(parseDynamicMenuResponse({ items: [{ label: "Parent", children: [{ label: "Nested", children: [] }] }] })).toBeNull();
+ expect(parseDynamicMenuResponse({ items: [{ label: "Run", action: { type: "invoke", method: "arbitrary" } }] })).toBeNull();
+ expect(parseDynamicMenuResponse({ items: [{ label: "Run", action: { type: "invoke", id: "start", reopenConnectionOnMissing: "yes" } }] })).toBeNull();
+ expect(parseDynamicMenuResponse({ items: [{ label: "Manage", action: { type: "open-workbench", workbench: "ssh.tunnels", presentation: "window" } }] })).toBeNull();
+ expect(parseDynamicMenuResponse({ items: [{ label: "Run", enabled: "yes" }] })).toBeNull();
+ expect(parseDynamicMenuResponse({ items: Array.from({ length: 25 }, () => ({ label: "X" })) })).toBeNull();
+ });
+
+ it("hides empty contributions and disables parents with no visible children", () => {
+ expect(parseDynamicMenuResponse({ items: [] })).toEqual([]);
+ const entries = parseDynamicMenuResponse({ items: [{ label: "Tunnels", children: [{ label: "Hidden", visible: false }] }] });
+ expect(renderDynamicMenuEntries(entries!, vi.fn())).toEqual([expect.objectContaining({ label: "Tunnels", disabled: true, children: [] })]);
+ });
+});
diff --git a/apps/desktop/src/lib/plugins/dynamicContextMenu.ts b/apps/desktop/src/lib/plugins/dynamicContextMenu.ts
new file mode 100644
index 0000000000..4b7378a28b
--- /dev/null
+++ b/apps/desktop/src/lib/plugins/dynamicContextMenu.ts
@@ -0,0 +1,75 @@
+import type { ContextMenuItem } from "@/components/ui/customContextMenuRegistry";
+
+export type DynamicMenuAction = { type: "invoke"; id: string; reopenConnectionOnMissing?: boolean } | { type: "open-workbench"; workbench: string; presentation?: "dialog" };
+
+export interface DynamicMenuEntry {
+ label: string;
+ visible?: boolean;
+ enabled?: boolean;
+ checked?: boolean;
+ action?: DynamicMenuAction;
+ children?: DynamicMenuEntry[];
+}
+
+const IDENTIFIER = /^[a-zA-Z0-9._:/-]{1,256}$/;
+
+function record(value: unknown): Record | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : null;
+}
+
+function parseAction(value: unknown): DynamicMenuAction | undefined {
+ const object = record(value);
+ if (!object) return undefined;
+ if (object.type === "invoke" && typeof object.id === "string" && IDENTIFIER.test(object.id)) {
+ if (object.reopenConnectionOnMissing !== undefined && typeof object.reopenConnectionOnMissing !== "boolean") return undefined;
+ return { type: "invoke", id: object.id, ...(object.reopenConnectionOnMissing === true ? { reopenConnectionOnMissing: true } : {}) };
+ }
+ if (object.type === "open-workbench" && typeof object.workbench === "string" && IDENTIFIER.test(object.workbench)) {
+ if (object.presentation !== undefined && object.presentation !== "dialog") return undefined;
+ return { type: "open-workbench", workbench: object.workbench, ...(object.presentation === "dialog" ? { presentation: "dialog" as const } : {}) };
+ }
+ return undefined;
+}
+
+function parseEntry(value: unknown, depth: number): DynamicMenuEntry | null {
+ const object = record(value);
+ if (!object || typeof object.label !== "string" || !object.label.trim() || object.label.length > 120) return null;
+ if (object.visible !== undefined && typeof object.visible !== "boolean") return null;
+ if (object.enabled !== undefined && typeof object.enabled !== "boolean") return null;
+ if (object.checked !== undefined && typeof object.checked !== "boolean") return null;
+ if (object.action !== undefined && !parseAction(object.action)) return null;
+ if (object.children !== undefined && (depth !== 0 || !Array.isArray(object.children) || object.children.length > 40 || object.action !== undefined)) return null;
+ const children = Array.isArray(object.children) ? object.children.map((child) => parseEntry(child, 1)) : undefined;
+ if (children?.some((child) => child === null)) return null;
+ return {
+ label: object.label.trim(),
+ visible: object.visible as boolean | undefined,
+ enabled: object.enabled as boolean | undefined,
+ checked: object.checked as boolean | undefined,
+ action: parseAction(object.action),
+ children: children as DynamicMenuEntry[] | undefined,
+ };
+}
+
+/** Reject malformed or oversized sidecar responses before they reach the native menu. */
+export function parseDynamicMenuResponse(value: unknown): DynamicMenuEntry[] | null {
+ const object = record(value);
+ if (!object || !Array.isArray(object.items) || object.items.length > 24) return null;
+ const items = object.items.map((item) => parseEntry(item, 0));
+ return items.some((item) => item === null) ? null : (items as DynamicMenuEntry[]);
+}
+
+export function renderDynamicMenuEntries(entries: DynamicMenuEntry[], activate: (action: DynamicMenuAction, label: string) => void): ContextMenuItem[] {
+ return entries
+ .filter((entry) => entry.visible !== false)
+ .map((entry) => {
+ const children = entry.children ? renderDynamicMenuEntries(entry.children, activate) : undefined;
+ return {
+ label: entry.label,
+ disabled: entry.enabled === false || (children !== undefined && children.length === 0),
+ checked: entry.checked,
+ action: entry.action ? () => activate(entry.action!, entry.label) : undefined,
+ children,
+ };
+ });
+}
diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts b/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
index 408cd54bea..40949e5415 100644
--- a/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
@@ -15,6 +15,7 @@ export interface SidebarTreeRuntimeGeneration {
export interface SidebarTreeRuntimeHost {
buildContextMenu(node: TreeNode): ContextMenuItem[];
+ resolveContextMenu(node: TreeNode, staticItems: ContextMenuItem[]): Promise | ContextMenuItem[];
handleRowClick(node: TreeNode, clickDetail: number): void;
handleRowDoubleClick(node: TreeNode, event: MouseEvent): void;
handleRowKeydown(node: TreeNode, event: KeyboardEvent): void;
@@ -37,6 +38,7 @@ export interface SidebarTreeRuntime {
beginAction(): SidebarTreeRuntimeGeneration;
isCurrent(token: SidebarTreeRuntimeGeneration): boolean;
buildContextMenu(node: TreeNode): ContextMenuItem[];
+ resolveContextMenu(node: TreeNode, staticItems: ContextMenuItem[]): Promise | ContextMenuItem[];
handleRowClick(node: TreeNode, clickDetail: number): void;
handleRowDoubleClick(node: TreeNode, event: MouseEvent): void;
handleRowKeydown(node: TreeNode, event: KeyboardEvent): void;
@@ -91,6 +93,9 @@ export function createSidebarTreeRuntime(): SidebarTreeRuntime {
menuBuilds += 1;
return currentHost()?.buildContextMenu(node) ?? [];
},
+ resolveContextMenu(node, staticItems) {
+ return currentHost()?.resolveContextMenu(node, staticItems) ?? staticItems;
+ },
handleRowClick(node, clickDetail) {
currentHost()?.handleRowClick(node, clickDetail);
},
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index c65b6e4bfd..741ed1f497 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -506,6 +506,7 @@ export interface PluginContextMenuContribution {
description?: string;
icon?: string;
menu: PluginContextMenuTarget;
+ dynamic?: boolean;
action?: PluginOpenWorkbenchTarget;
}
diff --git a/crates/dbx-plugin-runtime/src/plugins/manifest.rs b/crates/dbx-plugin-runtime/src/plugins/manifest.rs
index cd8076b786..fd9a5a42ca 100644
--- a/crates/dbx-plugin-runtime/src/plugins/manifest.rs
+++ b/crates/dbx-plugin-runtime/src/plugins/manifest.rs
@@ -737,6 +737,9 @@ pub struct PluginContextMenuContribution {
/// Menu surface the item belongs to: `connection` or `table`.
#[serde(default)]
pub menu: String,
+ /// Resolve native items through `contextMenu/resolve/` on each menu open.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub dynamic: bool,
/// Optional host-handled action. When absent, the legacy backend entrypoint is required.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option,
@@ -1433,6 +1436,9 @@ fn validate_contributions(
} else if !has_backend {
errors.push(format!("Context menu contribution '{id}' requires a backend entrypoint"));
}
+ if menu.dynamic && !has_backend {
+ errors.push(format!("Dynamic context menu contribution '{id}' requires a backend entrypoint"));
+ }
}
PluginContribution::FilesystemProvider(provider) => {
validate_required_text(&provider.label, &format!("Filesystem provider '{id}' label"), errors);
@@ -2652,6 +2658,36 @@ mod tests {
Ok(())
}
+ #[test]
+ fn dynamic_context_menu_requires_backend() -> Result<(), Box> {
+ let plugin_dir = tempfile::tempdir()?;
+ let context_menu: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "context-menu",
+ "id": "sample.tunnels",
+ "label": "Tunnels",
+ "menu": "connection",
+ "dynamic": true,
+ "action": { "type": "open-workbench", "workbench": "sample.main" }
+ }))?;
+ let workbench: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "workbench", "id": "sample.main", "label": "Sample"
+ }))?;
+ let mut errors = Vec::new();
+ validate_contributions(&[workbench, context_menu], false, true, plugin_dir.path(), &mut errors);
+ assert!(
+ errors.iter().any(|error| error
+ .contains("Dynamic context menu contribution 'sample.tunnels' requires a backend entrypoint")),
+ "{errors:?}"
+ );
+ let context_menu: PluginContribution = serde_json::from_value(serde_json::json!({
+ "type": "context-menu", "id": "sample.tunnels", "label": "Tunnels", "menu": "connection", "dynamic": true
+ }))?;
+ let mut errors = Vec::new();
+ validate_contributions(&[context_menu], true, false, plugin_dir.path(), &mut errors);
+ assert!(errors.is_empty(), "{errors:?}");
+ Ok(())
+ }
+
#[test]
fn rejects_dangling_and_invalid_context_menu_actions() -> Result<(), Box> {
let plugin_dir = tempfile::tempdir()?;
diff --git a/plugins/README.md b/plugins/README.md
index 72933b0eb3..ee317f5fb2 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -478,6 +478,24 @@ A context-menu item can instead declare a host-handled Workbench action:
The `workbench` reference must identify a `workbench` contribution in the same plugin manifest. This declarative action is resolved by the host and does not invoke the plugin backend.
+To provide state-dependent items and one level of native submenus, set `"dynamic": true` on a `context-menu` contribution. This requires a backend entrypoint. On each right-click, DBX calls `contextMenu/resolve/` with the same non-secret `{ connection }` or `{ table }` envelope used by legacy actions, plus the current `locale`; connection menus also include `ownerPluginId` when the connection belongs to a plugin. A plugin can return an empty menu for connections it does not own. Return `{ "items": [...] }`; returning an empty array hides the contribution. For example:
+
+```json
+{
+ "items": [
+ {
+ "label": "Tunnels",
+ "children": [
+ { "label": "Manage port forwards", "action": { "type": "open-workbench", "workbench": "ssh.tunnels", "presentation": "dialog" } },
+ { "label": "Start saved tunnels", "action": { "type": "invoke", "id": "start-all", "reopenConnectionOnMissing": true } }
+ ]
+ }
+ ]
+}
+```
+
+Each item accepts `label`, optional `visible`, `enabled`, `checked`, and either `action` or `children`. Children may not contain another submenu. An `invoke` action calls the declared contribution's existing `contextMenu/` backend method with the original envelope plus `itemId`; the host never executes an arbitrary method supplied by the resolver. For connection items, `reopenConnectionOnMissing: true` retries once after DBX restores that plugin connection when the backend reports `Connection is not active`; omit it for actions that do not need an open connection. An `open-workbench` action must target a workbench declared by the same plugin. Dynamic menu items may add `"presentation": "dialog"` to that action to show the workbench in a modal over DBX; without it the workbench opens in a tab. The host limits response size and resolution time; invalid or failed responses contribute no items. Existing static context-menu contributions continue to work unchanged.
+
For legacy entries without `action`, clicking a connection item dispatches `contextMenu/` with the existing non-secret connection summary (`{ id, dbType, name, database }`) under `connection`. Clicking a table item uses the same backend method and dispatches:
```json
diff --git a/plugins/manifest.schema.json b/plugins/manifest.schema.json
index 646dfb2dae..29e4f1a828 100644
--- a/plugins/manifest.schema.json
+++ b/plugins/manifest.schema.json
@@ -349,6 +349,7 @@
"description": { "type": "string" },
"icon": { "$ref": "#/$defs/assetPath" },
"menu": { "enum": ["connection", "table"] },
+ "dynamic": { "type": "boolean", "description": "Resolve native menu items through contextMenu/resolve/ when the menu opens." },
"action": { "$ref": "#/$defs/contextMenuAction" }
}
},