fix(deep-link): preserve cold-start connection links

Closes #10090
This commit is contained in:
t8y2 committed 2026-09-25 19:20:11 +08:00
1 parent 02886a4682
commit 135e5a91a7
5 files changed
+163 -92

No files matched your search

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