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(deep-link): preserve cold-start connection links

t8y2135e5a91a75c
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 35eff66901..b9da1933b1 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -4071,14 +4071,15 @@ onMounted(async () => {
appVersion.value = v;
})
.catch(() => {});
- setupTauriListeners();
+ void setupTauriListeners().then(() => {
+ void openPendingSqlFiles();
+ void openPendingDbFiles();
+ void openPendingConnectionLinks();
+ void openPendingAiConfigLinks();
+ void openPendingPluginInstallLinks();
+ });
setupCloseActionPromptListener();
void setupDetachedWindowEvents();
- void openPendingSqlFiles();
- void openPendingDbFiles();
- void openPendingConnectionLinks();
- void openPendingAiConfigLinks();
- void openPendingPluginInstallLinks();
console.log(`[STARTUP] onMounted sync done: ${(performance.now() - mountStart).toFixed(0)}ms`);
});
diff --git a/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts b/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts
index ab7000efcd..8e943f42d9 100644
--- a/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useTauriEvents.spec.ts
@@ -2,12 +2,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const listeners = new Map<string, (event: { payload: unknown }) => void>();
const unlisten = vi.fn();
+let listenerRegistrationBarrier: Promise<void> | null = null;
+const listen = vi.fn(async (event: string, handler: (event: { payload: unknown }) => void) => {
+ await listenerRegistrationBarrier;
+ listeners.set(event, handler);
+ return unlisten;
+});
vi.mock("@tauri-apps/api/event", () => ({
- listen: vi.fn(async (event: string, handler: (event: { payload: unknown }) => void) => {
- listeners.set(event, handler);
- return unlisten;
- }),
+ listen,
}));
vi.mock("@/stores/connectionStore", () => ({
@@ -23,7 +26,40 @@ import { useTauriEvents } from "@/composables/useTauriEvents";
describe("useTauriEvents", () => {
beforeEach(() => {
listeners.clear();
+ listen.mockClear();
unlisten.mockClear();
+ listenerRegistrationBarrier = null;
+ });
+
+ it("resolves setup only after every native listener is registered", async () => {
+ let releaseRegistration!: () => void;
+ listenerRegistrationBarrier = new Promise<void>((resolve) => {
+ releaseRegistration = resolve;
+ });
+ const events = useTauriEvents({
+ openTableTarget: vi.fn(),
+ openSqlFilePath: vi.fn(),
+ openDbFilePath: vi.fn(),
+ openConnectionDeepLink: vi.fn(),
+ openAiConfigDeepLink: vi.fn(),
+ openPluginInstallDeepLink: vi.fn(),
+ closeActiveSurface: vi.fn(),
+ refreshPluginWorkbenches: vi.fn(),
+ });
+
+ let setupResolved = false;
+ const setup = events.setupTauriListeners().then(() => {
+ setupResolved = true;
+ });
+ await vi.waitFor(() => expect(listen).toHaveBeenCalled());
+ expect(setupResolved).toBe(false);
+ expect(listeners.size).toBe(0);
+
+ releaseRegistration();
+ await setup;
+
+ expect(setupResolved).toBe(true);
+ expect(listeners.has("dbx-open-connection-links")).toBe(true);
});
it("routes the native macOS close-tab menu event to the active surface", async () => {
@@ -37,8 +73,7 @@ describe("useTauriEvents", () => {
refreshPluginWorkbenches: vi.fn(),
});
- events.setupTauriListeners();
- await vi.waitFor(() => expect(listeners.has("dbx-close-active-tab")).toBe(true));
+ await events.setupTauriListeners();
listeners.get("dbx-close-active-tab")!({ payload: undefined });
expect(closeActiveSurface).toHaveBeenCalledOnce();
@@ -57,8 +92,7 @@ describe("useTauriEvents", () => {
refreshPluginWorkbenches,
});
- events.setupTauriListeners();
- await vi.waitFor(() => expect(listeners.has("plugin-runtime-replaced")).toBe(true));
+ await events.setupTauriListeners();
listeners.get("plugin-runtime-replaced")!({ payload: { pluginId: "io.example.plugin", version: "0.2.0" } });
expect(refreshPluginWorkbenches).toHaveBeenCalledExactlyOnceWith("io.example.plugin");
diff --git a/apps/desktop/src/composables/useTauriEvents.ts b/apps/desktop/src/composables/useTauriEvents.ts
index 4b35918959..4d56da5e20 100644
--- a/apps/desktop/src/composables/useTauriEvents.ts
+++ b/apps/desktop/src/composables/useTauriEvents.ts
@@ -25,10 +25,19 @@ export function useTauriEvents(deps: {
);
}
- function setupTauriListeners() {
- import("@tauri-apps/api/event")
+ function setupTauriListeners(): Promise<void> {
+ return import("@tauri-apps/api/event")
.then(({ listen }) => {
- listen<{ connection_id: string; database: string; schema?: string; table: string }>("mcp-open-table", async (event) => {
+ const registrations: Promise<void>[] = [];
+ const track = (registration: Promise<() => void>) => {
+ registrations.push(
+ registration.then((unlisten) => {
+ unlistenHandles.push(unlisten);
+ }),
+ );
+ };
+
+ track(listen<{ connection_id: string; database: string; schema?: string; table: string }>("mcp-open-table", async (event) => {
try {
const { connection_id, database, schema, table } = event.payload;
if (!connectionStore.connections.length) await connectionStore.initFromDisk();
@@ -47,9 +56,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] mcp-open-table error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<{ connection_id: string }>("mcp-open-connection-workbench", async (event) => {
+ track(listen<{ connection_id: string }>("mcp-open-connection-workbench", async (event) => {
try {
const { connection_id } = event.payload;
if (!connectionStore.connections.length) await connectionStore.initFromDisk();
@@ -65,12 +74,12 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] mcp-open-connection-workbench error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
// Plugins report live transport state through plugin events; when an
// SSH session dies, flip the sidebar entry offline so the tree stops
// showing a connection that no longer exists.
- listen<{ method: string; params: { state?: string; connectionId?: string } }>("dbx-plugin-event", async (event) => {
+ track(listen<{ method: string; params: { state?: string; connectionId?: string } }>("dbx-plugin-event", async (event) => {
try {
const payload = event.payload ?? ({} as typeof event.payload);
if (payload.method !== "ssh/session/state" || payload.params?.state !== "disconnected") return;
@@ -82,17 +91,17 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-plugin-event (ssh/session/state) error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen("mcp-reload-connections", async () => {
+ track(listen("mcp-reload-connections", async () => {
try {
await connectionStore.initFromDisk();
} catch (e) {
console.error("[DBX] mcp-reload-connections error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<{
+ track(listen<{
connection_id: string;
database: string;
sql: string;
@@ -109,9 +118,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] mcp-execute-query error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<string[]>("dbx-open-sql-files", async (event) => {
+ track(listen<string[]>("dbx-open-sql-files", async (event) => {
try {
for (const path of event.payload) {
await deps.openSqlFilePath(path);
@@ -120,9 +129,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-open-sql-files error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<string[]>("dbx-open-db-files", async (event) => {
+ track(listen<string[]>("dbx-open-db-files", async (event) => {
try {
for (const path of event.payload) {
await deps.openDbFilePath(path);
@@ -131,9 +140,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-open-db-files error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<string[]>("dbx-open-connection-links", async (event) => {
+ track(listen<string[]>("dbx-open-connection-links", async (event) => {
try {
for (const url of event.payload) {
await deps.openConnectionDeepLink(url);
@@ -142,9 +151,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-open-connection-links error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<string[]>("dbx-open-ai-config-links", async (event) => {
+ track(listen<string[]>("dbx-open-ai-config-links", async (event) => {
try {
for (const url of event.payload) {
await deps.openAiConfigDeepLink(url);
@@ -153,9 +162,9 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-open-ai-config-links error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen<string[]>("dbx-open-plugin-install-links", async (event) => {
+ track(listen<string[]>("dbx-open-plugin-install-links", async (event) => {
try {
for (const url of event.payload) {
await deps.openPluginInstallDeepLink(url);
@@ -164,18 +173,20 @@ export function useTauriEvents(deps: {
} catch (e) {
console.error("[DBX] dbx-open-plugin-install-links error:", e);
}
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
- listen("dbx-close-active-tab", () => {
+ track(listen("dbx-close-active-tab", () => {
deps.closeActiveSurface();
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
// A plugin was installed/rolled back from its already-replaced runtime:
// open workbench tabs still render the previous UI bundle until they
// reload, so hand them the new identity to pick up.
- listen<{ pluginId: string; version: string }>("plugin-runtime-replaced", (event) => {
+ track(listen<{ pluginId: string; version: string }>("plugin-runtime-replaced", (event) => {
if (event.payload?.pluginId) deps.refreshPluginWorkbenches(event.payload.pluginId);
- }).then((unlisten) => unlistenHandles.push(unlisten));
+ }));
+
+ return Promise.allSettled(registrations).then(() => {});
})
.catch(() => {});
}
diff --git a/src-tauri/src/commands/deep_link.rs b/src-tauri/src/commands/deep_link.rs
index fd632039bd..125a5285a0 100644
--- a/src-tauri/src/commands/deep_link.rs
+++ b/src-tauri/src/commands/deep_link.rs
@@ -8,67 +8,81 @@ const APP_OPEN_DEEP_LINK_PREFIX: &str = "dbx://open";
#[tauri::command]
pub fn pending_open_connection_links(state: tauri::State<'_, DeepLinkOpenState>) -> Vec<String> {
- dedupe_links(state.drain_connection_links())
+ dedupe_links(state.activate_connection_links())
}
#[tauri::command]
pub fn pending_open_ai_config_links(state: tauri::State<'_, DeepLinkOpenState>) -> Vec<String> {
- dedupe_links(state.drain_ai_config_links())
+ dedupe_links(state.activate_ai_config_links())
}
#[tauri::command]
pub fn pending_open_plugin_install_links(state: tauri::State<'_, DeepLinkOpenState>) -> Vec<String> {
- dedupe_links(state.drain_plugin_install_links())
+ dedupe_links(state.activate_plugin_install_links())
+}
+
+#[derive(Default)]
+struct PendingDeepLinks {
+ links: Vec<String>,
+ frontend_ready: bool,
}
#[derive(Default)]
pub struct DeepLinkOpenState {
- pending_connection_links: Mutex<Vec<String>>,
- pending_ai_config_links: Mutex<Vec<String>>,
- pending_plugin_install_links: Mutex<Vec<String>>,
+ pending_connection_links: Mutex<PendingDeepLinks>,
+ pending_ai_config_links: Mutex<PendingDeepLinks>,
+ pending_plugin_install_links: Mutex<PendingDeepLinks>,
}
impl DeepLinkOpenState {
- pub fn push_connection_links(&self, links: Vec<String>) {
- if links.is_empty() {
- return;
- }
- if let Ok(mut pending) = self.pending_connection_links.lock() {
- pending.extend(links);
- }
+ pub fn route_connection_links(&self, links: Vec<String>) -> bool {
+ route_links(&self.pending_connection_links, links)
}
- pub fn push_ai_config_links(&self, links: Vec<String>) {
- if links.is_empty() {
- return;
- }
- if let Ok(mut pending) = self.pending_ai_config_links.lock() {
- pending.extend(links);
- }
+ pub fn route_ai_config_links(&self, links: Vec<String>) -> bool {
+ route_links(&self.pending_ai_config_links, links)
}
- pub fn push_plugin_install_links(&self, links: Vec<String>) {
- if links.is_empty() {
- return;
- }
- if let Ok(mut pending) = self.pending_plugin_install_links.lock() {
- pending.extend(links);
- }
+ pub fn route_plugin_install_links(&self, links: Vec<String>) -> bool {
+ route_links(&self.pending_plugin_install_links, links)
}
- fn drain_connection_links(&self) -> Vec<String> {
- self.pending_connection_links.lock().map(|mut pending| pending.drain(..).collect()).unwrap_or_default()
+ fn activate_connection_links(&self) -> Vec<String> {
+ activate_links(&self.pending_connection_links)
}
- fn drain_ai_config_links(&self) -> Vec<String> {
- self.pending_ai_config_links.lock().map(|mut pending| pending.drain(..).collect()).unwrap_or_default()
+ fn activate_ai_config_links(&self) -> Vec<String> {
+ activate_links(&self.pending_ai_config_links)
}
- fn drain_plugin_install_links(&self) -> Vec<String> {
- self.pending_plugin_install_links.lock().map(|mut pending| pending.drain(..).collect()).unwrap_or_default()
+ fn activate_plugin_install_links(&self) -> Vec<String> {
+ activate_links(&self.pending_plugin_install_links)
}
}
+fn route_links(pending: &Mutex<PendingDeepLinks>, links: Vec<String>) -> bool {
+ if links.is_empty() {
+ return false;
+ }
+ let Ok(mut pending) = pending.lock() else {
+ return true;
+ };
+ if pending.frontend_ready {
+ true
+ } else {
+ pending.links.extend(links);
+ false
+ }
+}
+
+fn activate_links(pending: &Mutex<PendingDeepLinks>) -> Vec<String> {
+ let Ok(mut pending) = pending.lock() else {
+ return Vec::new();
+ };
+ pending.frontend_ready = true;
+ pending.links.drain(..).collect()
+}
+
pub fn connection_deep_links_from_args<I, S>(args: I) -> Vec<String>
where
I: IntoIterator<Item = S>,
@@ -193,21 +207,26 @@ mod tests {
}
#[test]
- fn drains_pending_links_once() {
+ fn queues_links_until_the_frontend_activates_each_listener() {
let state = DeepLinkOpenState::default();
- state.push_connection_links(vec!["dbx://connection/new?type=mysql".to_string()]);
- state.push_ai_config_links(vec!["dbx://settings/ai/new?provider=openai-compatible".to_string()]);
- state.push_plugin_install_links(vec!["dbx://plugins/install?url=https://example.com/plugin.dbxp".to_string()]);
+ assert!(!state.route_connection_links(vec!["dbx://connection/new?type=mysql".to_string()]));
+ assert!(!state.route_ai_config_links(vec!["dbx://settings/ai/new?provider=openai-compatible".to_string()]));
+ assert!(!state
+ .route_plugin_install_links(vec!["dbx://plugins/install?url=https://example.com/plugin.dbxp".to_string()]));
- assert_eq!(state.drain_connection_links(), vec!["dbx://connection/new?type=mysql"]);
- assert_eq!(state.drain_ai_config_links(), vec!["dbx://settings/ai/new?provider=openai-compatible"]);
+ assert_eq!(state.activate_connection_links(), vec!["dbx://connection/new?type=mysql"]);
+ assert_eq!(state.activate_ai_config_links(), vec!["dbx://settings/ai/new?provider=openai-compatible"]);
assert_eq!(
- state.drain_plugin_install_links(),
+ state.activate_plugin_install_links(),
vec!["dbx://plugins/install?url=https://example.com/plugin.dbxp"]
);
- assert!(state.drain_connection_links().is_empty());
- assert!(state.drain_ai_config_links().is_empty());
- assert!(state.drain_plugin_install_links().is_empty());
+ assert!(state.route_connection_links(vec!["dbx://connection/new?type=postgres".to_string()]));
+ assert!(state.route_ai_config_links(vec!["dbx://settings/ai/new?provider=anthropic".to_string()]));
+ assert!(state
+ .route_plugin_install_links(vec!["dbx://plugins/install?url=https://example.com/next.dbxp".to_string()]));
+ assert!(state.activate_connection_links().is_empty());
+ assert!(state.activate_ai_config_links().is_empty());
+ assert!(state.activate_plugin_install_links().is_empty());
}
#[test]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 7ed71d9dbe..746f4ee26e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -686,10 +686,12 @@ fn open_connection_deep_links(app: &tauri::AppHandle, links: Vec<String>) {
if links.is_empty() {
return;
}
- if let Some(state) = app.try_state::<commands::deep_link::DeepLinkOpenState>() {
- state.push_connection_links(links.clone());
+ let should_emit = app
+ .try_state::<commands::deep_link::DeepLinkOpenState>()
+ .is_none_or(|state| state.route_connection_links(links.clone()));
+ if should_emit {
+ let _ = app.emit("dbx-open-connection-links", links);
}
- let _ = app.emit("dbx-open-connection-links", links);
show_main_window(app);
}
@@ -697,10 +699,12 @@ fn open_ai_config_deep_links(app: &tauri::AppHandle, links: Vec<String>) {
if links.is_empty() {
return;
}
- if let Some(state) = app.try_state::<commands::deep_link::DeepLinkOpenState>() {
- state.push_ai_config_links(links.clone());
+ let should_emit = app
+ .try_state::<commands::deep_link::DeepLinkOpenState>()
+ .is_none_or(|state| state.route_ai_config_links(links.clone()));
+ if should_emit {
+ let _ = app.emit("dbx-open-ai-config-links", links);
}
- let _ = app.emit("dbx-open-ai-config-links", links);
show_main_window(app);
}
@@ -708,10 +712,12 @@ fn open_plugin_install_deep_links(app: &tauri::AppHandle, links: Vec<String>) {
if links.is_empty() {
return;
}
- if let Some(state) = app.try_state::<commands::deep_link::DeepLinkOpenState>() {
- state.push_plugin_install_links(links.clone());
+ let should_emit = app
+ .try_state::<commands::deep_link::DeepLinkOpenState>()
+ .is_none_or(|state| state.route_plugin_install_links(links.clone()));
+ if should_emit {
+ let _ = app.emit("dbx-open-plugin-install-links", links);
}
- let _ = app.emit("dbx-open-plugin-install-links", links);
show_main_window(app);
}