Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(connection): block passive reconnect for user-closed connections

Abeautifulsnow20fc49d7db92
diff --git a/apps/desktop/src/components/admin/DamengJobAdmin.vue b/apps/desktop/src/components/admin/DamengJobAdmin.vue
index 66ce70b365..66a134a59b 100644
--- a/apps/desktop/src/components/admin/DamengJobAdmin.vue
+++ b/apps/desktop/src/components/admin/DamengJobAdmin.vue
@@ -95,7 +95,7 @@ const detailColumns = computed(() => {
const canCreateJob = computed(() => createName.value.trim() && createStepName.value.trim() && createScheduleName.value.trim() && createCommand.value.trim());
async function ensureConnection() {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
}
async function loadJobs() {
diff --git a/apps/desktop/src/components/admin/DamengRoleAdmin.vue b/apps/desktop/src/components/admin/DamengRoleAdmin.vue
index e63ffedc42..b4160d61f0 100644
--- a/apps/desktop/src/components/admin/DamengRoleAdmin.vue
+++ b/apps/desktop/src/components/admin/DamengRoleAdmin.vue
@@ -107,7 +107,7 @@ const availablePrivilegesForGrant = computed(() => {
const canCreateRole = computed(() => createRoleName.value.trim() !== "");
async function ensureConnection() {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
}
function isDdlAnyPrivDenied(message: string): boolean {
diff --git a/apps/desktop/src/components/admin/DamengUserAdmin.vue b/apps/desktop/src/components/admin/DamengUserAdmin.vue
index 1679be347d..60814cc203 100644
--- a/apps/desktop/src/components/admin/DamengUserAdmin.vue
+++ b/apps/desktop/src/components/admin/DamengUserAdmin.vue
@@ -180,7 +180,7 @@ const canCreateUser = computed(() => createUsername.value.trim() !== "" && creat
const canChangePassword = computed(() => passwordValue.value !== "" && passwordValue.value === passwordConfirm.value);
async function ensureConnection() {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
}
async function refreshConnectionTree() {
diff --git a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
index 2eba522aed..391019da3c 100644
--- a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
+++ b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue
@@ -192,7 +192,7 @@ function userDetail(user: DatabaseUserIdentity): string {
}
async function ensureConnection() {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
}
async function loadUsers() {
diff --git a/apps/desktop/src/components/admin/MySqlDashboard.vue b/apps/desktop/src/components/admin/MySqlDashboard.vue
index 8a0453ef85..eb5942687a 100644
--- a/apps/desktop/src/components/admin/MySqlDashboard.vue
+++ b/apps/desktop/src/components/admin/MySqlDashboard.vue
@@ -133,7 +133,7 @@ async function fetchStatus(options: { silent?: boolean } = {}) {
if (!options.silent) loading.value = true;
error.value = "";
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
const result = await api.executeQuery(props.connectionId, "", GLOBAL_STATUS_SQL, undefined, undefined, { maxRows: 2000, clientSessionId: props.clientSessionId });
const sample: StatusSample = { at: Date.now(), status: parseStatusResult(result) };
const next = [...samples.value, sample];
diff --git a/apps/desktop/src/components/admin/PostgresDashboard.vue b/apps/desktop/src/components/admin/PostgresDashboard.vue
index 54a4fad7e1..fe18fb8b8b 100644
--- a/apps/desktop/src/components/admin/PostgresDashboard.vue
+++ b/apps/desktop/src/components/admin/PostgresDashboard.vue
@@ -146,7 +146,7 @@ async function fetchStatus(options: { silent?: boolean } = {}) {
if (!options.silent) loading.value = true;
error.value = "";
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
const sql = fallbackStatusSql.value ?? activeDriver.statusSql;
let result;
try {
diff --git a/apps/desktop/src/components/admin/ProcessListPanel.vue b/apps/desktop/src/components/admin/ProcessListPanel.vue
index 6d3da69cbe..00f33e79cc 100644
--- a/apps/desktop/src/components/admin/ProcessListPanel.vue
+++ b/apps/desktop/src/components/admin/ProcessListPanel.vue
@@ -295,7 +295,7 @@ async function load(options: { silent?: boolean } = {}) {
if (!options.silent) loading.value = true;
loadError.value = "";
try {
- await connectionStore.ensureConnected(connectionId);
+ await connectionStore.ensureConnected(connectionId, { skipIfClosedByUser: true });
if (!isCurrent()) return;
if (ownSessionId.value === null) {
try {
diff --git a/apps/desktop/src/components/admin/SqlServerActivityTracePanel.vue b/apps/desktop/src/components/admin/SqlServerActivityTracePanel.vue
index 711e2907a8..adedf374fa 100644
--- a/apps/desktop/src/components/admin/SqlServerActivityTracePanel.vue
+++ b/apps/desktop/src/components/admin/SqlServerActivityTracePanel.vue
@@ -90,7 +90,7 @@ async function loadDatabases() {
loadingDatabases.value = true;
error.value = "";
try {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
const result = await api.listDatabases(props.connection.id);
databases.value = result.map((database) => database.name).filter(Boolean);
if (!selectedDatabase.value || !databases.value.includes(selectedDatabase.value)) {
diff --git a/apps/desktop/src/components/admin/XuguServerDashboard.vue b/apps/desktop/src/components/admin/XuguServerDashboard.vue
index 395ca4821f..5cca10e20d 100644
--- a/apps/desktop/src/components/admin/XuguServerDashboard.vue
+++ b/apps/desktop/src/components/admin/XuguServerDashboard.vue
@@ -186,7 +186,7 @@ async function load() {
error.value = "";
partialErrors.value = [];
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
const requests = [
["version", XUGU_VERSION_SQL, 1],
["nodes", XUGU_CLUSTER_NODES_SQL, 500],
diff --git a/apps/desktop/src/components/admin/XuguUserPermissions.vue b/apps/desktop/src/components/admin/XuguUserPermissions.vue
index d039b297e2..c0dbd4fa2a 100644
--- a/apps/desktop/src/components/admin/XuguUserPermissions.vue
+++ b/apps/desktop/src/components/admin/XuguUserPermissions.vue
@@ -175,7 +175,7 @@ async function queryEither(primary: string, fallback: string): Promise<{ result:
}
async function ensureConnection() {
- await connectionStore.ensureConnected(props.connection.id);
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
}
async function loadDatabaseContext() {
diff --git a/apps/desktop/src/components/admin/__tests__/MySqlDashboard.spec.ts b/apps/desktop/src/components/admin/__tests__/MySqlDashboard.spec.ts
index 9e077c8f6a..dbaf030d29 100644
--- a/apps/desktop/src/components/admin/__tests__/MySqlDashboard.spec.ts
+++ b/apps/desktop/src/components/admin/__tests__/MySqlDashboard.spec.ts
@@ -94,7 +94,7 @@ describe("MySqlDashboard session affinity", () => {
app.mount(root!);
await flushMountedPolling();
- expect(mocks.ensureConnected).toHaveBeenCalledWith("mysql-1");
+ expect(mocks.ensureConnected).toHaveBeenCalledWith("mysql-1", { skipIfClosedByUser: true });
expect(mocks.executeQuery).toHaveBeenNthCalledWith(1, "mysql-1", "", GLOBAL_STATUS_SQL, undefined, undefined, { maxRows: 2000, clientSessionId: "tab-dashboard" });
expect(mocks.executeQuery).toHaveBeenNthCalledWith(2, "mysql-1", "", GLOBAL_VARIABLES_SQL, undefined, undefined, { maxRows: 2000, clientSessionId: "tab-dashboard" });
expect(mocks.executeQuery).toHaveBeenCalledTimes(2);
diff --git a/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts b/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts
index 37e72181f5..d0f9afcec6 100644
--- a/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts
+++ b/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts
@@ -151,7 +151,7 @@ describe("XuguUserPermissions", () => {
configureCompleteCatalogs();
const container = await mountPage();
- expect(mocks.ensureConnected).toHaveBeenCalledWith("xugu-connection");
+ expect(mocks.ensureConnected).toHaveBeenCalledWith("xugu-connection", { skipIfClosedByUser: true });
expect(mocks.executeQuery.mock.calls.every(([, database]) => database === "SYSTEM")).toBe(true);
expect(container.textContent).toContain("xuguUserPermissions.scopeSystem");
diff --git a/apps/desktop/src/components/document/DocumentBrowser.vue b/apps/desktop/src/components/document/DocumentBrowser.vue
index 4cfaf5a217..410c72dcd9 100644
--- a/apps/desktop/src/components/document/DocumentBrowser.vue
+++ b/apps/desktop/src/components/document/DocumentBrowser.vue
@@ -2660,7 +2660,7 @@ onMounted(async () => {
try {
// A restored tab issues no query, so a blocking health probe here would be
// the only round trip left on the switch.
- await connectionStore.ensureConnected(props.connectionId, restoredDocumentData ? { verifyHealth: false } : {});
+ await connectionStore.ensureConnected(props.connectionId, { ...(restoredDocumentData ? { verifyHealth: false } : {}), skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
diff --git a/apps/desktop/src/components/kv/KvKeyBrowser.vue b/apps/desktop/src/components/kv/KvKeyBrowser.vue
index bc04c4b51b..91b51cadda 100644
--- a/apps/desktop/src/components/kv/KvKeyBrowser.vue
+++ b/apps/desktop/src/components/kv/KvKeyBrowser.vue
@@ -1821,7 +1821,7 @@ watch(
clearSelectedKey();
clearMultiSelection();
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch {
// Connection failed — loadKeys will show the error state
}
@@ -1868,7 +1868,7 @@ watch(editKey, () => {
onMounted(() => {
initialLoadPromise = (async () => {
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
diff --git a/apps/desktop/src/components/layout/AppSidebar.vue b/apps/desktop/src/components/layout/AppSidebar.vue
index 3f783a7165..44fc73876c 100644
--- a/apps/desktop/src/components/layout/AppSidebar.vue
+++ b/apps/desktop/src/components/layout/AppSidebar.vue
@@ -162,7 +162,8 @@ async function confirmDeleteSelectedConnections() {
await connectionStore.removeConnections(ids);
for (const connectionId of ids) {
// 页签已由 removeConnections 按「删除连接」策略处理,这里只清会话。
- connectionStore.disconnect(connectionId, { skipTabHandling: true }).catch((error) => {
+ // 删除是终态,不该留下"用户已关闭"标记(配置都没了)。
+ connectionStore.disconnect(connectionId, { skipTabHandling: true, markClosedByUser: false }).catch((error) => {
console.warn("[DBX][connection:delete:disconnect-failed]", { connectionId, error });
});
}
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 2d0a4649b6..d53de106e6 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -439,22 +439,30 @@ watch(activeDatabaseValue, (database) => {
if (database) databaseRequiredVisible.value = false;
});
+/**
+ * 用户在侧栏显式关闭过、且还没重新连上的连接。
+ *
+ * 下面三个 watchEffect 是自动预取(挂载工具栏、切页签/切库时拉下拉选项),不代表用户
+ * 想连接;对显式关闭的连接必须跳过,否则残留页签一被激活就把连接连回来。它同时是这些
+ * 效果的响应式依赖:用户重连后标记消失,预取会自然补上。
+ */
+const activeConnectionClosedByUser = computed(() => (props.activeConnection ? connectionStore.isConnectionClosedByUser(props.activeConnection.id) : false));
+
watchEffect(() => {
const connection = props.activeConnection;
- if (connection && showSchemaSelector.value) {
- loadSchemaOptions(connection.id, schemaDatabaseKey.value).catch(() => {});
- }
+ if (!connection || activeConnectionClosedByUser.value || !showSchemaSelector.value) return;
+ loadSchemaOptions(connection.id, schemaDatabaseKey.value).catch(() => {});
});
watchEffect(() => {
const connection = props.activeConnection;
- if (!connection || !connectionIsDorisFamilyCatalogCapable(connection)) return;
+ if (!connection || activeConnectionClosedByUser.value || !connectionIsDorisFamilyCatalogCapable(connection)) return;
void loadCatalogOptions(connection.id).catch(() => {});
});
watchEffect(() => {
const connection = props.activeConnection;
const catalog = props.activeTab.catalog;
- if (!connection || !catalog) return;
+ if (!connection || activeConnectionClosedByUser.value || !catalog) return;
void loadCatalogDatabaseOptions(connection.id, catalog).catch(() => {});
});
diff --git a/apps/desktop/src/components/layout/__tests__/EditorToolbar.userClosedConnection.spec.ts b/apps/desktop/src/components/layout/__tests__/EditorToolbar.userClosedConnection.spec.ts
new file mode 100644
index 0000000000..c3474df2a5
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/EditorToolbar.userClosedConnection.spec.ts
@@ -0,0 +1,132 @@
+// @vitest-environment happy-dom
+import { createApp, defineComponent, h, nextTick, reactive } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { createI18n } from "vue-i18n";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/components/ui/button", () => ({
+ Button: { name: "ButtonStub", template: `<button><slot /></button>` },
+}));
+vi.mock("@/components/ui/searchable-select", () => ({
+ SearchableSelect: { name: "SearchableSelectStub", template: `<div />` },
+}));
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: { name: "TooltipStub", template: `<span><slot /></span>` },
+ TooltipTrigger: { name: "TooltipTriggerStub", template: `<span><slot /></span>` },
+ TooltipContent: { name: "TooltipContentStub", template: `<span><slot /></span>` },
+}));
+vi.mock("@/components/ui/TruncatedTextTooltip.vue", () => ({
+ default: { name: "TruncatedTextTooltipStub", template: `<span />` },
+}));
+vi.mock("@/components/icons/DatabaseIcon.vue", () => ({
+ default: { name: "DatabaseIconStub", template: `<span />` },
+}));
+vi.mock("@/components/connection/ConnectionTreeSelect.vue", () => ({
+ default: { name: "ConnectionTreeSelectStub", template: `<div />` },
+}));
+vi.mock("@/components/common/ProductionContextBadge.vue", () => ({
+ default: { name: "ProductionContextBadgeStub", template: `<span />` },
+}));
+
+import EditorToolbar from "../EditorToolbar.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+
+describe("EditorToolbar: passive wake-up must not reconnect a user-closed connection", () => {
+ let pinia: ReturnType<typeof createPinia>;
+ let i18n: ReturnType<typeof createI18n>;
+ let host: HTMLDivElement;
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ host = document.createElement("div");
+ document.body.appendChild(host);
+ pinia = createPinia();
+ setActivePinia(pinia);
+ i18n = createI18n({ legacy: false, locale: "en", messages: { en: {} } });
+ });
+
+ function mount(state: { connectionId: string; database: string }, ensureSpy: ReturnType<typeof vi.fn>) {
+ const connectionStore = useConnectionStore();
+ connectionStore.ensureConnected = ensureSpy as never;
+ const Host = defineComponent({
+ setup: () => () =>
+ h(EditorToolbar, {
+ activeTab: {
+ id: "tab-1",
+ title: "SQL",
+ connectionId: state.connectionId,
+ database: state.database,
+ sql: "SELECT 1",
+ mode: "query",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ },
+ activeConnection: connectionStore.getConfig(state.connectionId),
+ executableSql: "SELECT 1",
+ explainMode: "explain",
+ blockDangerousRedisCommands: false,
+ sqlKeywordCase: "preserve",
+ databaseRequiredSignal: 0,
+ autoCommit: true,
+ txnSessionId: undefined,
+ txnAutoRolledBack: false,
+ txnPossiblyDirty: false,
+ stickyProvenReadOnlyState: false,
+ }),
+ });
+ const app = createApp(Host);
+ app.use(pinia);
+ app.use(i18n);
+ app.mount(host);
+ return app;
+ }
+
+ it("does not prefetch options for a connection the user just closed", async () => {
+ const connectionStore = useConnectionStore();
+ connectionStore.connections = [{ id: "conn-1", name: "conn", db_type: "postgres", database: "app", color: "" } as never];
+ const ensureSpy = vi.fn(async () => {});
+ const state = reactive({ connectionId: "conn-1", database: "app" });
+
+ // 侧栏「关闭连接」后的状态(写入细节由 connectionStore.userClosedConnection.spec 覆盖)。
+ connectionStore.userClosedConnectionIds = new Set(["conn-1"]);
+ expect(connectionStore.isConnectionClosedByUser("conn-1")).toBe(true);
+
+ const app = mount(state, ensureSpy);
+ await nextTick();
+ await Promise.resolve();
+ expect(ensureSpy).not.toHaveBeenCalled();
+
+ // 切到同一连接下另一个库(页签切换的老重现路径)也不该唤醒连接。
+ state.database = "other_db";
+ await nextTick();
+ await Promise.resolve();
+ expect(ensureSpy).not.toHaveBeenCalled();
+
+ app.unmount();
+ }, 20_000);
+
+ it("prefetches again once the user reconnects", async () => {
+ const connectionStore = useConnectionStore();
+ connectionStore.connections = [{ id: "conn-1", name: "conn", db_type: "postgres", database: "app", color: "" } as never];
+ const ensureSpy = vi.fn(async () => {});
+ const state = reactive({ connectionId: "conn-1", database: "app" });
+
+ connectionStore.userClosedConnectionIds = new Set(["conn-1"]);
+ const app = mount(state, ensureSpy);
+ await nextTick();
+ await Promise.resolve();
+ expect(ensureSpy).not.toHaveBeenCalled();
+
+ // 用户显式重连会清掉标记(见 connectionStore.userClosedConnection.spec)。
+ connectionStore.userClosedConnectionIds = new Set();
+ connectionStore.connectedIds.add("conn-1");
+ await nextTick();
+ await Promise.resolve();
+
+ expect(ensureSpy).toHaveBeenCalled();
+ expect(ensureSpy.mock.calls.every((call) => call[0] === "conn-1")).toBe(true);
+
+ app.unmount();
+ }, 20_000);
+});
diff --git a/apps/desktop/src/components/mq/MqAdminConsole.vue b/apps/desktop/src/components/mq/MqAdminConsole.vue
index eaaced1c61..912e2f8f2a 100644
--- a/apps/desktop/src/components/mq/MqAdminConsole.vue
+++ b/apps/desktop/src/components/mq/MqAdminConsole.vue
@@ -424,7 +424,7 @@ watch(
// Lifecycle
onMounted(async () => {
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
diff --git a/apps/desktop/src/components/nacos/NacosAdminConsole.vue b/apps/desktop/src/components/nacos/NacosAdminConsole.vue
index ff24f40b77..78ebe52032 100644
--- a/apps/desktop/src/components/nacos/NacosAdminConsole.vue
+++ b/apps/desktop/src/components/nacos/NacosAdminConsole.vue
@@ -2720,7 +2720,7 @@ watch(
instancesError.value = "";
selectedConfigKeys.value = [];
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
@@ -2732,7 +2732,7 @@ watch(
onMounted(async () => {
stopNacosNamespacesChangedListener = subscribeNacosNamespacesChanged(handleNacosNamespacesChanged);
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
diff --git a/apps/desktop/src/components/nacos/NacosDashboard.vue b/apps/desktop/src/components/nacos/NacosDashboard.vue
index 22acc4888b..14bbffa0ad 100644
--- a/apps/desktop/src/components/nacos/NacosDashboard.vue
+++ b/apps/desktop/src/components/nacos/NacosDashboard.vue
@@ -276,7 +276,7 @@ async function fetchSnapshot(options: { silent?: boolean } = {}) {
if (!options.silent) loading.value = true;
error.value = "";
try {
- await connectionStore.ensureConnected(connectionId);
+ await connectionStore.ensureConnected(connectionId, { skipIfClosedByUser: true });
const value = await api.nacosGetDashboard(connectionId, { namespace });
if (requestId !== latestRequestId) return;
samples.value = appendDashboardSample(samples.value, { at: Date.now(), snapshot: value });
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index 15583c792b..7702705333 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -3550,7 +3550,9 @@ watch(
sourceEditing.value = false;
sourceSaving.value = false;
try {
- await connectionStore.ensureConnected(props.connection.id);
+ // 被动唤醒(挂载/切上下文):用户显式关掉的连接交给缓存对象列表与「刷新」按钮,
+ // 不在这里把它连回来。
+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connection.id, e);
}
diff --git a/apps/desktop/src/components/plugins/PluginFilesystemTab.spec.ts b/apps/desktop/src/components/plugins/PluginFilesystemTab.spec.ts
index 77d8df3220..0c89cecef8 100644
--- a/apps/desktop/src/components/plugins/PluginFilesystemTab.spec.ts
+++ b/apps/desktop/src/components/plugins/PluginFilesystemTab.spec.ts
@@ -64,7 +64,7 @@ describe("PluginFilesystemTab restore self-heal", () => {
it("self-heals a restored tab: silent ensureConnected instead of the reload prompt", async () => {
await mountTab();
- expect(mocks.ensureConnected).toHaveBeenCalledWith("conn-1", { allowPasswordPrompt: false });
+ expect(mocks.ensureConnected).toHaveBeenCalledWith("conn-1", { allowPasswordPrompt: false, skipIfClosedByUser: true });
expect(root.textContent).not.toContain("pluginPlatform.reloadRequired");
});
diff --git a/apps/desktop/src/components/plugins/PluginFilesystemTab.vue b/apps/desktop/src/components/plugins/PluginFilesystemTab.vue
index 02e0bed309..7f08141653 100644
--- a/apps/desktop/src/components/plugins/PluginFilesystemTab.vue
+++ b/apps/desktop/src/components/plugins/PluginFilesystemTab.vue
@@ -72,7 +72,9 @@ async function refresh(options: { silent?: boolean } = {}) {
return;
}
} else {
- await connectionStore.ensureConnected(props.connectionId, silent ? { allowPasswordPrompt: false } : undefined);
+ // 被动唤醒(页签恢复/重新挂载):用户显式关掉的连接不在这里偷偷重连,
+ // 由下面 silent 分支停在「重新加载」提示上等用户自己决定。
+ await connectionStore.ensureConnected(props.connectionId, { allowPasswordPrompt: silent ? false : undefined, skipIfClosedByUser: true });
}
}
if (fileManagerRef.value?.refresh) {
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchTab.spec.ts b/apps/desktop/src/components/plugins/PluginWorkbenchTab.spec.ts
index 06f3d9f7f9..7b66851a89 100644
--- a/apps/desktop/src/components/plugins/PluginWorkbenchTab.spec.ts
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchTab.spec.ts
@@ -189,7 +189,7 @@ describe("PluginWorkbenchTab restore self-heal", () => {
app = createApp(PluginWorkbenchTab, { pluginId: "com.example.graph", contributionId: "graph.main", connectionId: "conn-1" });
app.mount(root);
- await vi.waitFor(() => expect(mocks.ensureConnected).toHaveBeenCalledWith("conn-1", { allowPasswordPrompt: false }));
+ await vi.waitFor(() => expect(mocks.ensureConnected).toHaveBeenCalledWith("conn-1", { allowPasswordPrompt: false, skipIfClosedByUser: true }));
await vi.waitFor(() => expect(root.querySelector("iframe")).toBeInstanceOf(HTMLIFrameElement));
expect(root.textContent).not.toContain("pluginPlatform.reloadRequired");
});
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue b/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue
index 1aa47071b2..97a6d0d806 100644
--- a/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchTab.vue
@@ -81,7 +81,8 @@ async function refresh(options: { silent?: boolean } = {}) {
return;
}
} else {
- await connectionStore.ensureConnected(connectionId, silent ? { allowPasswordPrompt: false } : undefined);
+ // 被动唤醒(页签恢复/重新挂载):用户显式关掉的连接不在这里偷偷重连。
+ await connectionStore.ensureConnected(connectionId, { allowPasswordPrompt: silent ? false : undefined, skipIfClosedByUser: true });
}
}
await load();
diff --git a/apps/desktop/src/components/redis/RedisDashboard.vue b/apps/desktop/src/components/redis/RedisDashboard.vue
index 52ca56a486..2e77c6e115 100644
--- a/apps/desktop/src/components/redis/RedisDashboard.vue
+++ b/apps/desktop/src/components/redis/RedisDashboard.vue
@@ -306,7 +306,7 @@ watch(autoRefreshInterval, () => {
// ---------------------------------------------------------------------------
onMounted(async () => {
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.vue b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
index 96c184713a..3d4a436d72 100644
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.vue
+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.vue
@@ -3180,7 +3180,7 @@ onMounted(async () => {
resumeRedisBrowserBackgroundWork();
void autofocusSearchOnce();
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
@@ -3194,7 +3194,7 @@ onActivated(async () => {
// Ensure the connection is still alive after reactivation (e.g. tab switch).
// Retry an empty failed/interrupted load, but retain successful sparse pages.
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
@@ -3234,7 +3234,7 @@ watch(
resetCommandDocumentation();
resetLoadedKeys();
try {
- await connectionStore.ensureConnected(connectionId);
+ await connectionStore.ensureConnected(connectionId, { skipIfClosedByUser: true });
} catch (error) {
console.warn("[DBX] ensureConnected failed for", connectionId, error);
}
diff --git a/apps/desktop/src/components/redis/RedisSlowlogPanel.vue b/apps/desktop/src/components/redis/RedisSlowlogPanel.vue
index fae2f9ac21..e68235390d 100644
--- a/apps/desktop/src/components/redis/RedisSlowlogPanel.vue
+++ b/apps/desktop/src/components/redis/RedisSlowlogPanel.vue
@@ -59,7 +59,7 @@ const showClientColumns = computed(() => {
onMounted(async () => {
if (connectionMode.value === "cluster") {
try {
- await connectionStore.ensureConnected(props.connectionId);
+ await connectionStore.ensureConnected(props.connectionId, { skipIfClosedByUser: true });
nodes.value = await api.redisClusterMasterNodes(props.connectionId);
} catch (e) {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
diff --git a/apps/desktop/src/composables/__tests__/useSidebarConnectionMutationRuntime.selection.spec.ts b/apps/desktop/src/composables/__tests__/useSidebarConnectionMutationRuntime.selection.spec.ts
index 0feba444a1..cf28802f93 100644
--- a/apps/desktop/src/composables/__tests__/useSidebarConnectionMutationRuntime.selection.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSidebarConnectionMutationRuntime.selection.spec.ts
@@ -196,8 +196,8 @@ describe("sidebar connection deletion selection", () => {
// removeConnections 已按「删除连接」策略处理页签,disconnect 必须跳过断开策略,
// 否则会把刚保留下来的 SQL 页签又关掉。
expect(store.disconnect.mock.calls).toEqual([
- ["conn-1", { skipTabHandling: true }],
- ["conn-2", { skipTabHandling: true }],
+ ["conn-1", { skipTabHandling: true, markClosedByUser: false }],
+ ["conn-2", { skipTabHandling: true, markClosedByUser: false }],
]);
expect(mocks.toast).toHaveBeenCalledWith('connection.deletedSelected:{"count":2}', 2000);
});
@@ -252,8 +252,8 @@ describe("sidebar connection group deletion selection", () => {
expect(store.deleteConnectionGroups).toHaveBeenCalledWith(["group-1", "group-2"], true);
// 页签已由 deleteConnectionGroups 按「删除连接」策略处理,disconnect 只清会话。
expect(store.disconnect.mock.calls).toEqual([
- ["conn-1", { skipTabHandling: true }],
- ["conn-2", { skipTabHandling: true }],
+ ["conn-1", { skipTabHandling: true, markClosedByUser: false }],
+ ["conn-2", { skipTabHandling: true, markClosedByUser: false }],
]);
expect(showDeleteGroupConfirm.value).toBe(false);
expect(connectionGroupDeleteTargetSnapshot.value).toEqual([]);
diff --git a/apps/desktop/src/composables/useDataGridActions.ts b/apps/desktop/src/composables/useDataGridActions.ts
index 5da614ee6e..4c80dae220 100644
--- a/apps/desktop/src/composables/useDataGridActions.ts
+++ b/apps/desktop/src/composables/useDataGridActions.ts
@@ -166,7 +166,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const trace = options.trace;
console.info("[DBX][reloadData:metadata:ensure-connected:start]", { traceId: trace?.traceId, elapsed: trace?.elapsed() });
- await connectionStore.ensureConnected(target.connectionId);
+ await connectionStore.ensureConnected(target.connectionId, { skipIfClosedByUser: true });
console.info("[DBX][reloadData:metadata:ensure-connected:done]", { traceId: trace?.traceId, elapsed: trace?.elapsed() });
if (metadataRequests.get(tab) !== requestToken || connectionStore.metadataGenerationFor(target.connectionId, target.database) !== metadataGenerationAtStart) {
console.info("[DBX][reloadData:metadata:superseded-by-connection-generation]", { traceId: trace?.traceId, elapsed: trace?.elapsed(), table: target.tableName });
diff --git a/apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts b/apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts
index 2f85ecd247..9203c5a5f0 100644
--- a/apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts
@@ -117,8 +117,9 @@ export function useSidebarConnectionMutationRuntime(options: SidebarConnectionMu
options.releaseActiveNodeReference(targets.map((target) => target.id));
for (const connectionId of connectionIds) {
// 页签已由 removeConnections 按「删除连接」策略处理,这里只清会话,
- // 避免再套用「断开连接」策略把刚保留的 SQL 页签关掉。
- connectionStore.disconnect(connectionId, { skipTabHandling: true }).catch((error) => {
+ // 避免再套用「断开连接」策略把刚保留的 SQL 页签关掉。删除是终态,
+ // 也不写"用户已关闭"标记。
+ connectionStore.disconnect(connectionId, { skipTabHandling: true, markClosedByUser: false }).catch((error) => {
// Removal has already succeeded; disconnect cleanup must not turn it into a failed delete.
console.warn("[DBX][connection:delete:disconnect-failed]", { connectionId, error });
});
@@ -415,7 +416,7 @@ export function useSidebarConnectionMutationRuntime(options: SidebarConnectionMu
options.releaseActiveNodeReference(groupIds);
for (const connectionId of connectionIds) {
// 页签已由 deleteConnectionGroups 按「删除连接」策略处理,这里只清会话。
- connectionStore.disconnect(connectionId, { skipTabHandling: true }).catch((error) => {
+ connectionStore.disconnect(connectionId, { skipTabHandling: true, markClosedByUser: false }).catch((error) => {
console.warn("[DBX][connection-group:delete:disconnect-failed]", { connectionId, error });
});
}
diff --git a/apps/desktop/src/lib/sidebar/sidebarTableSearchIndex.ts b/apps/desktop/src/lib/sidebar/sidebarTableSearchIndex.ts
index 973846ccec..c637f3ab6f 100644
--- a/apps/desktop/src/lib/sidebar/sidebarTableSearchIndex.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarTableSearchIndex.ts
@@ -16,8 +16,12 @@ import type { TableInfo } from "@/types/database";
* scope is in flight, further requests reuse the same promise instead of
* spawning a duplicate scan. Entries are removed once the build settles
* (success or failure) so a later search can retry.
+ *
+ * A build may resolve `null` when it declines to index the scope (the
+ * connection was closed by the user in this session): the callers then fall
+ * back to filtering the already-loaded children.
*/
-const inFlightSidebarTableSearchBuilds = new Map<string, Promise<TableInfo[]>>();
+const inFlightSidebarTableSearchBuilds = new Map<string, Promise<TableInfo[] | null>>();
/**
* Stop a later explicit refresh from reusing a build that started before the
@@ -28,10 +32,10 @@ export function invalidateSidebarTableSearchBuild(scopeKey: string): void {
inFlightSidebarTableSearchBuilds.delete(scopeKey);
}
-function dedupeInFlightBuild(scopeKey: string, build: () => Promise<TableInfo[]>): Promise<TableInfo[]> {
+function dedupeInFlightBuild(scopeKey: string, build: () => Promise<TableInfo[] | null>): Promise<TableInfo[] | null> {
const existing = inFlightSidebarTableSearchBuilds.get(scopeKey);
if (existing) return existing;
- let pending!: Promise<TableInfo[]>;
+ let pending!: Promise<TableInfo[] | null>;
pending = (async () => {
try {
return await build();
@@ -55,8 +59,10 @@ function dedupeInFlightBuild(scopeKey: string, build: () => Promise<TableInfo[]>
* the in-flight lock so double-clicks cannot start duplicate full builds.
* - A persisted index is reused without rebuilding; a missing one is built
* through the lock, and concurrent callers share the same build promise.
+ * - A build may decline to index (`null`, e.g. the connection was closed by the
+ * user): callers then fall back to filtering the loaded children only.
*/
-export async function loadOrBuildSidebarTableSearchIndex(scopeKey: string, query: string, read: () => Promise<TableInfo[] | null>, build: () => Promise<TableInfo[]>, refresh = false): Promise<TableInfo[] | null> {
+export async function loadOrBuildSidebarTableSearchIndex(scopeKey: string, query: string, read: () => Promise<TableInfo[] | null>, build: () => Promise<TableInfo[] | null>, refresh = false): Promise<TableInfo[] | null> {
if (!refresh && !query.trim()) return null;
if (refresh) return dedupeInFlightBuild(scopeKey, build);
const entries = await read();
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableSearchUserClosed.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableSearchUserClosed.spec.ts
new file mode 100644
index 0000000000..45bcde6047
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableSearchUserClosed.spec.ts
@@ -0,0 +1,108 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ConnectionConfig, TreeNode } from "@/types/database";
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function pgConnection(id: string): ConnectionConfig {
+ return { id, name: id, db_type: "postgres", host: "127.0.0.1", port: 5432, username: "postgres", password: "", database: "app", read_only: false } as ConnectionConfig;
+}
+
+function databaseNode(connectionId: string, database: string): TreeNode {
+ return {
+ id: `${connectionId}:${database}`,
+ label: database,
+ type: "database",
+ connectionId,
+ database,
+ isExpanded: true,
+ children: [{ id: `${connectionId}:${database}:__tables`, label: "tables", type: "group-tables", connectionId, database, children: [] }],
+ };
+}
+
+async function setup() {
+ const checkConnectionHealth = vi.fn().mockResolvedValue(undefined);
+ const connectDb = vi.fn(async (config: ConnectionConfig) => config.id);
+ const listTables = vi.fn().mockResolvedValue([]);
+
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth,
+ connectDb,
+ listTables,
+ disconnectDb: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ deleteTableVGroupsForConnection: vi.fn().mockResolvedValue(undefined),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveConnections: vi.fn().mockResolvedValue(undefined),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ }));
+
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const store = useConnectionStore();
+ store.connections = [pgConnection("conn-a")];
+ // 侧栏里该库的节点还在(这是搜索输入框存在的前提)。
+ store.treeNodes = [
+ {
+ id: "conn-a",
+ label: "conn-a",
+ type: "connection",
+ connectionId: "conn-a",
+ isExpanded: true,
+ children: [databaseNode("conn-a", "app")],
+ },
+ ];
+ store.sidebarTableSearchQueries = { "conn-a:app": "user" };
+ return { store, connectDb, listTables };
+}
+
+describe("sidebar table search never wakes an explicitly user-closed connection", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.unstubAllGlobals();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ });
+
+ it("declines to build the index instead of reconnecting", async () => {
+ const { store, connectDb, listTables } = await setup();
+ store.userClosedConnectionIds = new Set(["conn-a"]);
+
+ // 首次搜索触发索引构建(ConnectionTree → loadOrBuildSidebarTableSearchIndex → build)。
+ const entries = await store.refreshSidebarTableSearchIndex("conn-a:app");
+
+ expect(connectDb).not.toHaveBeenCalled();
+ expect(listTables).not.toHaveBeenCalled();
+ // null = 本次不建索引,UI 回退到"只过滤已加载的表",不会缓存成"无匹配"。
+ expect(entries).toBeNull();
+ expect(store.connectedIds.has("conn-a")).toBe(false);
+ }, 20_000);
+
+ it("still builds normally when the connection was not closed by the user", async () => {
+ const { store, connectDb, listTables } = await setup();
+
+ const entries = await store.refreshSidebarTableSearchIndex("conn-a:app");
+
+ expect(connectDb).toHaveBeenCalledTimes(1);
+ expect(listTables).toHaveBeenCalled();
+ expect(Array.isArray(entries)).toBe(true);
+ }, 20_000);
+
+ it("remote table search refresh is guarded the same way", async () => {
+ const { store, connectDb, listTables } = await setup();
+ store.userClosedConnectionIds = new Set(["conn-a"]);
+
+ await store.refreshSidebarTableSearch("conn-a:app");
+
+ expect(connectDb).not.toHaveBeenCalled();
+ expect(listTables).not.toHaveBeenCalled();
+ }, 20_000);
+});
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.userClosedConnection.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.userClosedConnection.spec.ts
new file mode 100644
index 0000000000..8b8d10b480
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/connectionStore.userClosedConnection.spec.ts
@@ -0,0 +1,111 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ConnectionConfig } from "@/types/database";
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function pgConnection(id: string): ConnectionConfig {
+ return { id, name: id, db_type: "postgres", host: "127.0.0.1", port: 5432, username: "postgres", password: "", database: "app", read_only: false } as ConnectionConfig;
+}
+
+async function setup() {
+ const checkConnectionHealth = vi.fn().mockResolvedValue(undefined);
+ const connectDb = vi.fn(async (config: ConnectionConfig) => config.id);
+ const disconnectDb = vi.fn().mockResolvedValue(undefined);
+
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth,
+ connectDb,
+ disconnectDb,
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ deleteTableVGroupsForConnection: vi.fn().mockResolvedValue(undefined),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveConnections: vi.fn().mockResolvedValue(undefined),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ }));
+
+ const { useConnectionStore, CONNECTION_CLOSED_BY_USER_MESSAGE } = await import("@/stores/connectionStore");
+ const store = useConnectionStore();
+ store.connections = [pgConnection("conn-a")];
+ return { store, connectDb, disconnectDb, CONNECTION_CLOSED_BY_USER_MESSAGE };
+}
+
+describe("connectionStore: user-closed connections do not wake up from passive paths", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ });
+
+ it("marks the connection on disconnect and blocks passive wake-ups", async () => {
+ const { store, connectDb, CONNECTION_CLOSED_BY_USER_MESSAGE } = await setup();
+ store.connectedIds.add("conn-a");
+ await store.disconnect("conn-a");
+
+ expect(store.connectedIds.has("conn-a")).toBe(false);
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(true);
+
+ await expect(store.ensureConnected("conn-a", { skipIfClosedByUser: true })).rejects.toThrow(CONNECTION_CLOSED_BY_USER_MESSAGE);
+ expect(connectDb).not.toHaveBeenCalled();
+ expect(store.connectedIds.has("conn-a")).toBe(false);
+ }, 20_000);
+
+ it("lets an explicit reconnect through and clears the mark", async () => {
+ const { store, connectDb } = await setup();
+ store.connectedIds.add("conn-a");
+ await store.disconnect("conn-a");
+
+ // 用户主动入口(点侧栏连接节点 / 按 Run / 打开表数据)不带 skipIfClosedByUser。
+ await store.ensureConnected("conn-a");
+ expect(connectDb).toHaveBeenCalledTimes(1);
+ expect(store.connectedIds.has("conn-a")).toBe(true);
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(false);
+
+ // 标记清掉之后,页签界面的被动唤醒可以正常工作。
+ await store.ensureConnected("conn-a", { skipIfClosedByUser: true });
+ expect(store.connectedIds.has("conn-a")).toBe(true);
+ }, 20_000);
+
+ it("connect() clears the mark as well", async () => {
+ const { store } = await setup();
+ store.connectedIds.add("conn-a");
+ await store.disconnect("conn-a");
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(true);
+
+ await store.connect(pgConnection("conn-a"));
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(false);
+ }, 20_000);
+
+ it("system-side disconnects do not mark the connection", async () => {
+ const { store, connectDb } = await setup();
+ store.connectedIds.add("conn-a");
+ // releasePluginConnectionsAfterClose / retirePasswordAfterChange 走这条。
+ await store.disconnect("conn-a", { markClosedByUser: false });
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(false);
+
+ await store.ensureConnected("conn-a", { skipIfClosedByUser: true });
+ expect(connectDb).toHaveBeenCalledTimes(1);
+ expect(store.connectedIds.has("conn-a")).toBe(true);
+ }, 20_000);
+
+ it("removing the connection clears a stale mark", async () => {
+ const { store } = await setup();
+ store.connectedIds.add("conn-a");
+ await store.disconnect("conn-a");
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(true);
+
+ await store.removeConnection("conn-a");
+ expect(store.isConnectionClosedByUser("conn-a")).toBe(false);
+ }, 20_000);
+});
diff --git a/apps/desktop/src/stores/__tests__/queryStore.pluginTabCloseDisconnect.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.pluginTabCloseDisconnect.spec.ts
index 370bbd04b3..7a504180a7 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.pluginTabCloseDisconnect.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.pluginTabCloseDisconnect.spec.ts
@@ -105,7 +105,8 @@ describe("queryStore plugin tab close connection lifecycle", () => {
queryStore.closeTab(pluginTabId);
await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledTimes(1));
- expect(disconnectSpy).toHaveBeenCalledWith("conn-plugin");
+ // 系统侧释放:不写"用户已关闭"标记,否则用户重新打开该插件页签会连不上。
+ expect(disconnectSpy).toHaveBeenCalledWith("conn-plugin", { markClosedByUser: false });
});
it("waits for the last plugin-owned workbench and filesystem tab before disconnecting", async () => {
@@ -129,7 +130,7 @@ describe("queryStore plugin tab close connection lifecycle", () => {
queryStore.closeTab(filesystemId);
await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledTimes(1));
- expect(disconnectSpy).toHaveBeenCalledWith("conn-plugin");
+ expect(disconnectSpy).toHaveBeenCalledWith("conn-plugin", { markClosedByUser: false });
});
it("does not let another plugin disconnect a plugin-owned connection it only borrows", async () => {
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 9cc682afba..c7ea5f4650 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -435,6 +435,12 @@ type BeforeConnectHandler = (config: ConnectionConfig) => Promise<void>;
export const CONNECTION_ATTEMPT_CANCELLED_MESSAGE = "Connection attempt was cancelled";
/** Thrown when a no-save-password connection is connected without a typed password. */
export const CONNECTION_PASSWORD_REQUIRED_MESSAGE = "Password is required for this connection";
+/**
+ * Thrown by passive wake-ups (callers passing `skipIfClosedByUser`) when the user
+ * explicitly closed the connection in this session and nothing reconnected it since.
+ * Such callers should stay in a "closed" state and let the user reconnect on purpose.
+ */
+export const CONNECTION_CLOSED_BY_USER_MESSAGE = "Connection was closed by the user";
const PLUGIN_CONFIG_RECONNECT_PASSWORD_MESSAGE = "Plugin settings were saved, but the connection was disconnected because its password is not available. Reconnect manually to apply the new settings.";
function metadataDriverProfile(config?: ConnectionConfig): string | undefined {
@@ -500,6 +506,22 @@ export const useConnectionStore = defineStore("connection", () => {
const activePinnedTreeNodeReorderKey = ref<string | null>(null);
let pinnedTreeNodePersistQueue: Promise<void> = Promise.resolve();
const connectedIds = ref<Set<string>>(new Set());
+ /**
+ * 本会话内被用户**显式关闭**(侧栏「关闭连接」/「关闭选中的 N 个连接」/「关闭所有活跃
+ * 连接」/「断开并忘记本次密码」)且此后尚未重新连接的连接。
+ *
+ * 存在的理由:`ensureConnected` 只区分"已连接 / 未连接",没有"用户主动关掉了"这一态,
+ * 于是任何被动唤醒(页签重新挂载/激活、工具栏与面板预取下拉选项、插件页签的 silent
+ * self-heal)都会把用户刚关掉的连接偷偷连回来。
+ *
+ * 语义边界(改动这里前先读):
+ * - 只被 `skipIfClosedByUser` 的被动唤醒消费;用户主动入口——点侧栏连接节点、按 Run /
+ * EXPLAIN、打开表数据或查询页签、「重新连接」按钮——一律照常连接,并顺手清掉标记。
+ * - 系统侧断开不写标记(插件页签关闭释放连接、改密码后的重连退役、删除连接),它们
+ * 不该让后续的用户动作变哑。
+ * - 仅内存:页面刷新或重启后自然清空,恢复流程(dbx-plugin-ssh#144 的页签自愈)照旧生效。
+ */
+ const userClosedConnectionIds = ref<Set<string>>(new Set());
const etcdAccessCapabilities = ref<Record<string, EtcdAccessCapabilities>>({});
const etcdAccessCapabilityGenerations = new Map<string, number>();
const etcdAccessCapabilityLoads = new Map<string, Promise<EtcdAccessCapabilities>>();
@@ -1101,6 +1123,29 @@ export const useConnectionStore = defineStore("connection", () => {
return disconnectInFlight.has(connectionId);
}
+ /** 用户显式关闭过、且此后没有重新连上的连接(见 `userClosedConnectionIds`)。 */
+ function isConnectionClosedByUser(connectionId: string): boolean {
+ return !!connectionId && userClosedConnectionIds.value.has(connectionId);
+ }
+
+ function markConnectionClosedByUser(connectionId: string): void {
+ if (!connectionId || userClosedConnectionIds.value.has(connectionId)) return;
+ const next = new Set(userClosedConnectionIds.value);
+ next.add(connectionId);
+ userClosedConnectionIds.value = next;
+ }
+
+ /**
+ * 连接真的连上之后标记必须消失,否则页签界面会一直停在"连接已关闭"的空态:
+ * 用户点侧栏重连、按 Run、或在对话框里补上密码后,标记不能再拦后续的被动唤醒。
+ */
+ function clearConnectionClosedByUser(connectionId: string): void {
+ if (!connectionId || !userClosedConnectionIds.value.has(connectionId)) return;
+ const next = new Set(userClosedConnectionIds.value);
+ next.delete(connectionId);
+ userClosedConnectionIds.value = next;
+ }
+
async function waitForBlockingDisconnectInFlight(connectionId: string): Promise<void> {
const pending = getBlockingDisconnectInFlight(connectionId);
if (pending) await pending;
@@ -3420,10 +3465,15 @@ export const useConnectionStore = defineStore("connection", () => {
return scopes;
}
- async function refreshSidebarTableSearchIndex(parentNodeId: string, identity?: SidebarRegexScopeIdentity): Promise<TableInfo[]> {
+ async function refreshSidebarTableSearchIndex(parentNodeId: string, identity?: SidebarRegexScopeIdentity): Promise<TableInfo[] | null> {
const parent = identity ? findSidebarTreeNodeByIdentity(parentNodeId, identity) : findNode(treeNodes.value, parentNodeId);
if (!parent?.connectionId || !hasTreeNodeDatabaseContext(parent)) return [];
const connectionId = parent.connectionId;
+ // 搜索是后台投影,不得替用户建连:用户在侧栏显式关闭过的连接在这里直接放弃索引
+ // (返回 null,UI 退回"只过滤已加载的表"),而不是把它连回来。这里不能抛
+ // `skipIfClosedByUser` 那个错误——输入路径(loadLocalTableSearchResults)没有 catch,
+ // 抛出会变成未处理的 Promise 拒绝。
+ if (isConnectionClosedByUser(connectionId)) return null;
const cacheKey = sidebarTableSearchIndexCacheKey(parent);
if (!cacheKey) return [];
const connectionGeneration = sidebarTableSearchIndexConnectionGeneration(connectionId);
@@ -4005,6 +4055,8 @@ export const useConnectionStore = defineStore("connection", () => {
for (const id of removedIds) nextLayout = removeConnectionFromSidebarLayout(nextLayout, id);
await persistConnectionDeletion(nextConnections, nextLayout);
applyConnectionRemoval(removedIds, nextConnections, nextLayout);
+ // 连接已不存在,"用户已关闭"标记没有意义,留着只会泄漏失效 id。
+ for (const id of removedIds) clearConnectionClosedByUser(id);
purgeTableVGroupsForConnections(removedIds);
// 删除已经落盘完成;页签处理失败只告警,不能让已成功的删除以异常收场。
try {
@@ -4097,6 +4149,8 @@ export const useConnectionStore = defineStore("connection", () => {
useQueryStore().syncTabsDatabaseForConnectionEdit(config.id, previousDatabase, config.database ?? "");
clearPrimaryVisibleObjectNames(config.id);
connectedIds.value.delete(config.id);
+ // 编辑连接会在保存后重新连上,不是"用户关闭",标记不该留下。
+ clearConnectionClosedByUser(config.id);
clearSidebarStorageCaches(config.id);
clearConnectionIdentifierQuote(config.id);
clearConnectionHealthCheck(config.id);
@@ -4619,6 +4673,9 @@ export const useConnectionStore = defineStore("connection", () => {
passwordChangeReconnectRequired.delete(config.id);
activeConnectionId.value = id;
connectedIds.value.add(id);
+ // 显式连接成功即结束"用户已关闭"状态:页签界面随后的被动唤醒可以正常参与。
+ clearConnectionClosedByUser(config.id);
+ clearConnectionClosedByUser(id);
if (config.db_type !== "plugin") {
void refreshConnectedDatabaseInfo(id, { ...config, id });
await refreshConnectionIdentifierQuote(id, { ...config, id });
@@ -4773,10 +4830,17 @@ export const useConnectionStore = defineStore("connection", () => {
* `options.skipTabHandling` 用于「删除连接」流程:删除时页签已按
* `deleteConnectionTabHandlingMode` 处理过,这里只做会话清理,不能再套用
* `disconnectTabHandlingMode`,否则会把刚保留下来的 SQL 页签又关掉。
+ *
+ * `options.markClosedByUser` 默认 true:这里的调用方基本上都是用户在侧栏按下
+ * 「关闭连接」。系统侧释放(插件页签关闭后回收连接、改密码后的退役、删除连接)必须
+ * 传 false,否则后续用户重新打开那个页签时会因为标记而连不上(见 `userClosedConnectionIds`)。
*/
- async function disconnect(connectionId: string, options: { skipTabHandling?: boolean } = {}) {
+ async function disconnect(connectionId: string, options: { skipTabHandling?: boolean; markClosedByUser?: boolean } = {}) {
const metadataDrain = cancelSchemaDiffTasksForConnection(connectionId, new Error(i18n.global.t("schemaDiff.connectionDisconnected")));
const stateRevision = bumpConnectionStateRevision(connectionId);
+ // 先写标记再清理:清理过程中存活下来的页签(未保存草稿、keep-tabs 模式)一旦被
+ // 重新挂载,也不该在这一刻把连接连回来。
+ if (options.markClosedByUser !== false) markConnectionClosedByUser(connectionId);
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
if (hasSqlServerActivityTraceForConnection(connectionId)) await disposeSqlServerActivityTracesForConnection(connectionId);
const disconnectRequest = startDisconnectRequest(connectionId, metadataDrain);
@@ -4855,7 +4919,9 @@ export const useConnectionStore = defineStore("connection", () => {
async function retirePasswordAfterChange(connectionId: string) {
passwordChangeReconnectRequired.set(connectionId, "retiring");
connections.value = connections.value.map((config) => (config.id === connectionId ? { ...config, password: "", save_password: false } : config));
- const results = await Promise.allSettled([disconnect(connectionId), persistConnections()]);
+ // 改密码后的退役是系统侧断开:用户随后会显式重连,写"用户已关闭"标记只会让
+ // 页签界面在重连期间多停一档空态。
+ const results = await Promise.allSettled([disconnect(connectionId, { markClosedByUser: false }), persistConnections()]);
try {
if (await api.sessionCredentialStatus(connectionId)) await api.forgetSessionCredential(connectionId);
if (results.some((result) => result.status === "rejected")) throw new Error();
@@ -4905,7 +4971,17 @@ export const useConnectionStore = defineStore("connection", () => {
invalidateConnectionMetadataLifetime(connectionId, database);
}
- async function ensureConnected(connectionId: string, options: { activate?: boolean; verifyHealth?: boolean; forceReconnect?: boolean; allowPasswordPrompt?: boolean } = {}) {
+ /**
+ * 确保连接可用。默认语义是"需要就建连",用户主动入口(点侧栏连接、按 Run、打开表数据)
+ * 保持该语义。
+ *
+ * `options.skipIfClosedByUser` 供**被动唤醒**使用:页签重新挂载/激活、工具栏与面板预取
+ * 下拉选项、插件页签的 silent self-heal。用户刚在侧栏关掉的连接在这里直接抛
+ * `CONNECTION_CLOSED_BY_USER_MESSAGE`,让调用方停在"连接已关闭"的空态,而不是把连接
+ * 偷偷连回来(这是"关闭连接后连接又自己回来"这类报告的根因)。
+ */
+ async function ensureConnected(connectionId: string, options: { activate?: boolean; verifyHealth?: boolean; forceReconnect?: boolean; allowPasswordPrompt?: boolean; skipIfClosedByUser?: boolean } = {}) {
+ if (options.skipIfClosedByUser && isConnectionClosedByUser(connectionId)) throw new Error(CONNECTION_CLOSED_BY_USER_MESSAGE);
if (passwordChangeReconnectRequired.has(connectionId)) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect"));
if (!options.forceReconnect && connectedIds.value.has(connectionId)) {
// Pure navigation can safely trust the existing connected state. Its
@@ -4982,6 +5058,8 @@ export const useConnectionStore = defineStore("connection", () => {
await syncMongoLegacyDriverFallback(connectionId, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
connectedIds.value.add(connectionId);
+ // 任何路径真的连上之后,"用户已关闭"标记就不能再拦后续的被动唤醒。
+ clearConnectionClosedByUser(connectionId);
if (config.db_type !== "plugin") {
void refreshConnectedDatabaseInfo(connectionId, config);
await refreshConnectionIdentifierQuote(connectionId, config);
@@ -7208,6 +7286,9 @@ export const useConnectionStore = defineStore("connection", () => {
async function refreshSidebarTableSearch(parentNodeId: string) {
const parent = findNode(treeNodes.value, parentNodeId);
if (!parent?.connectionId || !hasTreeNodeDatabaseContext(parent)) return;
+ // 与 refreshSidebarTableSearchIndex 同一契约:表名搜索(本函数是远程搜索/开关切换
+ // 路径)不得把用户在侧栏显式关闭的连接连回来。
+ if (isConnectionClosedByUser(parent.connectionId)) return;
const searchFilter = sidebarTableSearchQueries.value[parentNodeId]?.trim() || "";
const options: LoadTreeOptions = {
@@ -10296,6 +10377,8 @@ export const useConnectionStore = defineStore("connection", () => {
refreshObjectListTreeNode,
connectedIds,
connectingIds,
+ isConnectionClosedByUser,
+ userClosedConnectionIds,
connectionErrors,
setConnectionError,
clearConnectionError,
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index dc386c3f19..5d48c15e07 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -4434,7 +4434,9 @@ export const useQueryStore = defineStore("query", () => {
// 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);
+ // 系统侧释放(页签关闭触发的回收)不算用户关闭:写标记会让用户重新打开
+ // 这个插件页签时连不上。
+ await connectionStore.disconnect(connectionId, { markClosedByUser: false });
} catch (error) {
console.warn("[DBX][plugin-tab-close:disconnect]", connectionId, error);
} finally {