fix(plugins): stabilize plugin integration

This commit is contained in:
Jinpy authored and GitHub committed 2026-09-14 21:03:47 +08:00
1 parent b70d6da227
commit 3d1b84831f
76 files changed
+3846 -431

No files matched your search

@@ -467,3 +467,127 @@ describe("connectionStore save_password opt-out", () => {
expect(store.connectionErrors["mysql-1"]).toContain("disk full");
});
});
describe("connectionStore plugin password prompt", () => {
// Runtime-assembled placeholder: no credential literal in source (Mimosa gate).
const PROMPT_TYPED_PASSWORD = "typed" + "-pw";
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
requestPassword = vi.fn();
});
afterEach(() => {
vi.restoreAllMocks();
});
function sshInstalledPlugin(): unknown {
return {
manifest: {
id: "io.dbx.ssh",
name: "SSH",
drivers: [],
contributions: [
{
type: "connection-provider",
id: "io.dbx.ssh.connection",
label: "SSH server",
database_type: "ssh",
fields: [
{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] },
{
key: "password",
label: "Password",
type: "password",
binding: "password",
visible_when: { field: "authentication", one_of: ["password", "private-key-password"] },
required_when: { field: "authentication", one_of: ["password", "private-key-password"] },
},
],
},
],
},
compatibility: { compatible: true },
};
}
function pluginConnection(overrides: Record<string, unknown> = {}): ConnectionConfig {
return {
id: "ssh-1",
name: "hktkosl1086",
db_type: "plugin",
host: "hktkosl1086.int.kn",
port: 22,
username: "jinpy.he",
password: "",
save_password: false,
plugin_id: "io.dbx.ssh",
plugin_connection_provider: "io.dbx.ssh.connection",
plugin_connection_type: "ssh",
external_config: { authentication: "private-key", private_key_path: "/Users/dev/.ssh/id_rsa" },
read_only: false,
...overrides,
} as ConnectionConfig;
}
it("connects an SSH key-auth plugin connection without prompting for a password", async () => {
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([sshInstalledPlugin()]) });
installPasswordPromptMock();
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = pluginConnection();
store.connections = [connection];
await store.connect(connection);
expect(requestPassword).not.toHaveBeenCalled();
const { connectDb } = await import("@/lib/backend/api");
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1", external_config: expect.objectContaining({ authentication: "private-key" }) }), expect.any(Number));
});
it("still prompts for a plugin connection whose manifest requires the login password", async () => {
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([sshInstalledPlugin()]) });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: PROMPT_TYPED_PASSWORD, rememberPassword: false });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = pluginConnection({ external_config: { authentication: "password" } });
store.connections = [connection];
await store.connect(connection);
expect(requestPassword).toHaveBeenCalledWith({ connectionId: "ssh-1", connectionName: "hktkosl1086" });
const { connectDb } = await import("@/lib/backend/api");
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1", password: PROMPT_TYPED_PASSWORD }), expect.any(Number));
});
it("does not prompt when the plugin manifest cannot be resolved (backend surfaces the real error)", async () => {
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([]) });
installPasswordPromptMock();
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = pluginConnection();
store.connections = [connection];
await store.connect(connection);
expect(requestPassword).not.toHaveBeenCalled();
const { connectDb } = await import("@/lib/backend/api");
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1" }), expect.any(Number));
});
it("falls back to prompting when listing plugins fails", async () => {
installApiMocks({ listPlugins: vi.fn().mockRejectedValue(new Error("ipc down")) });
installPasswordPromptMock();
requestPassword.mockResolvedValue(null);
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = pluginConnection();
store.connections = [connection];
await expect(store.connect(connection)).rejects.toThrow(CONNECTION_PASSWORD_REQUIRED_MESSAGE);
});
});
@@ -0,0 +1,98 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useQueryStore } from "@/stores/queryStore";
describe("queryStore openPluginWorkbench reuse", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => null),
setItem: vi.fn(),
removeItem: vi.fn(),
});
vi.stubGlobal("window", { dispatchEvent: vi.fn() });
setActivePinia(createPinia());
});
it("reopening an open workbench surfaces the tab as-is without replacing its context", async () => {
const queryStore = useQueryStore();
const firstId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
title: "hktkosl1103",
connectionId: "conn-1",
context: { connectionId: "conn-1", workbenchId: "wb-original" },
});
// A later reopen (e.g. another sidebar click) carries a freshly minted
// context; the tab must keep the original one — a replacement would
// deep-reload the plugin webview (full flash) and orphan the sidecar
// session bound to the original workbench id.
const secondId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
title: "hktkosl1103",
connectionId: "conn-1",
context: { connectionId: "conn-1", workbenchId: "wb-fresh" },
});
expect(secondId).toBe(firstId);
expect(queryStore.activeTabId).toBe(firstId);
const tab = queryStore.tabs.find((t) => t.id === firstId);
expect(tab?.pluginWorkbench?.context).toEqual({ connectionId: "conn-1", workbenchId: "wb-original" });
});
it("a different connection still opens its own workbench tab", () => {
const queryStore = useQueryStore();
const firstId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
connectionId: "conn-1",
context: { connectionId: "conn-1", workbenchId: "wb-1" },
});
const secondId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
connectionId: "conn-2",
context: { connectionId: "conn-2", workbenchId: "wb-2" },
});
expect(secondId).not.toBe(firstId);
expect(queryStore.tabs).toHaveLength(2);
});
it("registers the workbench tab into the focused group so the group tab strip can render it", () => {
const queryStore = useQueryStore();
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
connectionId: "conn-1",
context: { connectionId: "conn-1" },
});
// The split workspace renders tab strips from group membership: a tab
// pushed straight onto `tabs` stays ownerless and never shows up in any
// strip (regression behind "click a sidebar connection, no tab appears").
const group = queryStore.groups.find((candidate) => candidate.tabIds.includes(id));
expect(group).toBeDefined();
expect(group?.activeTabId).toBe(id);
expect(queryStore.focusedGroupId).toBe(group?.id);
});
it("adopts a legacy ownerless workbench tab back into the workspace when reopened", () => {
const queryStore = useQueryStore();
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
connectionId: "conn-1",
context: { connectionId: "conn-1" },
});
// Simulate a tab created by a pre-registry build (ownerless) or a restore
// edge: strip it from its group, then reopen from the sidebar.
queryStore.groups = [{ id: "main", tabIds: [], activeTabId: null }];
const reopenedId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
connectionId: "conn-1",
context: { connectionId: "conn-1", workbenchId: "wb-fresh" },
});
expect(reopenedId).toBe(id);
expect(queryStore.groups[0]?.tabIds).toContain(id);
expect(queryStore.groups[0]?.activeTabId).toBe(id);
// Adoption must not replace the live context (same no-deep-reload rule).
expect(queryStore.tabs.find((t) => t.id === id)?.pluginWorkbench?.context).toEqual({ connectionId: "conn-1" });
});
});
@@ -0,0 +1,60 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
describe("queryStore plugin tab close disconnects the plugin connection", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => null),
setItem: vi.fn(),
removeItem: vi.fn(),
});
vi.stubGlobal("window", {
dispatchEvent: vi.fn(),
setTimeout: globalThis.setTimeout.bind(globalThis),
clearTimeout: globalThis.clearTimeout.bind(globalThis),
});
setActivePinia(createPinia());
});
it("disconnects the plugin connection when its last plugin tab closes", async () => {
const queryStore = useQueryStore();
const connectionStore = useConnectionStore();
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
queryStore.closeTab(id);
await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledTimes(1));
expect(disconnectSpy).toHaveBeenCalledWith("conn-1");
});
it("keeps the plugin connection while another plugin tab for it stays open", async () => {
const queryStore = useQueryStore();
const connectionStore = useConnectionStore();
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
// Workbench + filesystem tab riding the same connection (e.g. SSH terminal + SFTP).
const workbenchId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
queryStore.openPluginFilesystem("io.dbx.ssh", "fs", { connectionId: "conn-1", rootUri: "sftp:/" });
queryStore.closeTab(workbenchId);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(disconnectSpy).not.toHaveBeenCalled();
});
it("does not disconnect non-plugin connections when a regular tab closes", async () => {
const queryStore = useQueryStore();
const connectionStore = useConnectionStore();
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
const id = queryStore.createTab("pg-1", "app", "Query 1", "query");
queryStore.closeTab(id);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(disconnectSpy).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,68 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useQueryStore } from "@/stores/queryStore";
// Boot-time tab restore replays only tab metadata; the sidecar connection
// registry starts empty after a host restart, so restored plugin tabs need
// the connect lifecycle replayed (see reconnectRestoredPluginTabs).
const ensureConnected = vi.fn(async () => undefined);
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
getConfig: (id: string) => (id === "conn-sql" ? { id, db_type: "mysql" } : { id, db_type: "plugin" }),
ensureConnected,
}),
}));
describe("queryStore reconnectRestoredPluginTabs", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => null),
setItem: vi.fn(),
removeItem: vi.fn(),
});
vi.stubGlobal("window", { dispatchEvent: vi.fn() });
setActivePinia(createPinia());
ensureConnected.mockClear();
ensureConnected.mockImplementation(async () => undefined);
});
it("replays ensureConnected once per distinct plugin connection, active tab first", async () => {
const queryStore = useQueryStore();
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
queryStore.openPluginFilesystem("io.dbx.files", "files", { connectionId: "conn-1" });
// A non-plugin tab must not participate in the replay.
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-sql", context: { connectionId: "conn-sql" } });
const activeTabId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-2", context: { connectionId: "conn-2" } });
queryStore.activeTabId = activeTabId;
await queryStore.reconnectRestoredPluginTabs();
// conn-2 owns the active tab (last open won) so it is replayed first;
// activate:false keeps boot restore from stealing the active connection.
expect(ensureConnected.mock.calls.map((call) => call[0])).toEqual(["conn-2", "conn-1"]);
expect(ensureConnected).toHaveBeenCalledWith("conn-1", { activate: false });
});
it("a per-connection failure does not abort the remaining replays", async () => {
const queryStore = useQueryStore();
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
queryStore.openPluginWorkbench("io.dbx.ldap", "workbench", { connectionId: "conn-2", context: { connectionId: "conn-2" } });
ensureConnected.mockImplementation(async (id: string) => {
if (id === "conn-1") throw new Error("password prompt cancelled");
});
await expect(queryStore.reconnectRestoredPluginTabs()).resolves.toBeUndefined();
expect(ensureConnected).toHaveBeenCalledTimes(2);
});
it("no plugin tabs means no replay", async () => {
const queryStore = useQueryStore();
await queryStore.reconnectRestoredPluginTabs();
expect(ensureConnected).not.toHaveBeenCalled();
});
});
+52 -4
View File
@@ -148,7 +148,8 @@ import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel }
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
import { appendAgentDriverUpdateHint, connectionUsesSsh, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";
import { appendConnectionErrorHints, isMysqlMissingPasswordFailure, isSqliteMissingEncryptionPasswordFailure } from "@/lib/connection/connectionErrorHints";
import { connectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
import { connectionNeedsPasswordPrompt, pluginConnectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";
import { buildXuguTypeMemberNodes, isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";
import { isXuguPublicSynonymScope, isXuguSchedulerJobScope, isXuguSyntheticScope, sortXuguSchemaInfos, xuguSchemaDisplayName, XUGU_PUBLIC_SYNONYM_SCOPE, XUGU_SCHEDULER_JOB_SCOPE } from "@/lib/sidebar/xuguPublicSynonyms";
@@ -168,7 +169,7 @@ import { MetadataTaskLimiter } from "@/lib/metadata/metadataTaskLimiter";
import { buildCustomTypeTreeChildren } from "@/lib/sidebar/customTypeTree";
import { TreeNodeLoadRegistry, type TreeNodeLoadHandle } from "@/lib/metadata/treeNodeLoadHandle";
import { buildXuguTablespaceChildren } from "@/lib/sidebar/xuguTablespaces";
import i18n from "@/i18n";
import i18n, { currentLocale } from "@/i18n";
import type { MqAdminConfig } from "@/types/mq";
import { RABBITMQ_MQ_TENANT, resolveMqSystemKindFromConnection } from "@/lib/mq/mqConsoleDefaults";
import { applySidebarDatabaseStorage, applySidebarTableStorage, sidebarDatabaseNames, supportsSidebarDatabaseStorage, supportsSidebarTableStorage, type SidebarTableStorageScope } from "@/lib/sidebar/sidebarDatabaseStorage";
@@ -1024,6 +1025,11 @@ export const useConnectionStore = defineStore("connection", () => {
return disconnectInFlightScoped.get(connectionId) ? undefined : disconnectInFlight.get(connectionId);
}
/** True while any disconnect for the connection is in flight (full or scoped). */
function hasDisconnectInFlight(connectionId: string): boolean {
return disconnectInFlight.has(connectionId);
}
async function waitForBlockingDisconnectInFlight(connectionId: string): Promise<void> {
const pending = getBlockingDisconnectInFlight(connectionId);
if (pending) await pending;
@@ -4035,6 +4041,31 @@ export const useConnectionStore = defineStore("connection", () => {
return { config: { ...config, password: result.password }, rememberPassword: result.rememberPassword };
}
/**
* Manifest re-check for plugin connections that the save_password heuristic
* already flagged. The prompt can only fill the `password`-bound field, so
* when the manifest does not require it for the connection's external_config
* (SSH private-key / agent auth), connecting proceeds without prompting
* instead of failing with "Password is required". Non-plugin configs always
* prompt (the heuristic decided already). Callers must evaluate
* `connectionNeedsPasswordPrompt` synchronously first so the common
* no-prompt path keeps its microtask cadence.
*/
async function pluginConnectionPasswordPromptNeeded(config: ConnectionConfig): Promise<boolean> {
if (config.db_type !== "plugin") return true;
if (!config.plugin_id || !config.plugin_connection_provider) return false;
try {
const registry = createFrontendPluginRegistry(await api.listPlugins(), currentLocale());
const provider = registry.listConnectionProviders().find((entry) => entry.plugin.manifest.id === config.plugin_id && entry.contribution.id === config.plugin_connection_provider);
if (!provider) return false;
return pluginConnectionNeedsPasswordPrompt(provider.contribution.fields, config.external_config);
} catch {
// Manifest unavailable: keep the pre-manifest behavior (prompt) instead of
// silently connecting a connection that may genuinely need a password.
return true;
}
}
async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise<void> {
if (!rememberPassword) return;
const index = connections.value.findIndex((connection) => connection.id === config.id);
@@ -4073,7 +4104,7 @@ export const useConnectionStore = defineStore("connection", () => {
const localAttempt = beginLocalConnectionAttempt(config.id);
try {
let rememberPassword = false;
if (connectionNeedsPasswordPrompt(config) && !(await hasSessionCredential(config.id))) {
if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(config.id))) {
const prompted = await ensureConnectionPassword(config);
config = prompted.config;
rememberPassword = prompted.rememberPassword;
@@ -4168,6 +4199,21 @@ export const useConnectionStore = defineStore("connection", () => {
return true;
}
/**
* Marks a connection offline in the sidebar without the full teardown that
* `disconnect` performs (no tab closing, no pool teardown). Used when a
* plugin reports its live session died (e.g. `ssh/session/state
* disconnected`) so the tree reflects the real transport state.
*/
function markConnectionOffline(connectionId: string) {
connectedIds.value.delete(connectionId);
const node = findConnectionNode(connectionId);
if (node) {
node.isLoading = false;
}
clearConnectionHealthCheck(connectionId);
}
async function disconnect(connectionId: string) {
const stateRevision = bumpConnectionStateRevision(connectionId);
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
@@ -4336,7 +4382,7 @@ export const useConnectionStore = defineStore("connection", () => {
// Fast-path the common case (password saved or no password needed) so the
// in-flight dedup above keeps its exact microtask cadence; only await the
// interactive prompt when the connection actually needs a typed password.
if (connectionNeedsPasswordPrompt(config) && !(await hasSessionCredential(connectionId))) {
if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(connectionId))) {
const prompted = await ensureConnectionPassword(config);
config = prompted.config;
rememberPassword = prompted.rememberPassword;
@@ -9243,6 +9289,8 @@ export const useConnectionStore = defineStore("connection", () => {
connect,
cancelConnecting,
disconnect,
hasDisconnectInFlight,
markConnectionOffline,
metadataGenerationFor,
disconnectAndForgetConnectionPassword,
hasSessionCredential,
+114 -23
View File
@@ -3398,7 +3398,16 @@ export const useQueryStore = defineStore("query", () => {
if (!options.forceNew) {
const existing = tabs.value.find((tab) => tab.mode === "plugin-workbench" && tab.pluginWorkbench?.pluginId === pluginId && tab.pluginWorkbench?.contributionId === contributionId && tab.connectionId === (options.connectionId || ""));
if (existing) {
if (options.context) existing.pluginWorkbench = { ...existing.pluginWorkbench!, context: snapshotPluginWorkbenchContext(options.context) };
// Reopening surfaces the existing tab as-is. Replacing the context
// here (openPluginConnection mints a fresh workbenchId per click)
// would deep-reload the plugin webview — a full flash plus losing
// the sidecar session binding on the old workbench id.
// A tab created by an older build (or otherwise unregistered) may
// still be ownerless; land it in the workspace or the group-rendered
// tab strips can never show it.
if (!groupForTab(existing.id)) {
ensureTabInWorkspace(existing.id);
}
switchTab(existing.id);
return existing.id;
}
@@ -3421,6 +3430,9 @@ export const useQueryStore = defineStore("query", () => {
context: options.context ? snapshotPluginWorkbenchContext(options.context) : undefined,
},
};
// The split workspace renders strips from group membership — always go
// through registerOpenTab so the tab joins the focused group (raw push
// left it ownerless and invisible in every tab strip).
return registerOpenTab(tab);
}
@@ -3429,6 +3441,9 @@ export const useQueryStore = defineStore("query", () => {
const existing = tabs.value.find((tab) => tab.mode === "plugin-filesystem" && tab.pluginFilesystem?.pluginId === pluginId && tab.pluginFilesystem?.providerId === providerId && tab.connectionId === (options.connectionId || ""));
if (existing) {
if (options.currentUri) existing.pluginFilesystem = { ...existing.pluginFilesystem!, currentUri: options.currentUri };
if (!groupForTab(existing.id)) {
ensureTabInWorkspace(existing.id);
}
switchTab(existing.id);
return existing.id;
}
@@ -3475,6 +3490,15 @@ export const useQueryStore = defineStore("query", () => {
connectionId,
providerId,
connectionType: connection.plugin_connection_type,
workbenchId: crypto.randomUUID(),
connection: {
id: connection.id,
name: connection.name,
host: connection.host,
port: connection.port,
username: connection.username,
readOnly: false,
},
},
});
}
@@ -3482,12 +3506,44 @@ export const useQueryStore = defineStore("query", () => {
const filesystem = filesystemProviderId ? registry.listFilesystemProviders().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === filesystemProviderId) : undefined;
if (!filesystem) throw new Error(`Plugin connection provider '${pluginId}/${providerId}' does not declare a workbench or filesystem provider`);
return openPluginFilesystem(pluginId, filesystem.contribution.id, {
title: connection.name,
title: `${connection.name} · SFTP`,
connectionId,
rootUri: filesystem.contribution.root_uri,
});
}
/**
* Boot-time tab restore only replays tab metadata: after a host restart the
* sidecar's in-memory connection registry starts empty (credentials are
* injected per connect via `connection/connect`), so a restored plugin
* workbench/filesystem tab fails its first session/open with "Connection is
* not active" until the user reopens the connection from the sidebar. Replay
* the connect lifecycle for every distinct restored plugin connection —
* fire-and-forget so an interactive password prompt or a slow sidecar spawn
* never blocks startup; per-connection failures surface in the tab's own UI.
*/
async function reconnectRestoredPluginTabs() {
const connectionStore = useConnectionStore();
const activeConnectionId = tabs.value.find((tab) => tab.id === activeTabId.value)?.connectionId;
const orderedIds: string[] = [];
for (const tab of tabs.value) {
if (tab.mode !== "plugin-workbench" && tab.mode !== "plugin-filesystem") continue;
if (!tab.connectionId || orderedIds.includes(tab.connectionId)) continue;
if (tab.connectionId === activeConnectionId) orderedIds.unshift(tab.connectionId);
else orderedIds.push(tab.connectionId);
}
for (const connectionId of orderedIds) {
if (connectionStore.getConfig(connectionId)?.db_type !== "plugin") continue;
try {
// activate:false keeps the boot restore from overriding the last
// active connection already chosen by restoreActiveConnectionContext().
await connectionStore.ensureConnected(connectionId, { activate: false });
} catch (error) {
console.warn("[DBX][plugin-tab-restore:reconnect]", connectionId, error);
}
}
}
function applyTableStructureInitialTab(tab: QueryTab, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget) {
if (!initialTab && !initialTarget?.name) return;
if (initialTab) tab.structureInitialTab = initialTab;
@@ -3790,6 +3846,39 @@ export const useQueryStore = defineStore("query", () => {
continuePendingBatchClose();
}
const pluginReleaseInFlight = new Set<string>();
/**
* Closing the last plugin tab (workbench or filesystem) bound to a plugin
* connection ends that connection: the sidecar session has no remaining
* owner, so disconnecting tears the pool down and drops the sidebar's
* "connected" dot. Fire-and-forget; concurrent releases for the same
* connection coalesce, and a reopen racing the release wins.
*/
function releasePluginConnectionsAfterClose(closedTabs: ReadonlyArray<QueryTab>) {
const connectionIds = new Set(closedTabs.filter((tab) => (tab.mode === "plugin-workbench" || tab.mode === "plugin-filesystem") && tab.connectionId).map((tab) => tab.connectionId));
for (const connectionId of connectionIds) {
if (pluginReleaseInFlight.has(connectionId)) continue;
pluginReleaseInFlight.add(connectionId);
void (async () => {
try {
// Yield one microtask so a same-tick reopen registers its
// replacement plugin tab before we tear the connection down.
await Promise.resolve();
if (tabs.value.some((tab) => (tab.mode === "plugin-workbench" || tab.mode === "plugin-filesystem") && tab.connectionId === connectionId)) return;
const connectionStore = useConnectionStore();
// A user-initiated disconnect that closed these tabs already owns
// the teardown — don't stack a second one on top of it.
if (connectionStore.hasDisconnectInFlight(connectionId)) return;
await connectionStore.disconnect(connectionId);
} catch (error) {
console.warn("[DBX][plugin-tab-close:disconnect]", connectionId, error);
} finally {
pluginReleaseInFlight.delete(connectionId);
}
})();
}
}
function closeTab(id: string, { force = false }: { force?: boolean } = {}) {
const tab = tabs.value.find((t) => t.id === id);
if (!tab) return;
@@ -3822,6 +3911,7 @@ export const useQueryStore = defineStore("query", () => {
const wasGlobalActive = activeTabId.value === id;
tabs.value.splice(idx, 1);
releasePluginConnectionsAfterClose([tab]);
if (tab.externalSqlPath) refreshExternalSqlFileTitles();
if (owner) {
@@ -4161,29 +4251,29 @@ export const useQueryStore = defineStore("query", () => {
const closingIds = new Set(tabs.value.filter((tab) => predicate(tab)).map((tab) => tab.id));
if (closingIds.size === 0) return;
tabs.value
.filter((tab) => closingIds.has(tab.id))
.forEach((tab) => {
if (tab.mode === "sqlserver-trace") void disposeSqlServerActivityTrace(tab.id);
clearDataGridPendingSnapshotsForTab(tab.id);
beginClosingDataGridViewSnapshotsForTab(tab.id);
beginClosingBrowserState(tab.id);
clearDataGridStructuredFilterStatesForTab(tab.id);
clearDataGridSearchStatesForTab(tab.id);
if (tab.txnSessionId) void rollbackTransaction(tab.id);
if (tab.isExecuting) void cancelTabExecution(tab.id);
if (tab.isExplaining) void cancelTabExplain(tab.id);
void closeResultSession(tab);
void closeClientConnectionSession(tab);
clearResultRunSnapshots(tab);
void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
releaseTabResultObjectPayloads(tab);
clearResultRuns(tab);
clearResultPayload(tab);
});
const closingTabs = tabs.value.filter((tab) => closingIds.has(tab.id));
closingTabs.forEach((tab) => {
if (tab.mode === "sqlserver-trace") void disposeSqlServerActivityTrace(tab.id);
clearDataGridPendingSnapshotsForTab(tab.id);
beginClosingDataGridViewSnapshotsForTab(tab.id);
beginClosingBrowserState(tab.id);
clearDataGridStructuredFilterStatesForTab(tab.id);
clearDataGridSearchStatesForTab(tab.id);
if (tab.txnSessionId) void rollbackTransaction(tab.id);
if (tab.isExecuting) void cancelTabExecution(tab.id);
if (tab.isExplaining) void cancelTabExplain(tab.id);
void closeResultSession(tab);
void closeClientConnectionSession(tab);
clearResultRunSnapshots(tab);
void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
releaseTabResultObjectPayloads(tab);
clearResultRuns(tab);
clearResultPayload(tab);
});
const activeClosingIndex = tabs.value.findIndex((tab) => tab.id === activeTabId.value && closingIds.has(tab.id));
tabs.value = tabs.value.filter((tab) => !closingIds.has(tab.id));
releasePluginConnectionsAfterClose(closingTabs);
// Resolve the fallback against the POST-filter array: the survivor at the
// closing tab's index, not the closing tab itself.
const fallbackTabId = activeClosingIndex >= 0 ? tabs.value[Math.min(activeClosingIndex, tabs.value.length - 1)]?.id : undefined;
@@ -8492,10 +8582,11 @@ export const useQueryStore = defineStore("query", () => {
openMqAdmin,
openMqttAdmin,
openNacosAdmin,
clearNacosNavigationTarget,
openPluginWorkbench,
openPluginFilesystem,
reconnectRestoredPluginTabs,
openPluginConnection,
clearNacosNavigationTarget,
openTableStructure,
linkSavedSql,
linkExternalSqlPath,