feat(plugins): add floating window surface for plugin workbenches

This commit is contained in:
miracle authored and GitHub committed 2026-10-04 22:26:58 +08:00
1 parent a24a559160
commit 1bd9b821d3
13 files changed
+1879 -13

No files matched your search

+53
View File
@@ -188,6 +188,7 @@ import { useBackgroundImage } from "@/composables/useBackgroundImage";
import ExternalSqlFileChangeDialog from "@/components/editor/ExternalSqlFileChangeDialog.vue"; import ExternalSqlFileChangeDialog from "@/components/editor/ExternalSqlFileChangeDialog.vue";
import { resolveWindowContext } from "@/lib/app/windowContext"; import { resolveWindowContext } from "@/lib/app/windowContext";
import { openDetachedTabWindow } from "@/lib/app/detachedTabWindow"; import { openDetachedTabWindow } from "@/lib/app/detachedTabWindow";
import { FLOATING_OPEN_FILESYSTEM_EVENT, FLOATING_OPEN_WORKBENCH_EVENT, type FloatingOpenFilesystemPayload, type FloatingOpenWorkbenchPayload } from "@/lib/plugins/pluginFloatingWindow";
import { OPEN_PLUGIN_AI_CONVERSATION, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation"; import { OPEN_PLUGIN_AI_CONVERSATION, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation";
import type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostBridge"; import type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostBridge";
@@ -539,6 +540,7 @@ const pluginWorkbenchTabRefs = new Map<string, PluginWorkbenchTabHandle>();
const tabNavigationHistory = ref(createTabNavigationHistory()); const tabNavigationHistory = ref(createTabNavigationHistory());
let pendingTabHistoryNavigationId: string | null = null; let pendingTabHistoryNavigationId: string | null = null;
let detachedEventUnlisteners: Array<() => void> = []; let detachedEventUnlisteners: Array<() => void> = [];
let floatingEventUnlisteners: Array<() => void> = [];
let detachedCloseInProgress = false; let detachedCloseInProgress = false;
const detachedDropTargetTabId = ref<string | null>(null); const detachedDropTargetTabId = ref<string | null>(null);
const showDetachedClosePrompt = ref(false); const showDetachedClosePrompt = ref(false);
@@ -788,6 +790,54 @@ async function setupDetachedWindowEvents() {
} }
} }
// A floating plugin window hosts a single widget and has no shell of its own, so
// its shell-bound navigation is forwarded here (emitTo "main"): raise this window
// and open the tab the widget asked for. Payloads are validated field by field —
// they cross a window boundary, and a malformed one must not open a half-titled tab.
async function raiseMainWindow() {
const { getCurrentWindow } = await import("@tauri-apps/api/window");
const currentWindow = getCurrentWindow();
await currentWindow.show().catch(() => undefined);
await currentWindow.unminimize().catch(() => undefined);
await currentWindow.setFocus().catch(() => undefined);
}
async function handleFloatingOpenWorkbench(payload: unknown) {
const data = payload as Partial<FloatingOpenWorkbenchPayload> | null;
if (typeof data?.pluginId !== "string" || typeof data.contributionId !== "string") return;
const context = data.context && typeof data.context === "object" ? data.context : undefined;
await raiseMainWindow();
queryStore.openPluginWorkbench(data.pluginId, data.contributionId, {
...(typeof data.title === "string" && data.title ? { title: data.title } : {}),
...(context ? { context } : {}),
forceNew: data.forceNew === true,
});
}
async function handleFloatingOpenFilesystem(payload: unknown) {
const data = payload as Partial<FloatingOpenFilesystemPayload> | null;
if (typeof data?.pluginId !== "string" || typeof data.providerId !== "string") return;
const context = data.context && typeof data.context === "object" ? data.context : undefined;
await raiseMainWindow();
queryStore.openPluginFilesystem(data.pluginId, data.providerId, {
...(typeof data.title === "string" && data.title ? { title: data.title } : {}),
...(typeof data.rootUri === "string" && data.rootUri ? { rootUri: data.rootUri } : {}),
...(typeof context?.connectionId === "string" ? { connectionId: context.connectionId } : {}),
...(typeof context?.uri === "string" ? { currentUri: context.uri } : {}),
});
}
async function setupFloatingWindowEvents() {
if (!isDesktop || isDetachedWindowContext) return;
const { listen } = await import("@tauri-apps/api/event");
floatingEventUnlisteners.push(await listen(FLOATING_OPEN_WORKBENCH_EVENT, (message) => void handleFloatingOpenWorkbench(message.payload)));
floatingEventUnlisteners.push(await listen(FLOATING_OPEN_FILESYSTEM_EVENT, (message) => void handleFloatingOpenFilesystem(message.payload)));
// A floating window whose renderer dies cannot dismiss itself (frameless, and
// nothing inside it runs), so the main window reaps silent ones.
const { startFloatingWindowReaper } = await import("@/lib/plugins/pluginFloatingWindow");
floatingEventUnlisteners.push(startFloatingWindowReaper());
}
async function detachTab(tab: QueryTab, position?: { x: number; y: number }) { async function detachTab(tab: QueryTab, position?: { x: number; y: number }) {
if (isDetachedWindowContext || !isDetachableTab(tab)) return; if (isDetachedWindowContext || !isDetachableTab(tab)) return;
try { try {
@@ -4422,6 +4472,7 @@ onMounted(async () => {
}); });
setupCloseActionPromptListener(); setupCloseActionPromptListener();
void setupDetachedWindowEvents(); void setupDetachedWindowEvents();
void setupFloatingWindowEvents();
console.log(`[STARTUP] onMounted sync done: ${(performance.now() - mountStart).toFixed(0)}ms`); console.log(`[STARTUP] onMounted sync done: ${(performance.now() - mountStart).toFixed(0)}ms`);
}); });
@@ -4432,6 +4483,8 @@ onUnmounted(() => {
connectionLivenessUnlisten = null; connectionLivenessUnlisten = null;
detachedEventUnlisteners.forEach((unlisten) => unlisten()); detachedEventUnlisteners.forEach((unlisten) => unlisten());
detachedEventUnlisteners = []; detachedEventUnlisteners = [];
floatingEventUnlisteners.forEach((unlisten) => unlisten());
floatingEventUnlisteners = [];
cleanupTauriListeners(); cleanupTauriListeners();
cleanupCloseActionPromptListener(); cleanupCloseActionPromptListener();
if (updateCheckTimer) { if (updateCheckTimer) {
@@ -0,0 +1,187 @@
<script setup lang="ts">
// Floating plugin window root — the whole document of a frameless, always-on-top
// desktop window that hosts exactly one plugin workbench (§8.3 surface "window").
// main.ts mounts this instead of the workbench shell when the window URL carries
// the plugin-window parameters, so a widget never boots or paints the tab strip,
// dock, and panels it does not contain. Shell-bound navigation is forwarded to
// the main window (see pluginFloatingWindow.forwardFloatingToMainWindow).
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { AlertTriangle, Loader2, X } from "@lucide/vue";
import * as api from "@/lib/backend/api";
import { useTheme } from "@/composables/useTheme";
import { resolveWindowContext } from "@/lib/app/windowContext";
import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
import { closeFloatingWindows, FLOATING_OPEN_FILESYSTEM_EVENT, FLOATING_OPEN_WORKBENCH_EVENT, FLOATING_WEBVIEW_HELLO_EVENT, FLOATING_WEBVIEW_READY_EVENT, forwardFloatingToMainWindow, resumeFloatingDock, revealFloatingWindow } from "@/lib/plugins/pluginFloatingWindow";
import { emitTo, listen } from "@tauri-apps/api/event";
import type { PluginWorkbenchContext } from "@/lib/plugins/pluginHostBridge";
import PluginWorkbenchHost from "@/components/plugins/PluginWorkbenchHost.vue";
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
const props = defineProps<{ localeReady?: Promise<void> }>();
const { locale } = useI18n();
const { applyTheme } = useTheme();
const windowContext = resolveWindowContext();
const identity = windowContext.kind === "plugin-window" ? windowContext : null;
const plugins = ref<InstalledPlugin[]>([]);
const plugin = ref<InstalledPlugin | null>(null);
const contribution = ref<PluginWorkbenchContribution | null>(null);
const failure = ref("");
let revealed = false;
let revealFallback: ReturnType<typeof setTimeout> | undefined;
// A floating window whose plugin never talks back paints a blank page on the
// desktop — no capsule, no buttons, nothing to click. The iframe's `load` event
// fires even when the plugin's own boot dies afterwards, so "ready" is not
// proof of life: bridge traffic is. If none arrives, fall back to the error
// card, which at least can be read and dismissed.
let pluginTalked = false;
let silenceWatchdog: ReturnType<typeof setTimeout> | undefined;
const PLUGIN_SILENCE_TIMEOUT_MS = 10_000;
const hostContext = computed<PluginWorkbenchContext>(() => ({
...identity?.pluginContext,
workbenchId: identity?.windowLabel ?? "",
restored: false,
surface: "window",
}));
const zh = computed(() => locale.value.startsWith("zh"));
const statusText = computed(() => (failure.value ? `${zh.value ? "插件浮窗无法加载" : "The plugin window could not load"}: ${failure.value}` : zh.value ? "正在加载插件…" : "Loading plugin…"));
async function reveal() {
if (revealed) return;
revealed = true;
clearTimeout(revealFallback);
await revealFloatingWindow();
}
async function closeWindow() {
if (!identity) return;
await closeFloatingWindows([identity.windowLabel]);
}
function armSilenceWatchdog() {
clearTimeout(silenceWatchdog);
silenceWatchdog = setTimeout(() => {
if (!pluginTalked && !failure.value) failure.value = zh.value ? "插件没有响应" : "the plugin did not respond";
}, PLUGIN_SILENCE_TIMEOUT_MS);
}
function onHostReady() {
void reveal();
armSilenceWatchdog();
}
function onHostError(message: string) {
if (!failure.value) failure.value = message || (zh.value ? "插件加载失败" : "the plugin failed to load");
void reveal();
}
function onPluginMessage(event: MessageEvent) {
if (pluginTalked) return;
const frames = Array.from(document.querySelectorAll("iframe"));
if (frames.some((frame) => frame.contentWindow === event.source)) {
pluginTalked = true;
clearTimeout(silenceWatchdog);
}
}
function registry() {
return createFrontendPluginRegistry(plugins.value, locale.value);
}
async function onOpenWorkbench(pluginId: string, contributionId: string, context?: PluginWorkbenchContext, options?: { forceNew?: boolean }) {
const target = registry().findWorkbench(pluginId, contributionId);
await forwardFloatingToMainWindow(FLOATING_OPEN_WORKBENCH_EVENT, {
pluginId,
contributionId,
title: target?.contribution.label,
...(context ? { context } : {}),
forceNew: options?.forceNew === true,
});
}
async function onOpenFilesystem(pluginId: string, providerId: string, context?: PluginWorkbenchContext) {
const target = registry()
.listFilesystemProviders()
.find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId);
await forwardFloatingToMainWindow(FLOATING_OPEN_FILESYSTEM_EVENT, {
pluginId,
providerId,
title: target?.contribution.label,
...(target?.contribution.root_uri ? { rootUri: target.contribution.root_uri } : {}),
...(context ? { context } : {}),
});
}
onMounted(async () => {
applyTheme();
window.addEventListener("message", onPluginMessage);
// Report liveness to the window that created this one. A floating window is
// created hidden, so a webview that dies during boot leaves no visible trace;
// the creator waits for this event and retires windows that never send it.
const reportReady = (to: string) => emitTo(to, FLOATING_WEBVIEW_READY_EVENT, { label: identity?.windowLabel }).catch(() => undefined);
if (identity) void reportReady(identity.creatorLabel);
void listen<{ from?: unknown }>(FLOATING_WEBVIEW_HELLO_EVENT, (message) => {
const from = message.payload && typeof message.payload.from === "string" ? message.payload.from : "";
if (from && identity) void reportReady(from);
});
// The window is created hidden and reveals itself on the plugin's first paint;
// the fallback covers a plugin that never reports ready, so a broken widget
// cannot stay invisible on the desktop with no way to dismiss it.
revealFallback = setTimeout(() => void reveal(), 2500);
// If the user parked this widget docked to a screen edge, it opens tucked and
// the hover poll brings it back; the poll lives here, in this window.
void resumeFloatingDock();
try {
await props.localeReady?.catch(() => undefined);
if (!identity) {
failure.value = zh.value ? "缺少插件窗口参数" : "missing plugin window parameters";
return;
}
plugins.value = await api.listPlugins();
const definition = plugins.value.find((candidate) => candidate.manifest.id === identity.pluginId) ?? null;
if (!definition) {
failure.value = identity.pluginId;
return;
}
const target = (definition.manifest.contributions || []).find((candidate): candidate is PluginWorkbenchContribution => candidate.type === "workbench" && candidate.id === identity.contributionId) ?? null;
if (!target) {
failure.value = identity.contributionId;
return;
}
plugin.value = definition;
contribution.value = target;
} catch (error) {
failure.value = error instanceof Error ? error.message : String(error);
} finally {
if (failure.value) void reveal();
}
});
onBeforeUnmount(() => {
clearTimeout(revealFallback);
clearTimeout(silenceWatchdog);
window.removeEventListener("message", onPluginMessage);
});
</script>
<template>
<div class="floating-plugin-window relative size-full overflow-hidden bg-transparent">
<PluginWorkbenchHost v-if="plugin && contribution && !failure" :plugin="plugin" :contribution="contribution" :context="hostContext" @ready="onHostReady()" @error="onHostError($event)" @close-tab="void closeWindow()" @open-workbench="onOpenWorkbench" @open-filesystem="onOpenFilesystem" />
<div v-else class="absolute inset-0 flex items-center justify-center p-3">
<!-- Opaque card: an error inside a transparent window would be unreadable
over whatever the user is working on. -->
<div class="flex max-w-xs items-start gap-2 rounded-lg border border-border bg-background p-3 text-xs text-foreground shadow-lg">
<AlertTriangle v-if="failure" class="mt-0.5 size-3.5 shrink-0 text-destructive" />
<Loader2 v-else class="mt-0.5 size-3.5 shrink-0 animate-spin text-muted-foreground" />
<span class="flex-1 break-words">{{ statusText }}</span>
<button v-if="failure" class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="zh ? '关闭' : 'Close'" @click="void closeWindow()">
<X class="size-3.5" />
</button>
</div>
</div>
</div>
</template>
@@ -19,6 +19,8 @@ import {
type PluginAiRecommendationHostUpdate, type PluginAiRecommendationHostUpdate,
} from "@/lib/plugins/pluginHostBridge"; } from "@/lib/plugins/pluginHostBridge";
import { getCachedPluginUiHtml, getOrLoadPluginUiHtml } from "@/lib/plugins/pluginUiHtmlCache"; import { getCachedPluginUiHtml, getOrLoadPluginUiHtml } from "@/lib/plugins/pluginUiHtmlCache";
import { beginFloatingWindowDrag, closeFloatingWindows, endFloatingWindowDrag, openFloatingWindow, setFloatingWindowSize } from "@/lib/plugins/pluginFloatingWindow";
import { isFloatingPluginWindow } from "@/lib/app/windowContext";
import { buildPluginEditorAppearance } from "@/lib/plugins/pluginAppearance"; import { buildPluginEditorAppearance } from "@/lib/plugins/pluginAppearance";
import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin"; import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
import { executePluginCommand } from "@/lib/plugins/pluginCommandRegistry"; import { executePluginCommand } from "@/lib/plugins/pluginCommandRegistry";
@@ -469,6 +471,19 @@ function onHostFileDrop(event: Event): void {
const title = computed(() => `${props.plugin.manifest.name} · ${props.contribution.label}`); const title = computed(() => `${props.plugin.manifest.name} · ${props.contribution.label}`);
/**
* The §8.3 surface this host renders on. The tab surface keeps a minimum height
* (a workbench needs room to be usable); the dock and floating-window surfaces
* are sized by their own container, where a floor would make the frame taller
* than the visible area and swallow clicks near its bottom edge. The floating
* surface is transparent: the widget paints its own shape.
*/
const surface = computed(() => (typeof props.context?.surface === "string" ? props.context.surface : "tab"));
const hostSurfaceClass = computed(() => (surface.value === "tab" ? "min-h-40 bg-background" : surface.value === "window" ? "min-h-0 bg-transparent" : "min-h-0 bg-background"));
/** The loading overlays must not paint an opaque box inside a transparent floating window. */
const overlayClass = computed(() => (surface.value === "window" ? "bg-transparent" : "bg-background"));
const isFloatingSurface = isFloatingPluginWindow();
/** Collect resolved DBX design tokens so the sandbox can theme itself with the same values. */ /** Collect resolved DBX design tokens so the sandbox can theme itself with the same values. */
function currentBridgeTheme(): PluginBridgeTheme { function currentBridgeTheme(): PluginBridgeTheme {
const tokens: Record<string, string> = {}; const tokens: Record<string, string> = {};
@@ -509,8 +524,12 @@ function createBridge() {
// the single-plugin registry is equivalent here because findCommand / // the single-plugin registry is equivalent here because findCommand /
// findWorkbench / enablement never cross plugins. Panel commands dock, // findWorkbench / enablement never cross plugins. Panel commands dock,
// tab commands open tabs, §4.1 reuse with `instance_key` placeholder // tab commands open tabs, §4.1 reuse with `instance_key` placeholder
// scoping — identical to menu execution. // scoping — identical to menu execution. Not offered on the floating
executeCommand: (pluginId, commandId, context) => executePluginCommand(createFrontendPluginRegistry([props.plugin], appLocale.value), useQueryStore(), pluginId, commandId, context), // surface: every command action opens a shell surface (a dock entry or a
// workbench tab) that a floating widget window does not have, so it would
// resolve successfully and show nothing. There, plugins navigate with
// openWorkbench / floating.open, which the host routes to the main window.
...(isFloatingSurface ? {} : { executeCommand: (pluginId: string, commandId: string, context?: Record<string, unknown>) => executePluginCommand(createFrontendPluginRegistry([props.plugin], appLocale.value), useQueryStore(), pluginId, commandId, context) }),
openFilesystem: async (pluginId, providerId, context) => emit("openFilesystem", pluginId, providerId, context), openFilesystem: async (pluginId, providerId, context) => emit("openFilesystem", pluginId, providerId, context),
reopenConnection: (pluginId, connectionId) => useConnectionStore().reopenPluginConnection(connectionId, pluginId), reopenConnection: (pluginId, connectionId) => useConnectionStore().reopenPluginConnection(connectionId, pluginId),
// PR-A4 generic extension point: a read-only, secret-free, plugin-scoped connection list (for in-panel connection switching). // PR-A4 generic extension point: a read-only, secret-free, plugin-scoped connection list (for in-panel connection switching).
@@ -541,6 +560,16 @@ function createBridge() {
await api.setPluginDataGrant(pluginId, connectionId, true); await api.setPluginDataGrant(pluginId, connectionId, true);
}, },
closeTab: () => emit("closeTab"), closeTab: () => emit("closeTab"),
// Floating widget windows (§8.3 surface "window"). Desktop-only: the web
// host omits them so capabilities.floating stays false and the plugin can
// fall back to an in-shell surface. Opening and closing work from any
// window; the geometry calls act on the window that hosts the caller and
// reject elsewhere, so a tab can never move a window it is not inside.
openFloatingWindow: isTauriRuntime() ? (request) => openFloatingWindow(request) : undefined,
closeFloatingWindows: isTauriRuntime() ? (labels) => closeFloatingWindows(labels) : undefined,
beginFloatingDrag: isTauriRuntime() ? () => beginFloatingWindowDrag() : undefined,
endFloatingDrag: isTauriRuntime() ? (snap) => endFloatingWindowDrag(snap) : undefined,
setFloatingSize: isTauriRuntime() ? (width, height) => setFloatingWindowSize(width, height) : undefined,
saveFile: (_pluginId, request, data) => savePluginFile(request, data), saveFile: (_pluginId, request, data) => savePluginFile(request, data),
downloadFile: isTauriRuntime() ? downloadPluginFile : undefined, downloadFile: isTauriRuntime() ? downloadPluginFile : undefined,
cancelDownload: isTauriRuntime() ? cancelPluginDownload : undefined, cancelDownload: isTauriRuntime() ? cancelPluginDownload : undefined,
@@ -794,8 +823,8 @@ onBeforeUnmount(() => {
</script> </script>
<template> <template>
<div class="relative flex size-full min-h-40 overflow-hidden bg-background"> <div class="relative flex size-full overflow-hidden" :class="hostSurfaceClass">
<div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center bg-background text-sm text-muted-foreground"> <div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center text-sm text-muted-foreground" :class="overlayClass">
<Loader2 class="mr-2 size-4 animate-spin" /> <Loader2 class="mr-2 size-4 animate-spin" />
{{ t("pluginPlatform.loadingTitle", { title }) }} {{ t("pluginPlatform.loadingTitle", { title }) }}
</div> </div>
@@ -804,13 +833,17 @@ onBeforeUnmount(() => {
<span>{{ error }}</span> <span>{{ error }}</span>
</div> </div>
<template v-else> <template v-else>
<iframe ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" allow="clipboard-write" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" /> <!-- `allow` delegates fullscreen into the sandboxed frame: without the
Permissions-Policy entry, requestFullscreen() rejects there no matter
which sandbox tokens are set (the legacy `allow-fullscreen` sandbox
flag was removed from the platform and logs an error when present). -->
<iframe ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" allow="clipboard-write; fullscreen" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
<!-- Cover until the frame has actually painted: the iframe stays mounted <!-- Cover until the frame has actually painted: the iframe stays mounted
underneath so its load event can fire (v-else on the overlay would underneath so its load event can fire (v-else on the overlay would
deadlock), it just isn't visible yet. Fully opaque so the covered deadlock), it just isn't visible yet. Fully opaque so the covered
phase is visually identical to the host background, and faded out phase is visually identical to the host background, and faded out
instead of removed so the reveal is never a hard swap. --> instead of removed so the reveal is never a hard swap. -->
<div class="absolute inset-0 z-10 flex items-center justify-center bg-background text-sm text-muted-foreground transition-opacity duration-150 ease-out" :class="frameReady ? 'pointer-events-none opacity-0' : 'opacity-100'"> <div class="absolute inset-0 z-10 flex items-center justify-center text-sm text-muted-foreground transition-opacity duration-150 ease-out" :class="[overlayClass, frameReady ? 'pointer-events-none opacity-0' : 'opacity-100']">
<Loader2 class="mr-2 size-4 animate-spin" /> <Loader2 class="mr-2 size-4 animate-spin" />
{{ t("pluginPlatform.loadingTitle", { title }) }} {{ t("pluginPlatform.loadingTitle", { title }) }}
</div> </div>
+106 -4
View File
@@ -1,8 +1,20 @@
import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
export type WindowContext = { kind: "main"; windowLabel: "main" } | { kind: "detached-tab"; windowLabel: string; tabId: string }; export type WindowContext =
| { kind: "main"; windowLabel: "main" }
| { kind: "detached-tab"; windowLabel: string; tabId: string }
/** A floating plugin window: one plugin workbench rendered outside the shell (§8.3 surface "window"). */
| { kind: "plugin-window"; windowLabel: string; pluginId: string; contributionId: string; creatorLabel: string; pluginContext?: Record<string, unknown> };
const DETACHED_WINDOW_PARAM = "dbxDetachedTab"; const DETACHED_WINDOW_PARAM = "dbxDetachedTab";
const PLUGIN_WINDOW_PARAM = "dbxPluginWindow";
const PLUGIN_WINDOW_CONTRIBUTION_PARAM = "dbxPluginContribution";
const PLUGIN_WINDOW_CONTEXT_PARAM = "dbxPluginWindowContext";
/** Label of the window that created this floating window, so the widget can report liveness back to it. */
const PLUGIN_WINDOW_CREATOR_PARAM = "dbxPluginWindowFrom";
const FLOATING_WINDOW_LABEL_PREFIX = "plugin-floating-";
/** Bound for the URL-carried plugin context: it is routing state, not a data channel. */
export const MAX_PLUGIN_WINDOW_CONTEXT_BYTES = 4 * 1024;
let cachedContext: WindowContext | undefined; let cachedContext: WindowContext | undefined;
@@ -10,6 +22,64 @@ export function detachedWindowLabel(tabId: string): string {
return `detached-tab-${tabId}`; return `detached-tab-${tabId}`;
} }
/**
* Deterministic label for a plugin's floating window: one window per
* (plugin, workbench contribution) pair, so reopening focuses the existing
* window instead of stacking widgets. Tauri only allows alphanumeric, `-`,
* `/`, `:` and `_` in labels, so plugin ids (dots) are slugged and a short hash
* of the raw pair keeps slugs that differ only in stripped characters apart.
* Labels are also the capability-scope pattern (`plugin-floating-*`), and an
* over-long pair is folded into hashes.
*/
export function floatingWindowLabel(pluginId: string, contributionId: string): string {
const raw = `${pluginId}/${contributionId}`;
const slug = raw.replace(/[^A-Za-z0-9_-]+/g, "-");
const label = `${FLOATING_WINDOW_LABEL_PREFIX}${slug}-${stableHash(raw)}`;
return label.length <= 120 ? label : `${FLOATING_WINDOW_LABEL_PREFIX}${stableHash(pluginId)}-${stableHash(contributionId)}`;
}
export function isFloatingWindowLabel(label: string): boolean {
return label.startsWith(FLOATING_WINDOW_LABEL_PREFIX);
}
function stableHash(value: string): string {
let hash = 0x811c9dc5;
for (let index = 0; index < value.length; index += 1) {
hash ^= value.charCodeAt(index);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return hash.toString(36);
}
/**
* Plugin context rides the window URL (base64url JSON) because the floating
* window resolves it synchronously at boot; a cross-window event handoff would
* race the first render. `undefined` when absent, oversized, or malformed —
* a floating window still boots, it just starts without extra context.
*/
export function encodeFloatingPluginContext(context: Record<string, unknown> | undefined): string | undefined {
if (!context || !Object.keys(context).length) return undefined;
const json = JSON.stringify(context);
if (new TextEncoder().encode(json).byteLength > MAX_PLUGIN_WINDOW_CONTEXT_BYTES) return undefined;
const bytes = new TextEncoder().encode(json);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export function decodeFloatingPluginContext(raw: string | undefined): Record<string, unknown> | undefined {
if (!raw) return undefined;
try {
const padded = raw.replace(/-/g, "+").replace(/_/g, "/");
const binary = atob(padded + "=".repeat((4 - (padded.length % 4)) % 4));
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
const value = JSON.parse(new TextDecoder().decode(bytes));
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
} catch {
return undefined;
}
}
export function resolveWindowContext(): WindowContext { export function resolveWindowContext(): WindowContext {
if (cachedContext) return cachedContext; if (cachedContext) return cachedContext;
if (!isTauriRuntime()) { if (!isTauriRuntime()) {
@@ -17,15 +87,32 @@ export function resolveWindowContext(): WindowContext {
return cachedContext; return cachedContext;
} }
const tabId = new URLSearchParams(window.location.search).get(DETACHED_WINDOW_PARAM)?.trim(); const search = new URLSearchParams(window.location.search);
const tabId = search.get(DETACHED_WINDOW_PARAM)?.trim();
if (tabId) { if (tabId) {
// The window label is not available synchronously from the Tauri API. The // The window label is not available synchronously from the Tauri API. The
// deterministic label is also what the creator uses, so it is sufficient // deterministic label is also what the creator uses, so it is sufficient
// for routing and event targeting during bootstrap. // for routing and event targeting during bootstrap.
cachedContext = { kind: "detached-tab", windowLabel: detachedWindowLabel(tabId), tabId }; cachedContext = { kind: "detached-tab", windowLabel: detachedWindowLabel(tabId), tabId };
} else { return cachedContext;
cachedContext = { kind: "main", windowLabel: "main" };
} }
const pluginId = search.get(PLUGIN_WINDOW_PARAM)?.trim();
const contributionId = search.get(PLUGIN_WINDOW_CONTRIBUTION_PARAM)?.trim();
if (pluginId && contributionId) {
const pluginContext = decodeFloatingPluginContext(search.get(PLUGIN_WINDOW_CONTEXT_PARAM)?.trim());
cachedContext = {
kind: "plugin-window",
windowLabel: floatingWindowLabel(pluginId, contributionId),
pluginId,
contributionId,
creatorLabel: search.get(PLUGIN_WINDOW_CREATOR_PARAM)?.trim() || "main",
...(pluginContext ? { pluginContext } : {}),
};
return cachedContext;
}
cachedContext = { kind: "main", windowLabel: "main" };
return cachedContext; return cachedContext;
} }
@@ -33,6 +120,10 @@ export function isDetachedWindow(): boolean {
return resolveWindowContext().kind === "detached-tab"; return resolveWindowContext().kind === "detached-tab";
} }
export function isFloatingPluginWindow(): boolean {
return resolveWindowContext().kind === "plugin-window";
}
export function detachedTabId(): string | undefined { export function detachedTabId(): string | undefined {
const context = resolveWindowContext(); const context = resolveWindowContext();
return context.kind === "detached-tab" ? context.tabId : undefined; return context.kind === "detached-tab" ? context.tabId : undefined;
@@ -44,3 +135,14 @@ export function detachedWindowUrl(tabId: string): string {
url.hash = ""; url.hash = "";
return url.toString(); return url.toString();
} }
export function floatingWindowUrl(pluginId: string, contributionId: string, context?: Record<string, unknown>, creatorLabel?: string): string {
const url = new URL(window.location.href);
const search = new URLSearchParams({ [PLUGIN_WINDOW_PARAM]: pluginId, [PLUGIN_WINDOW_CONTRIBUTION_PARAM]: contributionId });
const encodedContext = encodeFloatingPluginContext(context);
if (encodedContext) search.set(PLUGIN_WINDOW_CONTEXT_PARAM, encodedContext);
if (creatorLabel) search.set(PLUGIN_WINDOW_CREATOR_PARAM, creatorLabel);
url.search = search.toString();
url.hash = "";
return url.toString();
}
@@ -0,0 +1,323 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import {
clampFloatingSize,
defaultFloatingPosition,
dockRectsForEdge,
FLOATING_EDGE_MARGIN_PX,
FLOATING_MAX_HEIGHT_PX,
FLOATING_MAX_WIDTH_PX,
FLOATING_MIN_HEIGHT_PX,
FLOATING_MIN_WIDTH_PX,
FLOATING_SNAP_THRESHOLD_PX,
parseFloatingPosition,
parseFloatingWindowRequest,
pickMonitorForPoint,
pointInsideWorkArea,
resolveFloatingPlacement,
snapRectToWorkArea,
type FloatingMonitor,
} from "@/lib/plugins/pluginFloatingWindow";
import { MAX_PLUGIN_WINDOW_CONTEXT_BYTES, decodeFloatingPluginContext, encodeFloatingPluginContext, floatingWindowLabel, floatingWindowUrl, isFloatingWindowLabel } from "@/lib/app/windowContext";
/** A 1920x1080 monitor whose taskbar takes the bottom 40px, at 1x DPI. */
const monitor: FloatingMonitor = { x: 0, y: 0, width: 1920, height: 1040, scaleFactor: 1 };
/** A second monitor to the right, at 2x DPI, with its own taskbar. */
const hidpiMonitor: FloatingMonitor = { x: 1920, y: 0, width: 3840, height: 2080, scaleFactor: 2 };
describe("snapRectToWorkArea", () => {
it("pulls a window onto an edge it landed near and reports that edge", () => {
const result = snapRectToWorkArea({ x: 12, y: 500, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(result.rect.x).toBe(FLOATING_EDGE_MARGIN_PX);
expect(result.rect.y).toBe(500);
expect(result.edges).toEqual(["left"]);
});
it("snaps both axes in a corner", () => {
const result = snapRectToWorkArea({ x: 1660, y: 980, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: 80 });
expect(result.rect).toEqual({ x: 1920 - FLOATING_EDGE_MARGIN_PX - 260, y: 1040 - FLOATING_EDGE_MARGIN_PX - 60, width: 260, height: 60 });
expect(result.edges).toEqual(["right", "bottom"]);
});
it("leaves a window in the middle of the work area where the user dropped it", () => {
const result = snapRectToWorkArea({ x: 800, y: 400, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(result.rect).toEqual({ x: 800, y: 400, width: 260, height: 60 });
expect(result.edges).toEqual([]);
});
it("snaps a window shoved past an edge onto that edge, so it is never lost off-screen", () => {
// A drag tracks the native cursor with no lower bound, so pushing the widget
// against a border lands the release well outside the threshold band. That
// overshoot is the intent to dock, and the result is still fully on screen.
const result = snapRectToWorkArea({ x: 2400, y: -300, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(result.edges).toEqual(["right", "top"]);
expect(result.rect).toEqual({ x: 1920 - FLOATING_EDGE_MARGIN_PX - 260, y: FLOATING_EDGE_MARGIN_PX, width: 260, height: 60 });
});
it("snaps anywhere along an edge, not only where the threshold band reaches", () => {
const shovedLeft = snapRectToWorkArea({ x: -140, y: 500, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(shovedLeft.edges).toEqual(["left"]);
expect(shovedLeft.rect.x).toBe(FLOATING_EDGE_MARGIN_PX);
expect(shovedLeft.rect.y).toBe(500);
const shovedBottom = snapRectToWorkArea({ x: 800, y: 1200, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(shovedBottom.edges).toEqual(["bottom"]);
expect(shovedBottom.rect.y).toBe(1040 - FLOATING_EDGE_MARGIN_PX - 60);
expect(shovedBottom.rect.x).toBe(800);
});
it("scales the margin and threshold by the monitor DPI, so a snap feels the same on every display", () => {
// 40 physical px from the edge is inside the 28 logical px threshold on a 2x
// monitor (56 physical px), so it snaps onto the 16 logical px (32 physical) margin.
const hidpi = snapRectToWorkArea({ x: 1920 + 32 + 40, y: 500, width: 520, height: 120 }, hidpiMonitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(hidpi.rect.x).toBe(1920 + FLOATING_EDGE_MARGIN_PX * 2);
expect(hidpi.edges).toEqual(["left"]);
// The same 40 physical px on a 1x monitor is outside the threshold and stays put.
const standard = snapRectToWorkArea({ x: FLOATING_EDGE_MARGIN_PX + 40, y: 500, width: 260, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
expect(standard.rect.x).toBe(FLOATING_EDGE_MARGIN_PX + 40);
expect(standard.edges).toEqual([]);
});
it("keeps a window larger than the work area reachable instead of snapping it", () => {
const result = snapRectToWorkArea({ x: -500, y: 500, width: 4000, height: 60 }, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
// No edge is meaningful when the window is wider than the work area, so the
// inverted range only has to keep part of it on screen — the drop position stands.
expect(result.edges).toEqual([]);
expect(result.rect.x).toBe(-500);
expect(result.rect.x).toBeGreaterThanOrEqual(1920 - FLOATING_EDGE_MARGIN_PX - 4000);
expect(result.rect.x).toBeLessThanOrEqual(FLOATING_EDGE_MARGIN_PX);
});
});
describe("dockRectsForEdge", () => {
const rect = { x: 1600, y: 500, width: 260, height: 60 };
it("tucks a right-docked widget off-screen leaving exactly the sliver", () => {
const dock = dockRectsForEdge(rect, monitor, "right", 14);
expect(dock.revealed).toEqual({ x: 1920 - 260, y: 500 });
expect(dock.tucked).toEqual({ x: 1920 - 14, y: 500 });
expect(dock.sliver).toEqual({ x: 1920 - 14, y: 500, width: 14, height: 60 });
});
it("tucks a left-docked widget the other way, sliver flush to the edge", () => {
const dock = dockRectsForEdge(rect, monitor, "left", 14);
expect(dock.revealed).toEqual({ x: 0, y: 500 });
expect(dock.tucked).toEqual({ x: 14 - 260, y: 500 });
expect(dock.sliver).toEqual({ x: 0, y: 500, width: 14, height: 60 });
});
it("tucks a bottom-docked widget vertically", () => {
const dock = dockRectsForEdge(rect, monitor, "bottom", 14);
expect(dock.revealed).toEqual({ x: 1600, y: 1040 - 60 });
expect(dock.tucked).toEqual({ x: 1600, y: 1040 - 14 });
expect(dock.sliver).toEqual({ x: 1600, y: 1040 - 14, width: 260, height: 14 });
});
it("scales the sliver by the monitor DPI", () => {
const hidpiRect = { x: 2200, y: 500, width: 520, height: 120 };
const dock = dockRectsForEdge(hidpiRect, hidpiMonitor, "right", 14);
expect(dock.revealed).toEqual({ x: 1920 + 3840 - 520, y: 500 });
expect(dock.tucked).toEqual({ x: 1920 + 3840 - 28, y: 500 });
expect(dock.sliver.width).toBe(28);
});
});
describe("resolveFloatingPlacement with a docked position", () => {
it("restores a docked home like any on-screen point (it stores the revealed position)", () => {
// Right-docked and revealed: flush to the edge, fully on screen.
const placement = resolveFloatingPlacement({ x: 1920 - 260, y: 500, scaleFactor: 1, edge: "right" }, [monitor], { width: 260, height: 60 });
expect(placement).toEqual({ x: 1920 - 260, y: 500, restored: true });
});
it("falls back to the default when a docked home lost its monitor", () => {
const placement = resolveFloatingPlacement({ x: 1920 - 260, y: 500, scaleFactor: 1, edge: "right" }, [hidpiMonitor], { width: 260, height: 60 });
expect(placement.restored).toBe(false);
expect(placement.x).toBeGreaterThan(hidpiMonitor.x);
});
it("keeps the dock edge through the storage round-trip", () => {
expect(parseFloatingPosition(JSON.stringify({ x: 1, y: 2, scaleFactor: 1.5, edge: "bottom" }))).toEqual({ x: 1, y: 2, scaleFactor: 1.5, edge: "bottom" });
expect(parseFloatingPosition(JSON.stringify({ x: 1, y: 2, scaleFactor: 1, edge: "diagonal" }))).toEqual({ x: 1, y: 2, scaleFactor: 1 });
});
});
describe("monitor lookup", () => {
it("picks the monitor that contains the point and falls back to the first one", () => {
expect(pointInsideWorkArea({ x: 2000, y: 100 }, hidpiMonitor)).toBe(true);
expect(pickMonitorForPoint({ x: 2000, y: 100 }, [monitor, hidpiMonitor])).toBe(hidpiMonitor);
expect(pickMonitorForPoint({ x: 100, y: 100 }, [monitor, hidpiMonitor])).toBe(monitor);
// A point on no monitor (display unplugged between reads) still gets a target.
expect(pickMonitorForPoint({ x: -9000, y: -9000 }, [monitor, hidpiMonitor])).toBe(monitor);
expect(pickMonitorForPoint({ x: 0, y: 0 }, [])).toBeNull();
});
});
describe("clampFloatingSize", () => {
it("clamps into the floating bounds and falls back to the minimum for garbage", () => {
expect(clampFloatingSize(260, 60)).toEqual({ width: 260, height: 60 });
expect(clampFloatingSize(10, 4)).toEqual({ width: FLOATING_MIN_WIDTH_PX, height: FLOATING_MIN_HEIGHT_PX });
expect(clampFloatingSize(99_999, 99_999)).toEqual({ width: FLOATING_MAX_WIDTH_PX, height: FLOATING_MAX_HEIGHT_PX });
expect(clampFloatingSize(Number.NaN, Number.POSITIVE_INFINITY)).toEqual({ width: FLOATING_MIN_WIDTH_PX, height: FLOATING_MIN_HEIGHT_PX });
expect(clampFloatingSize(260.6, 60.4)).toEqual({ width: 261, height: 60 });
});
});
describe("defaultFloatingPosition", () => {
it("lands in the bottom-right corner of the work area, clear of the edge", () => {
expect(defaultFloatingPosition(monitor, { width: 260, height: 60 }, FLOATING_EDGE_MARGIN_PX)).toEqual({ x: 1920 - FLOATING_EDGE_MARGIN_PX - 260, y: 1040 - FLOATING_EDGE_MARGIN_PX - 60 });
});
it("scales the logical size and margin for a HiDPI monitor", () => {
expect(defaultFloatingPosition(hidpiMonitor, { width: 260, height: 60 }, FLOATING_EDGE_MARGIN_PX)).toEqual({ x: 1920 + 3840 - 32 - 520, y: 2080 - 32 - 120 });
});
it("never pushes the window off the top-left of a work area smaller than the window", () => {
const tiny: FloatingMonitor = { x: 100, y: 100, width: 120, height: 80, scaleFactor: 1 };
expect(defaultFloatingPosition(tiny, { width: 260, height: 60 }, FLOATING_EDGE_MARGIN_PX)).toEqual({ x: 116, y: 116 });
});
});
describe("resolveFloatingPlacement", () => {
const size = { width: 260, height: 60 };
it("restores the stored position when it still lands on a connected monitor", () => {
const placement = resolveFloatingPlacement({ x: 400, y: 300, scaleFactor: 1 }, [monitor], size);
expect(placement).toEqual({ x: 400, y: 300, restored: true });
});
it("pulls a stored position that hangs over the edge back inside the work area", () => {
// The taskbar grew since the position was stored: the point now sits in it.
// Restore clamps the point a margin away from every edge — the window's real
// size is not known yet, so it must not be part of the math.
const placement = resolveFloatingPlacement({ x: 1915, y: 1035, scaleFactor: 1 }, [monitor], size);
expect(placement.restored).toBe(true);
expect(placement.x).toBe(1920 - FLOATING_EDGE_MARGIN_PX);
expect(placement.y).toBe(1040 - FLOATING_EDGE_MARGIN_PX);
});
it("falls back to the work-area default when the stored position is on a monitor that is gone", () => {
const placement = resolveFloatingPlacement({ x: 5000, y: 3000, scaleFactor: 1 }, [monitor], size);
expect(placement).toEqual({ ...defaultFloatingPosition(monitor, size, FLOATING_EDGE_MARGIN_PX), restored: false });
});
it("falls back to the origin when no monitor is known at all", () => {
expect(resolveFloatingPlacement({ x: 400, y: 300, scaleFactor: 1 }, [], size)).toEqual({ x: 0, y: 0, restored: false });
});
it("opens on the monitor the caller is on, not just the first connected one", () => {
const placement = resolveFloatingPlacement(null, [monitor, hidpiMonitor], size, hidpiMonitor);
expect(placement.restored).toBe(false);
expect(placement).toEqual({ ...defaultFloatingPosition(hidpiMonitor, size, FLOATING_EDGE_MARGIN_PX), restored: false });
});
});
describe("parseFloatingPosition", () => {
it("reads back what was persisted and rejects anything malformed", () => {
expect(parseFloatingPosition(JSON.stringify({ x: 10, y: -20, scaleFactor: 2 }))).toEqual({ x: 10, y: -20, scaleFactor: 2 });
// A missing or non-positive scale factor is normalized, not rejected: the
// position itself is still usable.
expect(parseFloatingPosition(JSON.stringify({ x: 10, y: 20 }))).toEqual({ x: 10, y: 20, scaleFactor: 1 });
expect(parseFloatingPosition(JSON.stringify({ x: 10, y: 20, scaleFactor: 0 }))).toEqual({ x: 10, y: 20, scaleFactor: 1 });
expect(parseFloatingPosition(null)).toBeNull();
expect(parseFloatingPosition("")).toBeNull();
expect(parseFloatingPosition("not json")).toBeNull();
expect(parseFloatingPosition(JSON.stringify({ x: 10 }))).toBeNull();
expect(parseFloatingPosition(JSON.stringify({ x: "10", y: 20 }))).toBeNull();
expect(parseFloatingPosition(JSON.stringify({ x: Number.NaN, y: 20 }))).toBeNull();
});
});
describe("parseFloatingWindowRequest", () => {
it("keeps the host-supplied plugin id and passes through the declared options", () => {
const request = parseFloatingWindowRequest("io.dbx.demo", {
contributionId: "capsule",
title: " Now playing ",
width: 260,
height: 60,
alwaysOnTop: false,
context: { queueId: "q1" },
// A plugin cannot open a window for somebody else's plugin.
pluginId: "io.dbx.other",
});
expect(request).toEqual({
pluginId: "io.dbx.demo",
contributionId: "capsule",
title: "Now playing",
width: 260,
height: 60,
alwaysOnTop: false,
context: { queueId: "q1" },
});
});
it("omits options the plugin did not send, so host defaults apply", () => {
expect(parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule" })).toEqual({ pluginId: "io.dbx.demo", contributionId: "capsule" });
expect(parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule", title: " ", context: null })).toEqual({ pluginId: "io.dbx.demo", contributionId: "capsule" });
});
it("rejects malformed input instead of forwarding it to the window manager", () => {
expect(() => parseFloatingWindowRequest("io.dbx.demo", {})).toThrow(/contributionId/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "" })).toThrow(/contributionId/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "../escape" })).toThrow(/contributionId/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: 42 as unknown as string })).toThrow(/contributionId/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule", width: "260" })).toThrow(/width/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule", height: Number.NaN })).toThrow(/height/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule", x: "10" })).toThrow(/x must be a finite number/);
expect(() => parseFloatingWindowRequest("io.dbx.demo", { contributionId: "capsule", context: [1, 2] })).toThrow(/context/);
});
});
describe("floating window identity", () => {
it("derives a deterministic label per plugin and contribution, so reopening focuses the same window", () => {
const label = floatingWindowLabel("io.dbx.demo", "capsule");
expect(label).toBe(floatingWindowLabel("io.dbx.demo", "capsule"));
expect(label.startsWith("plugin-floating-")).toBe(true);
expect(isFloatingWindowLabel(label)).toBe(true);
// Other window kinds must never be addressable through the floating path.
expect(isFloatingWindowLabel("main")).toBe(false);
expect(isFloatingWindowLabel("detached-tab-1234")).toBe(false);
});
it("keeps the label inside Tauri's charset (no dots) and inside the length bound", () => {
// Tauri rejects window labels outside alphanumeric + - / : _ — plugin ids are
// full of dots, so they must never reach the label verbatim.
for (const label of [floatingWindowLabel("io.dbx.demo", "capsule"), floatingWindowLabel("io.dbx.demo", "cap sule/with symbols")]) {
expect(label).toMatch(/^plugin-floating-[A-Za-z0-9_/-]+$/);
expect(label).not.toMatch(/\./);
}
// Slugs that differ only in stripped characters stay apart through the hash:
// "io.dbx.demo" and "io-dbx-demo" must not share a window.
expect(floatingWindowLabel("io.dbx.demo", "capsule")).not.toBe(floatingWindowLabel("io-dbx-demo", "capsule"));
const long = floatingWindowLabel("io.dbx.".concat("a".repeat(200)), "contribution");
expect(long.startsWith("plugin-floating-")).toBe(true);
expect(long.length).toBeLessThanOrEqual(120);
expect(long).toBe(floatingWindowLabel("io.dbx.".concat("a".repeat(200)), "contribution"));
expect(long).not.toBe(floatingWindowLabel("io.dbx.".concat("a".repeat(200)), "other"));
});
it("carries the plugin identity and bounded context in the window url", () => {
const url = new URL(floatingWindowUrl("io.dbx.demo", "capsule", { queueId: "q1" }));
expect(url.searchParams.get("dbxPluginWindow")).toBe("io.dbx.demo");
expect(url.searchParams.get("dbxPluginContribution")).toBe("capsule");
expect(decodeFloatingPluginContext(url.searchParams.get("dbxPluginWindowContext") ?? undefined)).toEqual({ queueId: "q1" });
expect(url.hash).toBe("");
// No context: no parameter at all, so the url stays readable.
expect(new URL(floatingWindowUrl("io.dbx.demo", "capsule")).searchParams.has("dbxPluginWindowContext")).toBe(false);
});
it("round-trips the context codec and drops payloads that do not fit", () => {
expect(decodeFloatingPluginContext(encodeFloatingPluginContext({ a: 1, b: ["x", null], c: { d: true } }))).toEqual({ a: 1, b: ["x", null], c: { d: true } });
// Non-ASCII survives the UTF-8 round trip.
expect(decodeFloatingPluginContext(encodeFloatingPluginContext({ title: "夜曲 · Live" }))).toEqual({ title: "夜曲 · Live" });
expect(encodeFloatingPluginContext(undefined)).toBeUndefined();
expect(encodeFloatingPluginContext({})).toBeUndefined();
expect(encodeFloatingPluginContext({ blob: "x".repeat(MAX_PLUGIN_WINDOW_CONTEXT_BYTES) })).toBeUndefined();
expect(decodeFloatingPluginContext(undefined)).toBeUndefined();
expect(decodeFloatingPluginContext("!!!not base64!!!")).toBeUndefined();
// Valid base64url of a non-object is still not a context.
expect(decodeFloatingPluginContext(encodeFloatingPluginContext({ a: 1 })?.replace(/./g, "e") ?? "")).toBeUndefined();
});
});
@@ -0,0 +1,893 @@
// Floating plugin windows — the `window` surface of the plugin UI spec (§8.3
// surface vocabulary): a frameless, always-on-top desktop window that hosts one
// plugin workbench outside the main shell, so a plugin can keep a small widget
// (player capsule, session badge, quick picker) visible while the user works in
// other applications.
//
// The window is an ordinary DBX webview: it boots the same bundle and renders
// PluginFloatingWindow.vue instead of the workbench shell (see main.ts). All
// geometry stays host-owned — a plugin drives its own window through the bridge
// (`dbxPlugin.floating`) and never receives a window handle, so it cannot move,
// resize, or close anything but the window that hosts it.
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
import { floatingWindowLabel, floatingWindowUrl, isFloatingPluginWindow, isFloatingWindowLabel, resolveWindowContext } from "@/lib/app/windowContext";
/** Logical (CSS pixel) bounds for a floating window. */
export const FLOATING_MIN_WIDTH_PX = 64;
export const FLOATING_MIN_HEIGHT_PX = 40;
export const FLOATING_MAX_WIDTH_PX = 4096;
export const FLOATING_MAX_HEIGHT_PX = 4096;
/** Logical size used when a plugin does not ask for one. */
export const FLOATING_DEFAULT_WIDTH_PX = 320;
export const FLOATING_DEFAULT_HEIGHT_PX = 200;
/** Gap kept between a snapped window and the work-area edge, in logical pixels. */
export const FLOATING_EDGE_MARGIN_PX = 16;
/** Distance from a work-area edge (logical pixels) that pulls the window onto it when a drag ends. A release past the edge always snaps, so this only widens the band on the inner side. */
export const FLOATING_SNAP_THRESHOLD_PX = 28;
/** Width of the strip an edge-docked widget leaves on screen, in logical pixels. */
export const FLOATING_DOCK_SLIVER_PX = 14;
/**
* How long a docked widget stays a fully visible capsule before it tucks away:
* measured from the last moment the cursor was over it, so aiming the widget is
* never interrupted, and a reopened widget gets this much time to be read.
*/
const FLOATING_DOCK_IDLE_MS = 2_500;
const FLOATING_DOCK_POLL_MS = 150;
/** Extra hit area around the dock strip, in physical pixels. */
const FLOATING_DOCK_HOVER_PAD_PX = 8;
/** A drag nobody ends (the webview lost the pointerup) must not keep the window glued to the cursor. */
const FLOATING_DRAG_TIMEOUT_MS = 30_000;
/**
* Cursor quiet period after which a drag counts as released. The plugin's
* pointerup is the normal end and arrives reliably, so this only has to catch a
* webview that lost the pointer — long enough that aiming the widget with a
* deliberate mid-drag pause does not drop the gesture.
*/
const FLOATING_DRAG_IDLE_MS = 1_500;
const FLOATING_CREATE_TIMEOUT_MS = 10_000;
const FLOATING_POSITION_STORAGE_PREFIX = "dbx-plugin-floating-window:";
export interface FloatingRect {
x: number;
y: number;
width: number;
height: number;
}
/** One connected monitor: its work area (screen minus taskbar/dock) in physical pixels, plus the DPI scale. */
export interface FloatingMonitor {
x: number;
y: number;
width: number;
height: number;
scaleFactor: number;
}
/** Where the user last left a plugin's floating window: a physical point and the DPI scale it was captured at. */
export interface FloatingPosition {
x: number;
y: number;
scaleFactor: number;
/** Set when the position is an edge-docked (mostly off-screen) home. */
edge?: FloatingDockEdge;
}
export interface OpenFloatingWindowRequest {
pluginId: string;
contributionId: string;
/** Window title (taskbar/tooltips); the plugin's own UI stays chrome-less. */
title?: string;
/** Logical size, clamped to the floating bounds. */
width?: number;
height?: number;
/** Physical screen position. Omitted restores where the user last left the window. */
x?: number;
y?: number;
alwaysOnTop?: boolean;
skipTaskbar?: boolean;
resizable?: boolean;
/** Host-forwarded plugin context, delivered as `dbxPlugin.context` (bounded, see windowContext). */
context?: Record<string, unknown>;
}
export interface OpenFloatingWindowResult {
/** Opaque window id (the deterministic host label). */
windowId: string;
reused: boolean;
}
export interface SnapFloatingResult {
rect: FloatingRect;
/** Work-area edges the window was pulled onto. */
edges: Array<"left" | "right" | "top" | "bottom">;
}
/**
* Pulls a physical rect onto the work-area edges it landed near or past, then
* clamps it fully inside, so a released widget is never half off-screen.
* `margin` and `threshold` are logical pixels and are scaled by the monitor DPI
* here. Pure: no window access, so the geometry rules are unit-testable.
*/
export function snapRectToWorkArea(rect: FloatingRect, monitor: FloatingMonitor, options?: { margin?: number; threshold?: number }): SnapFloatingResult {
const scale = monitor.scaleFactor > 0 ? monitor.scaleFactor : 1;
const margin = Math.max(0, Math.round((options?.margin ?? 0) * scale));
const threshold = Math.max(0, Math.round((options?.threshold ?? 0) * scale));
const edges: SnapFloatingResult["edges"] = [];
const x = snapAxis(rect.x, monitor.x + margin, monitor.x + monitor.width - margin - rect.width, threshold, "left", "right", edges);
const y = snapAxis(rect.y, monitor.y + margin, monitor.y + monitor.height - margin - rect.height, threshold, "top", "bottom", edges);
return { rect: { x, y, width: rect.width, height: rect.height }, edges };
}
function snapAxis(value: number, min: number, max: number, threshold: number, minEdge: "left" | "top", maxEdge: "right" | "bottom", edges: SnapFloatingResult["edges"]): number {
// A window wider/taller than the work area has no edge to snap to; keep it
// reachable by clamping into the (inverted) range instead.
if (max < min) return Math.min(Math.max(value, max), min);
let next = value;
// At or past the edge always snaps: a drag tracks the cursor without a lower
// bound, so shoving the widget against a border lands it well outside any
// threshold band — and that overshoot is the intent to dock, not a miss.
if (value <= min + threshold) {
next = min;
edges.push(minEdge);
} else if (value >= max - threshold) {
next = max;
edges.push(maxEdge);
}
return Math.min(Math.max(next, min), max);
}
export type FloatingDockEdge = "left" | "right" | "top" | "bottom";
export interface FloatingDockRects {
/** Flush against the edge, fully on screen: the hover-revealed position. */
revealed: { x: number; y: number };
/** Slid out past the edge until only `sliver` pixels stay visible. */
tucked: { x: number; y: number };
/** The on-screen strip of the tucked window — the hover target. */
sliver: FloatingRect;
}
/**
* Geometry of an edge-docked widget: where it sits revealed (flush to the edge),
* where it hides (all but a sliver off-screen), and the strip that stays
* clickable while hidden. Pure, in physical pixels, so the rules are testable.
*/
export function dockRectsForEdge(rect: FloatingRect, monitor: FloatingMonitor, edge: FloatingDockEdge, sliverLogical: number): FloatingDockRects {
const scale = monitor.scaleFactor > 0 ? monitor.scaleFactor : 1;
const sliver = Math.max(1, Math.round(sliverLogical * scale));
const clampX = (x: number) => Math.min(Math.max(x, monitor.x), monitor.x + Math.max(0, monitor.width - rect.width));
const clampY = (y: number) => Math.min(Math.max(y, monitor.y), monitor.y + Math.max(0, monitor.height - rect.height));
if (edge === "left" || edge === "right") {
const revealedX = edge === "left" ? monitor.x : monitor.x + monitor.width - rect.width;
const y = clampY(rect.y);
const tuckedX = edge === "left" ? revealedX - rect.width + sliver : revealedX + rect.width - sliver;
const sliverX = edge === "left" ? tuckedX + rect.width - sliver : tuckedX;
return { revealed: { x: revealedX, y }, tucked: { x: tuckedX, y }, sliver: { x: sliverX, y, width: sliver, height: rect.height } };
}
const revealedY = edge === "top" ? monitor.y : monitor.y + monitor.height - rect.height;
const x = clampX(rect.x);
const tuckedY = edge === "top" ? revealedY - rect.height + sliver : revealedY + rect.height - sliver;
const sliverY = edge === "top" ? tuckedY + rect.height - sliver : tuckedY;
return { revealed: { x, y: revealedY }, tucked: { x, y: tuckedY }, sliver: { x, y: sliverY, width: rect.width, height: sliver } };
}
function pointInRect(point: { x: number; y: number }, rect: FloatingRect, pad: number): boolean {
return point.x >= rect.x - pad && point.x <= rect.x + rect.width + pad && point.y >= rect.y - pad && point.y <= rect.y + rect.height + pad;
}
/** Clamps a requested logical size into the floating bounds; non-finite input falls back to the minimum. */
export function clampFloatingSize(width: number, height: number): { width: number; height: number } {
const clamp = (value: number, min: number, max: number) => (Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : min);
return {
width: clamp(width, FLOATING_MIN_WIDTH_PX, FLOATING_MAX_WIDTH_PX),
height: clamp(height, FLOATING_MIN_HEIGHT_PX, FLOATING_MAX_HEIGHT_PX),
};
}
/** Default placement: the bottom-right corner of the work area, clear of the edge. `size` is logical. */
export function defaultFloatingPosition(monitor: FloatingMonitor, size: { width: number; height: number }, margin: number): { x: number; y: number } {
const scale = monitor.scaleFactor > 0 ? monitor.scaleFactor : 1;
const gap = Math.round(margin * scale);
return {
x: Math.round(monitor.x + Math.max(gap, monitor.width - gap - Math.round(size.width * scale))),
y: Math.round(monitor.y + Math.max(gap, monitor.height - gap - Math.round(size.height * scale))),
};
}
/** True when the point lies inside the work area; used to reject positions stored for a monitor that is gone. */
export function pointInsideWorkArea(point: { x: number; y: number }, monitor: FloatingMonitor): boolean {
return point.x >= monitor.x && point.x <= monitor.x + monitor.width && point.y >= monitor.y && point.y <= monitor.y + monitor.height;
}
/** The monitor containing the point, else the first one, else null. */
export function pickMonitorForPoint(point: { x: number; y: number }, monitors: readonly FloatingMonitor[]): FloatingMonitor | null {
return monitors.find((monitor) => pointInsideWorkArea(point, monitor)) ?? monitors[0] ?? null;
}
export function floatingPositionStorageKey(pluginId: string, contributionId: string): string {
return `${FLOATING_POSITION_STORAGE_PREFIX}${pluginId}:${contributionId}`;
}
/** Parses a stored position; anything malformed is treated as absent. */
export function parseFloatingPosition(raw: string | null): FloatingPosition | null {
if (!raw) return null;
try {
const value = JSON.parse(raw) as Partial<FloatingPosition>;
if (typeof value?.x !== "number" || typeof value?.y !== "number" || !Number.isFinite(value.x) || !Number.isFinite(value.y)) return null;
const scaleFactor = typeof value.scaleFactor === "number" && Number.isFinite(value.scaleFactor) && value.scaleFactor > 0 ? value.scaleFactor : 1;
const edge = value.edge === "left" || value.edge === "right" || value.edge === "top" || value.edge === "bottom" ? value.edge : undefined;
return { x: value.x, y: value.y, scaleFactor, ...(edge ? { edge } : {}) };
} catch {
return null;
}
}
/**
* Resolves where a floating window should appear: the stored position when it
* still lands on a connected monitor (pulled inside the work area, since the
* taskbar or the monitor layout may have changed), otherwise the work-area
* default on `fallback` (the monitor the caller is on, so the widget opens where
* the user is looking). `size` is logical. Docked windows store their revealed
* (flush-to-edge, fully on-screen) point, so the same rules cover them; the
* window comes up as a readable capsule and tucks once the cursor has left it
* (resumeFloatingDock).
*/
export function resolveFloatingPlacement(stored: FloatingPosition | null, monitors: readonly FloatingMonitor[], size: { width: number; height: number }, fallback?: FloatingMonitor): { x: number; y: number; restored: boolean } {
if (stored) {
const monitor = pickMonitorForPoint(stored, monitors);
if (monitor && pointInsideWorkArea(stored, monitor)) {
// Clamp the stored point, not a rect: the window's real size is only known
// once its plugin has laid itself out, so assuming the requested size here
// would shift restored positions by the difference. Keeping the point a
// margin away from every edge is enough to keep the window reachable.
const scale = monitor.scaleFactor > 0 ? monitor.scaleFactor : 1;
const gap = Math.round(FLOATING_EDGE_MARGIN_PX * scale);
return {
x: Math.min(Math.max(stored.x, monitor.x + gap), monitor.x + monitor.width - gap),
y: Math.min(Math.max(stored.y, monitor.y + gap), monitor.y + monitor.height - gap),
restored: true,
};
}
}
const monitor = fallback ?? monitors[0];
if (!monitor) return { x: 0, y: 0, restored: false };
return { ...defaultFloatingPosition(monitor, size, FLOATING_EDGE_MARGIN_PX), restored: false };
}
export function persistFloatingPosition(pluginId: string, contributionId: string, position: FloatingPosition): void {
safeLocalStorageSet(floatingPositionStorageKey(pluginId, contributionId), JSON.stringify({ x: Math.round(position.x), y: Math.round(position.y), scaleFactor: position.scaleFactor, ...(position.edge ? { edge: position.edge } : {}) }));
}
/**
* Validates one `host.openFloating` payload. The plugin id always comes from
* the bridge (never from the payload), so a plugin can only open windows for
* its own contributions.
*/
export function parseFloatingWindowRequest(pluginId: string, input: Record<string, unknown>): OpenFloatingWindowRequest {
const contributionId = input.contributionId;
if (typeof contributionId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(contributionId)) throw new Error("host.openFloating requires a valid contributionId");
const readNumber = (value: unknown, label: string): number | undefined => {
if (value === undefined || value === null) return undefined;
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${label} must be a finite number`);
return value;
};
const readBoolean = (value: unknown, label: string): boolean | undefined => {
if (value === undefined || value === null) return undefined;
if (typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
return value;
};
const title = typeof input.title === "string" && input.title.trim() ? input.title.trim().slice(0, 200) : undefined;
const context = input.context;
if (context !== undefined && context !== null && (typeof context !== "object" || Array.isArray(context))) throw new Error("context must be an object");
const width = readNumber(input.width, "width");
const height = readNumber(input.height, "height");
const x = readNumber(input.x, "x");
const y = readNumber(input.y, "y");
const alwaysOnTop = readBoolean(input.alwaysOnTop, "alwaysOnTop");
const skipTaskbar = readBoolean(input.skipTaskbar, "skipTaskbar");
const resizable = readBoolean(input.resizable, "resizable");
return {
pluginId,
contributionId,
...(title === undefined ? {} : { title }),
...(width === undefined ? {} : { width }),
...(height === undefined ? {} : { height }),
...(x === undefined ? {} : { x }),
...(y === undefined ? {} : { y }),
...(alwaysOnTop === undefined ? {} : { alwaysOnTop }),
...(skipTaskbar === undefined ? {} : { skipTaskbar }),
...(resizable === undefined ? {} : { resizable }),
...(context === undefined || context === null ? {} : { context: context as Record<string, unknown> }),
};
}
interface DragSession {
/** Native cursor reading at drag start; cursorPosition() reports physical pixels. */
anchorX: number;
anchorY: number;
/** Window outer position at drag start, in physical pixels. */
windowX: number;
windowY: number;
startedAt: number;
lastCursorX: number;
lastCursorY: number;
lastMoveAt: number;
timer?: ReturnType<typeof setInterval>;
}
const dragSessions = new Map<string, DragSession>();
/** The calling window, when it is a floating plugin window; anything else is a misuse. */
async function ownFloatingWindow() {
if (!isTauriRuntime()) throw new Error("Floating plugin windows require the desktop app");
if (!isFloatingPluginWindow()) throw new Error("This call is only available inside a floating plugin window");
const { getCurrentWindow } = await import("@tauri-apps/api/window");
return getCurrentWindow();
}
async function listMonitors(): Promise<FloatingMonitor[]> {
const { availableMonitors } = await import("@tauri-apps/api/window");
const monitors = await availableMonitors().catch(() => []);
return monitors.map((monitor) => {
const area = monitor.workArea ?? { position: monitor.position, size: monitor.size };
return { x: area.position.x, y: area.position.y, width: area.size.width, height: area.size.height, scaleFactor: monitor.scaleFactor > 0 ? monitor.scaleFactor : 1 };
});
}
/** The monitor the calling window is on, so a new widget lands where the user is looking. */
async function currentMonitorArea(monitors: readonly FloatingMonitor[]): Promise<FloatingMonitor | null> {
const { currentMonitor } = await import("@tauri-apps/api/window");
const current = await currentMonitor().catch(() => null);
if (!current) return null;
const area = current.workArea ?? { position: current.position, size: current.size };
const match = monitors.find((monitor) => monitor.x === area.position.x && monitor.y === area.position.y && monitor.width === area.size.width && monitor.height === area.size.height);
return match ?? { x: area.position.x, y: area.position.y, width: area.size.width, height: area.size.height, scaleFactor: current.scaleFactor > 0 ? current.scaleFactor : 1 };
}
/** The floating window's document reports through this event that it mounted (i.e. its webview is alive). */
export const FLOATING_WEBVIEW_READY_EVENT = "dbx:plugin-floating-webview-ready";
/** The creator asks an already-open floating window to re-report liveness. */
export const FLOATING_WEBVIEW_HELLO_EVENT = "dbx:plugin-floating-hello";
/**
* How long the creator waits for the floating window's document to report that
* it mounted. Production bundles mount in well under a second; the dev server
* transforms this chunk's dependency graph (workbench host + stores) on first
* request after an edit, which can take several seconds — a timeout below that
* would retire perfectly healthy windows.
*/
const FLOATING_WEBVIEW_READY_TIMEOUT_MS = 6_000;
/**
* Creation attempts. WebView2 intermittently drops the initial navigation of a
* freshly created webview (the window sits at about:blank and never mounts), so
* a dead attempt is retired and retried instead of surfacing as a silent no-op.
*/
const FLOATING_OPEN_ATTEMPTS = 4;
/**
* True when the floating window's own document mounts within the timeout. A
* floating window is created hidden, so a webview that dies during boot leaves
* no visible trace at all — without this handshake a failed open would look like
* "minimize did nothing" while a dead window sits in the registry and shadows
* every later open.
*/
async function pingFloatingWebview(label: string, from: string): Promise<boolean> {
const { listen, emitTo } = await import("@tauri-apps/api/event");
return await new Promise<boolean>((resolve) => {
let settled = false;
let unlisten: (() => void) | undefined;
const timer = setTimeout(() => settle(false), FLOATING_WEBVIEW_READY_TIMEOUT_MS);
function settle(value: boolean) {
if (settled) return;
settled = true;
clearTimeout(timer);
unlisten?.();
resolve(value);
}
void listen<{ label?: unknown }>(FLOATING_WEBVIEW_READY_EVENT, (message) => {
if (message.payload && message.payload.label === label) settle(true);
}).then((fn) => {
unlisten = fn;
});
// A window that mounted before this listener existed answers the hello; a
// window still booting reports on its own once it mounts.
void emitTo(label, FLOATING_WEBVIEW_HELLO_EVENT, { from });
});
}
async function createFloatingChild(label: string, request: OpenFloatingWindowRequest, creatorLabel: string, placement: { x: number; y: number }, size: { width: number; height: number }): Promise<void> {
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
// Loaded lazily: the module pulls the i18n singleton in, which this window-only
// path has no other use for.
const { assertUpdateAllowsInteraction, beginUpdateSensitiveOperation } = await import("@/lib/app/updatePreparation");
assertUpdateAllowsInteraction();
let finishOperation: (() => void) | undefined;
try {
finishOperation = beginUpdateSensitiveOperation();
// Deliberately the same creation shape as the proven detached-tab windows:
// url/size/position/decorations/visibility only, with the widget chrome
// applied afterwards through setters. This is the shape verified to receive
// real OS mouse input (the drag acceptance presses and moves the widget with
// native input); richer creation-time option sets were not.
const child = new WebviewWindow(label, {
url: floatingWindowUrl(request.pluginId, request.contributionId, request.context, creatorLabel),
title: request.title ?? "DBX",
width: size.width,
height: size.height,
minWidth: FLOATING_MIN_WIDTH_PX,
minHeight: FLOATING_MIN_HEIGHT_PX,
x: placement.x,
y: placement.y,
resizable: request.resizable === true,
visible: false,
decorations: false,
center: false,
});
// A caller timeout does not prove native window creation has stopped, so the
// reservation is held until a native terminal event arrives (same reasoning
// as the detached-tab creator).
const finishNativeCreation = beginUpdateSensitiveOperation();
await new Promise<void>((resolve, reject) => {
let settled = false;
let timeout: ReturnType<typeof setTimeout> | undefined;
const settle = (finish: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
finishNativeCreation();
finish();
};
void child.once("tauri://created", () => settle(resolve));
void child.once("tauri://error", (event) => {
const message = typeof event?.payload === "string" ? event.payload : "Floating window creation failed";
console.error("[DBX][plugin-floating:create:error]", message);
settle(() => reject(new Error(message)));
});
timeout = setTimeout(() => settle(() => reject(new Error("Timed out while creating the floating plugin window"))), FLOATING_CREATE_TIMEOUT_MS);
});
// Widget chrome after creation: a floating widget owns no taskbar button and
// stays above other applications. Each is best-effort — failing degrades to a
// taskbar entry or a coverable window, never to a lost widget.
if (request.alwaysOnTop !== false) await child.setAlwaysOnTop(true).catch(() => undefined);
if (request.skipTaskbar !== false) await child.setSkipTaskbar(true).catch((error: unknown) => console.error("[DBX][plugin-floating:skip-taskbar]", error));
await child.show().catch((error: unknown) => console.error("[DBX][plugin-floating:show]", error));
// setPosition speaks the same (outer) coordinate space as the position we
// persist on drag end; the creation-time x/y do not, once a shadow frame is
// in play, and restoring through them drifts by the frame thickness.
const { PhysicalPosition } = await import("@tauri-apps/api/dpi");
await child.setPosition(new PhysicalPosition(Math.round(placement.x), Math.round(placement.y))).catch(() => undefined);
} finally {
finishOperation?.();
}
}
/**
* Opens (or focuses) the floating window for one plugin workbench contribution.
* The window is opaque and the plugin paints its own card. Creation is retried
* because WebView2 intermittently drops a fresh webview's initial navigation,
* and a window whose document never mounts would otherwise sit in the registry
* shadowing every later open.
*/
export async function openFloatingWindow(request: OpenFloatingWindowRequest): Promise<OpenFloatingWindowResult> {
if (!isTauriRuntime()) throw new Error("Floating plugin windows require the desktop app");
const label = floatingWindowLabel(request.pluginId, request.contributionId);
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
const { getCurrentWindow } = await import("@tauri-apps/api/window");
const creatorLabel = getCurrentWindow().label;
const size = clampFloatingSize(request.width ?? FLOATING_DEFAULT_WIDTH_PX, request.height ?? FLOATING_DEFAULT_HEIGHT_PX);
const monitors = await listMonitors();
const target = (await currentMonitorArea(monitors)) ?? monitors[0] ?? { x: 0, y: 0, width: 1920, height: 1080, scaleFactor: 1 };
const stored = parseFloatingPosition(safeLocalStorageGet(floatingPositionStorageKey(request.pluginId, request.contributionId)));
const placement = request.x !== undefined && request.y !== undefined ? { x: Math.round(request.x), y: Math.round(request.y) } : resolveFloatingPlacement(stored, monitors, size, target);
for (let attempt = 0; ; attempt += 1) {
const existing = await WebviewWindow.getByLabel(label);
if (!existing) await createFloatingChild(label, request, creatorLabel, placement, size);
const child = existing ?? (await WebviewWindow.getByLabel(label));
if (!child) throw new Error("Floating window creation failed");
if (await pingFloatingWebview(label, creatorLabel)) {
if (existing) {
await child.show();
await child.setFocus();
}
return { windowId: label, reused: Boolean(existing) };
}
// A window whose document never mounted is dead weight, and on the reuse
// path it would shadow every later open — retire it and retry; only after
// the last attempt does the failure reach the plugin, which then falls back
// to an in-shell surface.
console.error("[DBX][plugin-floating:webview-dead]", label, attempt);
await child.destroy().catch(() => undefined);
if (attempt >= FLOATING_OPEN_ATTEMPTS - 1) throw new Error("The floating plugin window did not come up");
}
}
/**
* Closes floating windows by host label. Labels are derived by the caller from
* its own manifest, so a plugin can only ever close its own windows.
*/
export async function closeFloatingWindows(labels: readonly string[]): Promise<void> {
if (!isTauriRuntime()) return;
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
for (const label of labels) {
// Never let a caller address the main shell or a detached tab through this path.
if (!isFloatingWindowLabel(label)) continue;
const target = await WebviewWindow.getByLabel(label);
if (!target) continue;
const session = dragSessions.get(label);
if (session?.timer) clearInterval(session.timer);
dragSessions.delete(label);
undockFloatingWindow(label);
await target.destroy().catch(async () => {
await target.close().catch((error: unknown) => console.error("[DBX][plugin-floating:close]", label, error));
});
}
}
/**
* Starts a window drag. The plugin only reports that its grip passed the drag
* threshold; from here the host polls the NATIVE cursor position and moves the
* window itself. Per-move messages from the plugin would work too, but a host
* poll keeps the widget glued to the cursor even if the webview stops seeing
* pointer events (a drag that outruns the window, a cancelled capture).
* `startDragging()` is not an option: the OS move loop only starts from a
* synchronous mousedown handler, and a bridge call is always async.
*
* Both readings are physical pixels — `cursorPosition()` resolves to a
* PhysicalPosition and so does `outerPosition()` — so the delta needs no DPI
* conversion. Dividing it by the scale factor makes the window trail the
* cursor by that factor.
*/
export async function beginFloatingWindowDrag(): Promise<void> {
const window = await ownFloatingWindow();
const label = window.label;
if (dragSessions.has(label)) return;
const { cursorPosition } = await import("@tauri-apps/api/window");
const { PhysicalPosition } = await import("@tauri-apps/api/dpi");
const [cursor, position] = await Promise.all([cursorPosition(), window.outerPosition()]);
const session: DragSession = {
anchorX: cursor.x,
anchorY: cursor.y,
windowX: position.x,
windowY: position.y,
startedAt: Date.now(),
lastCursorX: cursor.x,
lastCursorY: cursor.y,
lastMoveAt: Date.now(),
};
dragSessions.set(label, session);
session.timer = setInterval(() => {
const active = dragSessions.get(label);
if (!active) return;
void cursorPosition()
.then((cursor) => {
const current = dragSessions.get(label);
if (!current) return;
if (cursor.x !== current.lastCursorX || cursor.y !== current.lastCursorY) {
current.lastCursorX = cursor.x;
current.lastCursorY = cursor.y;
current.lastMoveAt = Date.now();
}
const dx = Math.round(cursor.x - current.anchorX);
const dy = Math.round(cursor.y - current.anchorY);
void window.setPosition(new PhysicalPosition(current.windowX + dx, current.windowY + dy)).catch(() => undefined);
// The plugin's pointerup is the normal end, but a webview that lost the
// pointer never sends one, so a quiet cursor is the release of last resort.
if (Date.now() - current.lastMoveAt > FLOATING_DRAG_IDLE_MS || Date.now() - current.startedAt > FLOATING_DRAG_TIMEOUT_MS) {
void endFloatingWindowDrag(true);
}
})
.catch(() => undefined);
}, 16);
}
/**
* Ends a drag: snaps the window onto the work-area edges it landed near, clamps
* it inside, and persists the position so the widget reopens where the user
* left it. Returns the final physical rect, or null when geometry is unreadable.
*/
export async function endFloatingWindowDrag(snap = true): Promise<FloatingRect | null> {
const window = await ownFloatingWindow();
const session = dragSessions.get(window.label);
if (session?.timer) clearInterval(session.timer);
dragSessions.delete(window.label);
const scaleFactor = (await window.scaleFactor().catch(() => 1)) || 1;
const rect = await currentWindowRect(window);
if (!rect) return null;
let final = rect;
if (snap) {
const monitors = await listMonitors();
const monitor = pickMonitorForPoint({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }, monitors);
if (monitor) {
const snapped = snapRectToWorkArea(rect, monitor, { margin: FLOATING_EDGE_MARGIN_PX, threshold: FLOATING_SNAP_THRESHOLD_PX });
final = snapped.rect;
const { PhysicalPosition } = await import("@tauri-apps/api/dpi");
await window.setPosition(new PhysicalPosition(Math.round(final.x), Math.round(final.y)));
if (snapped.edges.length) {
// Released against an edge: dock it. The cursor is still over the widget,
// so start revealed and let the dock poll tuck it once the user leaves.
await dockFloatingWindow(window, snapped.edges[0], monitor, final, false);
const tucked = dockSessions.get(window.label)?.rects.tucked;
if (tucked) final = { ...final, x: tucked.x, y: tucked.y };
} else {
undockFloatingWindow(window.label);
}
}
} else {
undockFloatingWindow(window.label);
}
const docked = dockSessions.get(window.label);
// Store the revealed (on-screen) home plus the edge: the tucked point hangs
// off-screen and would fail every monitor/clamp check on the next open.
persistOwnPosition(docked ? docked.rects.revealed : final, scaleFactor, docked?.edge);
return final;
}
type DockableWindow = Awaited<ReturnType<typeof ownFloatingWindow>>;
interface DockSession {
edge: FloatingDockEdge;
monitor: FloatingMonitor;
rects: FloatingDockRects;
size: { width: number; height: number };
hidden: boolean;
lastHoverAt: number;
timer?: ReturnType<typeof setInterval>;
}
const dockSessions = new Map<string, DockSession>();
function stopDockPoll(label: string): void {
const session = dockSessions.get(label);
if (session?.timer) clearInterval(session.timer);
}
/** Drops a window's dock state and its hover poll. */
export function undockFloatingWindow(label: string): void {
stopDockPoll(label);
dockSessions.delete(label);
}
async function setWindowPosition(window: DockableWindow, to: { x: number; y: number }): Promise<void> {
const { PhysicalPosition } = await import("@tauri-apps/api/dpi");
await window.setPosition(new PhysicalPosition(Math.round(to.x), Math.round(to.y))).catch(() => undefined);
}
/**
* Docks a floating window onto a work-area edge: it tucks off-screen until only
* a sliver stays visible, slides out flush to the edge while the cursor is over
* that sliver, and tucks again once the cursor has been away for a moment. The
* poll lives in the floating window's own context (like the drag poll), so it
* survives a main-window reload.
*/
export async function dockFloatingWindow(window: DockableWindow, edge: FloatingDockEdge, monitor: FloatingMonitor, rect: FloatingRect, hidden: boolean): Promise<void> {
stopDockPoll(window.label);
const rects = dockRectsForEdge(rect, monitor, edge, FLOATING_DOCK_SLIVER_PX);
const session: DockSession = { edge, monitor, rects, size: { width: rect.width, height: rect.height }, hidden, lastHoverAt: Date.now() };
dockSessions.set(window.label, session);
await setWindowPosition(window, hidden ? rects.tucked : rects.revealed);
session.timer = setInterval(() => {
const live = dockSessions.get(window.label);
if (!live) return;
// A drag owns the window; re-arm the idle clock so it never tucks mid-drag.
if (dragSessions.has(window.label)) {
live.lastHoverAt = Date.now();
return;
}
void import("@tauri-apps/api/window")
.then(({ cursorPosition }) => cursorPosition())
.then((cursor) => {
const current = dockSessions.get(window.label);
if (!current) return;
const revealedRect: FloatingRect = { x: current.rects.revealed.x, y: current.rects.revealed.y, width: current.size.width, height: current.size.height };
const overSliver = pointInRect(cursor, current.rects.sliver, FLOATING_DOCK_HOVER_PAD_PX);
const overWidget = pointInRect(cursor, revealedRect, FLOATING_DOCK_HOVER_PAD_PX);
if (current.hidden) {
if (overSliver) {
current.hidden = false;
current.lastHoverAt = Date.now();
void setWindowPosition(window, current.rects.revealed);
}
} else if (overWidget || overSliver) {
current.lastHoverAt = Date.now();
} else if (Date.now() - current.lastHoverAt > FLOATING_DOCK_IDLE_MS) {
current.hidden = true;
void setWindowPosition(window, current.rects.tucked);
}
})
.catch(() => undefined);
}, FLOATING_DOCK_POLL_MS);
}
/** Re-derives a docked window's tuck/reveal geometry after its size changed. */
async function refreshFloatingDock(window: DockableWindow): Promise<void> {
const session = dockSessions.get(window.label);
if (!session) return;
const rect = await currentWindowRect(window);
if (!rect) return;
session.size = { width: rect.width, height: rect.height };
session.rects = dockRectsForEdge(rect, session.monitor, session.edge, FLOATING_DOCK_SLIVER_PX);
await setWindowPosition(window, session.hidden ? session.rects.tucked : session.rects.revealed);
}
/**
* Re-arms the dock for a freshly opened floating window whose stored position
* carries an edge — the user had left it parked on that edge. It opens as a full,
* readable capsule and only tucks once the cursor has been away for a moment: a
* widget the user just summoned should not greet them as a sliver. A window with
* no docked home (a fresh minimize) gets no dock at all and simply stays a capsule,
* even though the default placement sits against the edge.
*/
export async function resumeFloatingDock(): Promise<void> {
if (!isTauriRuntime() || !isFloatingPluginWindow()) return;
const context = resolveWindowContext();
if (context.kind !== "plugin-window") return;
const stored = parseFloatingPosition(safeLocalStorageGet(floatingPositionStorageKey(context.pluginId, context.contributionId)));
if (!stored?.edge) return;
const window = await ownFloatingWindow();
if (dockSessions.has(window.label)) return;
const [rect, monitors] = await Promise.all([currentWindowRect(window), listMonitors()]);
const monitor = pickMonitorForPoint(stored, monitors) ?? monitors[0];
if (!rect || !monitor) return;
await dockFloatingWindow(window, stored.edge, monitor, rect, false);
}
/** Resizes the calling floating window (logical pixels). */
export async function setFloatingWindowSize(width: number, height: number): Promise<void> {
const window = await ownFloatingWindow();
const size = clampFloatingSize(width, height);
const { LogicalSize } = await import("@tauri-apps/api/dpi");
await window.setSize(new LogicalSize(size.width, size.height));
// A resized window hangs over the edge it was docked to with the old geometry;
// re-derive tuck/reveal before persisting anything.
await refreshFloatingDock(window);
// Keep the stored position honest so the next open lands where this one sits.
const scaleFactor = (await window.scaleFactor().catch(() => 1)) || 1;
const docked = dockSessions.get(window.label);
const position = docked ? docked.rects.revealed : await window.outerPosition().catch(() => null);
if (position) persistOwnPosition(position, scaleFactor, docked?.edge);
}
const FLOATING_REAPER_INTERVAL_MS = 8_000;
const FLOATING_REAPER_REPLY_MS = 4_000;
const FLOATING_REAPER_MISSES = 2;
/** A window gets this long to finish booting before silence counts against it. */
const FLOATING_REAPER_GRACE_MS = 15_000;
const reaperLastSeen = new Map<string, number>();
const reaperMisses = new Map<string, number>();
const reaperFirstSeen = new Map<string, number>();
/**
* Reaps floating windows whose webview stopped answering. A renderer that dies
* mid-session leaves an opaque rectangle on the desktop with no capsule and no
* buttons — nothing inside it can dismiss it, and a frameless window gives the
* user no close affordance — so the main window has to. Floating shells answer
* FLOATING_WEBVIEW_HELLO with FLOATING_WEBVIEW_READY (the same handshake that
* proves a freshly created window mounted), so two silent cycles mean dead.
*/
export function startFloatingWindowReaper(): () => void {
if (!isTauriRuntime()) return () => undefined;
let stopped = false;
let unlisten: (() => void) | undefined;
void import("@tauri-apps/api/event")
.then(({ listen }) =>
listen<{ label?: unknown }>(FLOATING_WEBVIEW_READY_EVENT, (message) => {
const label = message.payload && typeof message.payload.label === "string" ? message.payload.label : "";
if (label) {
reaperLastSeen.set(label, Date.now());
reaperMisses.delete(label);
}
}),
)
.then((stop) => {
if (stopped) stop();
else unlisten = stop;
});
const timer = setInterval(() => {
void (async () => {
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
const { emitTo } = await import("@tauri-apps/api/event");
const labels = (await WebviewWindow.getAll()).map((window) => window.label).filter(isFloatingWindowLabel);
// A label that disappeared (closed normally) must not carry its miss count
// into the next window that reuses the same deterministic label.
for (const label of [...reaperMisses.keys(), ...reaperFirstSeen.keys()]) {
if (!labels.includes(label)) {
reaperMisses.delete(label);
reaperFirstSeen.delete(label);
}
}
if (!labels.length) return;
const cycle = Date.now();
for (const label of labels) if (!reaperFirstSeen.has(label)) reaperFirstSeen.set(label, cycle);
for (const label of labels) void emitTo(label, FLOATING_WEBVIEW_HELLO_EVENT, { from: "main" }).catch(() => undefined);
setTimeout(() => {
if (stopped) return;
for (const label of labels) {
if ((reaperLastSeen.get(label) ?? 0) >= cycle) {
reaperMisses.delete(label);
continue;
}
// Fresh windows are still booting (cold transforms can take a while);
// silence only counts once the grace period is over.
if (cycle - (reaperFirstSeen.get(label) ?? cycle) < FLOATING_REAPER_GRACE_MS) continue;
const misses = (reaperMisses.get(label) ?? 0) + 1;
reaperMisses.set(label, misses);
if (misses >= FLOATING_REAPER_MISSES) {
console.error("[DBX][plugin-floating:reap]", label, misses);
reaperMisses.delete(label);
reaperFirstSeen.delete(label);
void closeFloatingWindows([label]);
}
}
}, FLOATING_REAPER_REPLY_MS);
})();
}, FLOATING_REAPER_INTERVAL_MS);
return () => {
stopped = true;
clearInterval(timer);
unlisten?.();
};
}
/** Reveals the window once its plugin content has painted. */
export async function revealFloatingWindow(): Promise<void> {
if (!isTauriRuntime() || !isFloatingPluginWindow()) return;
const { getCurrentWindow } = await import("@tauri-apps/api/window");
const window = getCurrentWindow();
await window.show().catch((error: unknown) => console.error("[DBX][plugin-floating:show]", error));
await window.setFocus().catch(() => undefined);
}
/**
* Shell-bound navigation from a floating window: it has no tab strip, dock, or
* panels of its own, so opening a workbench or a filesystem tab is forwarded to
* the main window (which raises itself and creates the tab).
*/
export const FLOATING_OPEN_WORKBENCH_EVENT = "dbx:plugin-floating-open-workbench";
export const FLOATING_OPEN_FILESYSTEM_EVENT = "dbx:plugin-floating-open-filesystem";
export interface FloatingOpenWorkbenchPayload {
pluginId: string;
contributionId: string;
title?: string;
context?: Record<string, unknown>;
forceNew?: boolean;
}
export interface FloatingOpenFilesystemPayload {
pluginId: string;
providerId: string;
title?: string;
rootUri?: string;
context?: Record<string, unknown>;
}
export async function forwardFloatingToMainWindow(event: string, payload: unknown): Promise<void> {
if (!isTauriRuntime()) throw new Error("Floating plugin windows require the desktop app");
const { emitTo } = await import("@tauri-apps/api/event");
await emitTo("main", event, payload);
}
interface WindowLike {
label: string;
outerPosition(): Promise<{ x: number; y: number }>;
outerSize(): Promise<{ width: number; height: number }>;
}
async function currentWindowRect(window: WindowLike): Promise<FloatingRect | null> {
try {
const [position, size] = await Promise.all([window.outerPosition(), window.outerSize()]);
if (!position || !size) return null;
return { x: position.x, y: position.y, width: size.width, height: size.height };
} catch (error) {
console.error("[DBX][plugin-floating:geometry]", error);
return null;
}
}
/** Stores a position under this window's own plugin identity (parsed from its URL). */
function persistOwnPosition(position: { x: number; y: number }, scaleFactor: number, edge?: FloatingDockEdge): void {
const context = resolveWindowContext();
if (context.kind !== "plugin-window") return;
persistFloatingPosition(context.pluginId, context.contributionId, { x: position.x, y: position.y, scaleFactor, ...(edge ? { edge } : {}) });
}
@@ -8,6 +8,8 @@ import { isValidPluginAiRecommendationTemplate, resolvePluginAiRecommendationUpd
import type { PluginAiRecommendation } from "@/types/pluginAiRecommendations"; import type { PluginAiRecommendation } from "@/types/pluginAiRecommendations";
import { MAX_PLUGIN_SCHEMA_METADATA_NAME_CHARS, PLUGIN_SCHEMA_METADATA_CAPABILITY, PLUGIN_SCHEMA_METADATA_PERMISSION, type PluginTableContext, type PluginTableMetadata } from "@/types/pluginSchemaMetadata"; import { MAX_PLUGIN_SCHEMA_METADATA_NAME_CHARS, PLUGIN_SCHEMA_METADATA_CAPABILITY, PLUGIN_SCHEMA_METADATA_PERMISSION, type PluginTableContext, type PluginTableMetadata } from "@/types/pluginSchemaMetadata";
import { MAX_PLUGIN_DATA_MAX_ROWS, MAX_PLUGIN_DATA_NAME_CHARS, MAX_PLUGIN_DATA_SQL_CHARS, MAX_PLUGIN_DATA_TIMEOUT_MS, PLUGIN_DATA_ACCESS_NOT_GRANTED, PLUGIN_DATA_CAPABILITY, PLUGIN_DATA_READ_PERMISSION, type PluginDataQueryRequest, type PluginDataQueryResult } from "@/types/pluginData"; import { MAX_PLUGIN_DATA_MAX_ROWS, MAX_PLUGIN_DATA_NAME_CHARS, MAX_PLUGIN_DATA_SQL_CHARS, MAX_PLUGIN_DATA_TIMEOUT_MS, PLUGIN_DATA_ACCESS_NOT_GRANTED, PLUGIN_DATA_CAPABILITY, PLUGIN_DATA_READ_PERMISSION, type PluginDataQueryRequest, type PluginDataQueryResult } from "@/types/pluginData";
import { floatingWindowLabel } from "@/lib/app/windowContext";
import { parseFloatingWindowRequest, type FloatingRect, type OpenFloatingWindowRequest, type OpenFloatingWindowResult } from "@/lib/plugins/pluginFloatingWindow";
const PLUGIN_MESSAGE_SOURCE = "dbx-plugin"; const PLUGIN_MESSAGE_SOURCE = "dbx-plugin";
const HOST_MESSAGE_SOURCE = "dbx-host"; const HOST_MESSAGE_SOURCE = "dbx-host";
@@ -225,6 +227,27 @@ export interface PluginHostBridgeApi {
/** Persists the grant the user just allowed. */ /** Persists the grant the user just allowed. */
grantDataAccess?(pluginId: string, connectionId: string): Promise<void>; grantDataAccess?(pluginId: string, connectionId: string): Promise<void>;
closeTab?(): Promise<void> | void; closeTab?(): Promise<void> | void;
/**
* Floating plugin windows (the §8.3 "window" surface): a frameless,
* always-on-top desktop widget outside the main shell. Desktop hosts only — a
* host without it omits these so `capabilities.floating` stays false and the
* plugin can fall back to an in-shell surface (tab or dock).
*
* Geometry is host-owned end to end: the plugin asks to open/close its window
* and reports drag intent, while positions, work-area snapping, and DPI
* conversion stay here. A drag is driven by the native cursor position rather
* than plugin-supplied coordinates, which would be relative to a viewport that
* is itself moving.
*/
openFloatingWindow?(request: OpenFloatingWindowRequest): Promise<OpenFloatingWindowResult>;
/** Closes floating windows by host label; callers derive labels from their own manifest, never from plugin input. */
closeFloatingWindows?(labels: string[]): Promise<void>;
/** Hands the calling floating window's movement to the OS drag loop. */
beginFloatingDrag?(): Promise<void>;
/** Ends a drag, snapping the window onto the work-area edges it landed near. Resolves the final physical rect. */
endFloatingDrag?(snap: boolean): Promise<FloatingRect | null>;
/** Resizes the calling floating window (logical pixels). */
setFloatingSize?(width: number, height: number): Promise<void>;
/** Persist plugin bytes through the host's native save dialog. Resolves null when the user cancels. */ /** Persist plugin bytes through the host's native save dialog. Resolves null when the user cancels. */
saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): Promise<PluginSaveFileResult | null>; saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): Promise<PluginSaveFileResult | null>;
downloadFile?(pluginId: string, request: PluginDownloadRequest, onProgress: (progress: unknown) => void): Promise<PluginSaveFileResult | null>; downloadFile?(pluginId: string, request: PluginDownloadRequest, onProgress: (progress: unknown) => void): Promise<PluginSaveFileResult | null>;
@@ -484,6 +507,9 @@ export class PluginHostBridge {
clipboardRead: !!this.api.clipboardRead, clipboardRead: !!this.api.clipboardRead,
clipboardImageRead: !!this.api.clipboardReadImage, clipboardImageRead: !!this.api.clipboardReadImage,
mediaUrl: !!this.api.openMedia && !!this.api.closeMedia, mediaUrl: !!this.api.openMedia && !!this.api.closeMedia,
// Floating desktop widget windows: advertised only when the host can both
// open a window and drive its geometry, so a plugin sees one honest flag.
floating: !!this.api.openFloatingWindow && !!this.api.beginFloatingDrag && !!this.api.endFloatingDrag,
// The namespace exists on both hosts, but what it can DO differs: // The namespace exists on both hosts, but what it can DO differs:
// portable plugins gate on these flags instead of probing calls. // portable plugins gate on these flags instead of probing calls.
fileTransfer: { fileTransfer: {
@@ -933,9 +959,54 @@ export class PluginHostBridge {
await this.api.storageDelete(this.plugin.manifest.id, requireStorageKey(input.key)); await this.api.storageDelete(this.plugin.manifest.id, requireStorageKey(input.key));
return null; return null;
} }
if (method === "host.openFloating") {
// A floating window is a workbench surface in its own right, so it shares
// the workbench permission gate instead of introducing a new one.
this.requirePermission("host.workbench");
if (!this.api.openFloatingWindow) throw new Error("Floating plugin windows require the desktop host");
const request = parseFloatingWindowRequest(this.plugin.manifest.id, requireRecord(params, "host.openFloating params"));
if (!this.ownWorkbenchContributionIds().has(request.contributionId)) throw new Error("Unknown workbench contribution");
return this.api.openFloatingWindow(request);
}
if (method === "host.closeFloating") {
if (!this.api.closeFloatingWindows) throw new Error("Floating plugin windows require the desktop host");
const input = isRecord(params) ? params : {};
const contributionId = optionalTrimmedString(input.contributionId);
const own = this.ownWorkbenchContributionIds();
if (contributionId && !own.has(contributionId)) throw new Error("Unknown workbench contribution");
// Without an explicit contribution every floating window of this plugin
// closes; labels are host-derived, so a plugin can never reach another
// plugin's window (or the main shell) through this path.
const contributionIds = contributionId ? [contributionId] : [...own];
await this.api.closeFloatingWindows(contributionIds.map((id) => floatingWindowLabel(this.plugin.manifest.id, id)));
return null;
}
if (method === "host.beginFloatingDrag") {
if (!this.api.beginFloatingDrag) throw new Error("Floating plugin windows require the desktop host");
await this.api.beginFloatingDrag();
return null;
}
if (method === "host.endFloatingDrag") {
if (!this.api.endFloatingDrag) throw new Error("Floating plugin windows require the desktop host");
const input = isRecord(params) ? params : {};
return (await this.api.endFloatingDrag(input.snap !== false)) ?? null;
}
if (method === "host.setFloatingSize") {
if (!this.api.setFloatingSize) throw new Error("Floating plugin windows require the desktop host");
const input = requireRecord(params, "host.setFloatingSize params");
const width = requireFloatingDimension(input.width, "width");
const height = requireFloatingDimension(input.height, "height");
await this.api.setFloatingSize(width, height);
return null;
}
throw new Error(`Unsupported plugin host method '${method}'`); throw new Error(`Unsupported plugin host method '${method}'`);
} }
/** The plugin's own declared workbench contributions — the only ones it may host in a floating window. */
private ownWorkbenchContributionIds(): Set<string> {
return new Set((this.plugin.manifest.contributions || []).filter((candidate) => candidate.type === "workbench").map((candidate) => candidate.id));
}
private async requireClipboardRead(): Promise<number> { private async requireClipboardRead(): Promise<number> {
const now = Date.now(); const now = Date.now();
if (!clipboardReadGateAllows(this.clipboardReadGate, now)) { if (!clipboardReadGateAllows(this.clipboardReadGate, now)) {
@@ -1311,6 +1382,29 @@ export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType })); return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType }));
}, },
openWorkbench: (contributionId, childContext, options) => request('host.openWorkbench', { contributionId, context: childContext, forceNew: !!(options && options.forceNew), target: options && options.target === "tab" ? "tab" : undefined }), openWorkbench: (contributionId, childContext, options) => request('host.openWorkbench', { contributionId, context: childContext, forceNew: !!(options && options.forceNew), target: options && options.target === "tab" ? "tab" : undefined }),
// Closes whatever surface hosts this plugin UI — a workbench tab, a dock
// entry, or this plugin's floating window. Same path as the Ctrl+W
// shortcut, so a plugin can offer its own close/minimize affordance.
closeWorkbench: () => parent.postMessage({ source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'shortcut', shortcut: 'closeTab' }, '*'),
// Floating desktop widget windows (the "window" surface): a frameless,
// always-on-top window that stays visible over other applications. Gate on
// capabilities.floating — a web host, or a desktop host without window
// support, omits it and the plugin should fall back to tab or dock.
//
// Dragging is split by design: the plugin decides WHEN a drag starts
// (thresholds, which element is a grip) and the host owns the movement —
// beginDrag hands the window to the OS move loop, and the host snaps it
// onto the work-area edges and remembers the spot once the loop goes
// quiet. Per-move coordinates are deliberately not part of the protocol:
// once the window follows the pointer, the webview's pointer capture is
// cancelled and the move stream dies mid-drag.
floating: Object.freeze({
open: (options) => request('host.openFloating', options || {}),
close: (contributionId) => request('host.closeFloating', { contributionId }),
beginDrag: () => request('host.beginFloatingDrag'),
endDrag: (options) => request('host.endFloatingDrag', options || {}),
setSize: (width, height) => request('host.setFloatingSize', { width, height }),
}),
// §4/§5 command execution from a webview — the same registry path a menu // §4/§5 command execution from a webview — the same registry path a menu
// placement takes (enablement, §4.1 reuse, host-authored context), // placement takes (enablement, §4.1 reuse, host-authored context),
// scoped to the plugin's own declared commands. The optional context // scoped to the plugin's own declared commands. The optional context
@@ -1653,6 +1747,12 @@ function requireStorageKey(value: unknown): string {
return value; return value;
} }
/** A floating window dimension in logical pixels; the host clamps it to its own bounds. */
function requireFloatingDimension(value: unknown, label: string): number {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw new Error(`${label} must be a positive number`);
return value;
}
function base64ToBytes(value: string): ArrayBuffer { function base64ToBytes(value: string): ArrayBuffer {
const binary = atob(value); const binary = atob(value);
const bytes = new Uint8Array(binary.length); const bytes = new Uint8Array(binary.length);
@@ -97,6 +97,17 @@ async function inlineLocalUiAssets(html: string, pluginId: string): Promise<Plug
resource.replaceWith(script); resource.replaceWith(script);
} else { } else {
const style = document.createElement("style"); const style = document.createElement("style");
// Carry the stylesheet's own attributes over, exactly like the script
// branch does: they are how a plugin addresses the sheet later (a theme or
// skin switch selects sheets by a data-* marker and toggles `disabled`),
// so dropping them here silently breaks every runtime stylesheet lookup in
// plugin form. Note that `disabled` does not reflect from the content
// attribute on a <style> element the way it does on a <link>, and it cannot
// survive serialization as an IDL property either — a plugin that ships a
// disabled stylesheet has to re-apply `sheet.disabled` itself.
for (const attribute of [...resource.attributes]) {
if (attribute.name !== "href" && attribute.name !== "rel") style.setAttribute(attribute.name, attribute.value);
}
style.textContent = content; style.textContent = content;
resource.replaceWith(style); resource.replaceWith(style);
} }
+18
View File
@@ -6,6 +6,7 @@ import { retryStartupAfterPreloadFailure } from "@/lib/startup/startupPreloadRec
import { markStartupPhase } from "@/lib/startup/startupTiming"; import { markStartupPhase } from "@/lib/startup/startupTiming";
import { applyLegacyWebViewClass, isBlockingCompatFailure } from "@/lib/ui/legacyWebView"; import { applyLegacyWebViewClass, isBlockingCompatFailure } from "@/lib/ui/legacyWebView";
import { hydrateAppAppearance } from "@/lib/app/appAppearance"; import { hydrateAppAppearance } from "@/lib/app/appAppearance";
import { isFloatingPluginWindow } from "@/lib/app/windowContext";
function startupErrorMessage(error: unknown): string { function startupErrorMessage(error: unknown): string {
if (error instanceof Error) { if (error instanceof Error) {
@@ -92,6 +93,23 @@ async function bootstrap() {
// durable appearance record before importing i18n and the theme composable; // durable appearance record before importing i18n and the theme composable;
// those modules synchronously read the compatibility keys during evaluation. // those modules synchronously read the compatibility keys during evaluation.
await hydrateAppAppearance(); await hydrateAppAppearance();
// A floating plugin window is a widget, not the workbench: it mounts its own
// root (one plugin workbench on a transparent page) and skips StartupGate/App,
// so shell singletons — authentication, tab restore, update prompts — stay in
// the main window instead of booting a second time per widget.
if (isFloatingPluginWindow()) {
const [{ default: i18n, loadSavedLocale }, { default: PluginFloatingWindow }] = await Promise.all([import("./i18n"), import("@/components/plugins/PluginFloatingWindow.vue")]);
const localeReady = loadSavedLocale();
const floatingApp = createApp(PluginFloatingWindow, { localeReady });
floatingApp.use(createPinia());
floatingApp.use(i18n);
floatingApp.mount("#root");
// The inline startup guard in index.html swallows Escape until this fires; a
// widget has no startup wizard, so release it as soon as the root is mounted.
window.dispatchEvent(new Event("dbx:startup-ready"));
void localeReady.catch(() => {});
return;
}
const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./StartupGate.vue")]); const [{ default: i18n, loadSavedLocale }, { default: App }] = await Promise.all([import("./i18n"), import("./StartupGate.vue")]);
console.log("[STARTUP] frontend modules loaded"); console.log("[STARTUP] frontend modules loaded");
const localeReady = loadSavedLocale(); const localeReady = loadSavedLocale();
+66 -1
View File
@@ -321,6 +321,8 @@ Workbench 上下文跨越 DBX 与插件边界时是 JSON 数据快照。宿主
连接 Provider 使用 `binding: "config"` 的字段会保存到 `external_config`;使用 `binding: "secret"` 的字段会保存到 Secret Store。插件连接的 `external_config` 会在新建、编辑、保存和重新连接流程中保留。 连接 Provider 使用 `binding: "config"` 的字段会保存到 `external_config`;使用 `binding: "secret"` 的字段会保存到 Secret Store。插件连接的 `external_config` 会在新建、编辑、保存和重新连接流程中保留。
宿主还会为每个 workbench 上下文写入三个保留字段:`workbenchId`(宿主生成的稳定实例 id)、`restored` 和 `surface`。`surface` 表示当前 UI 跑在哪种容器里——`"tab"`(主多标签工作台)、`"dock"`(底部面板)或 `"window"`(桌面浮动小组件窗口,见[浮动窗口](#浮动窗口))。同一个插件的同一个 contribution 可以同时开在多个 surface 上,各自拥有独立的上下文和生命周期;遇到未知取值应退化成 `"tab"` 的行为。
## 前端 Host API ## 前端 Host API
UI 在隔离的 iframe 中运行,DBX 通过 `window.dbxPlugin` 提供桥接对象。不要导入 DBX 的 Vue/Tauri 模块,也不要假设浏览器页面能直接访问 Node.js、文件系统或网络。 UI 在隔离的 iframe 中运行,DBX 通过 `window.dbxPlugin` 提供桥接对象。不要导入 DBX 的 Vue/Tauri 模块,也不要假设浏览器页面能直接访问 Node.js、文件系统或网络。
@@ -350,13 +352,14 @@ const assetUrl = await window.dbxPlugin.readAssetUrl("assets/empty-state.svg");
| `sendBinary(channel, data)` / `onBinary(fn)` | 发送或接收二进制数据;需要 `stdio-framed` 和 `host.binary`。 | | `sendBinary(channel, data)` / `onBinary(fn)` | 发送或接收二进制数据;需要 `stdio-framed` 和 `host.binary`。 |
| `readAsset(path)` / `readAssetUrl(path)` | 读取包内资源;路径不能越出插件资源根目录。 | | `readAsset(path)` / `readAssetUrl(path)` | 读取包内资源;路径不能越出插件资源根目录。 |
| `openWorkbench(id, context)` | 打开本插件的另一个工作台;需要 `host.workbench`。 | | `openWorkbench(id, context)` | 打开本插件的另一个工作台;需要 `host.workbench`。 |
| `closeWorkbench()` | 关闭承载当前 UI 的表面——工作台标签、dock 面板条目,或本插件的浮动窗口。与 `Ctrl/Cmd+W` 快捷键走同一条路径,因此插件可以提供自己的关闭或最小化按钮。 |
| `executeCommand(commandId, context?)` | 执行本插件自己声明的命令,与菜单执行完全同径——重新检查 `enablement`、按单例复用,并遵循声明的 `presentation`(panel 停靠底部面板,tab 打开工作台标签页)。`context` 合并到命令上下文之上,并解析 `instance_key` 的 `{{path}}` 占位符(如 `instance_key: "logs:{{connectionId}}"` 即每个连接一个面板实例)。预期结果通过 `{ error }` 返回;需要 `host.workbench`。 | | `executeCommand(commandId, context?)` | 执行本插件自己声明的命令,与菜单执行完全同径——重新检查 `enablement`、按单例复用,并遵循声明的 `presentation`(panel 停靠底部面板,tab 打开工作台标签页)。`context` 合并到命令上下文之上,并解析 `instance_key` 的 `{{path}}` 占位符(如 `instance_key: "logs:{{connectionId}}"` 即每个连接一个面板实例)。预期结果通过 `{ error }` 返回;需要 `host.workbench`。 |
| `openFilesystem(id, context)` | 打开本插件的文件系统入口;需要 `host.filesystem`。 | | `openFilesystem(id, context)` | 打开本插件的文件系统入口;需要 `host.filesystem`。 |
| `getPlanCapabilities(connectionId)` | 读取宿主与该连接能提供什么计划能力;需要 `host.plans:read`。 | | `getPlanCapabilities(connectionId)` | 读取宿主与该连接能提供什么计划能力;需要 `host.plans:read`。 |
| `explainPlan({ connectionId, database?, schema?, sql, mode, timeoutMs? })` | 返回 `sql` 的估算执行计划;需要 `host.plans:read`。 | | `explainPlan({ connectionId, database?, schema?, sql, mode, timeoutMs? })` | 返回 `sql` 的估算执行计划;需要 `host.plans:read`。 |
| `getTableMetadata({ connectionId, database?, schema?, table })` | 读取已打开连接的窄化 table schema metadata;需要 `host.schema:read`。 | | `getTableMetadata({ connectionId, database?, schema?, table })` | 读取已打开连接的窄化 table schema metadata;需要 `host.schema:read`。 |
| `queryData({ connectionId, database?, schema?, sql, maxRows?, timeoutMs? })` | 在用户授权给插件的连接上执行一条只读 SQL;需要 `host.data:read`。 | | `queryData({ connectionId, database?, schema?, sql, maxRows?, timeoutMs? })` | 在用户授权给插件的连接上执行一条只读 SQL;需要 `host.data:read`。 |
| `capabilities` | 来自 init 消息的 `{ downloadFile, planApi, schemaMetadataApi, dataApi, storage, ai, aiRecommendations, clipboardWrite, clipboardRead }`。字段缺失或为 `false` 表示当前宿主不支持该组 Host API,应据此关闭功能而不是用真实请求试探。 | | `capabilities` | 来自 init 消息的 `{ downloadFile, planApi, schemaMetadataApi, dataApi, storage, ai, aiRecommendations, clipboardWrite, clipboardRead, floating }`。字段缺失或为 `false` 表示当前宿主不支持该组 Host API,应据此关闭功能而不是用真实请求试探。 |
| `ai.openConversation({ title, prompt, context, send?, mode? })` | 在内置 AI 面板新建插件对话;`send` 默认 `false`,`mode` 默认 `ask`。`mode: "agent"` 会在 context 包含已打开插件连接时使用实时插件工具;需要 `host.ai`,并以 `capabilities.ai` 广播。 | | `ai.openConversation({ title, prompt, context, send?, mode? })` | 在内置 AI 面板新建插件对话;`send` 默认 `false`,`mode` 默认 `ask`。`mode: "agent"` 会在 context 包含已打开插件连接时使用实时插件工具;需要 `host.ai`,并以 `capabilities.ai` 广播。 |
| `ai.setRecommendations({ context, items })` | 覆盖当前工作台的默认推荐问题并立即刷新全局 AI 面板;每次最多 5 条,支持 `{{path.to.value}}` 占位符;需要 `host.ai` 和 `capabilities.aiRecommendations`。 | | `ai.setRecommendations({ context, items })` | 覆盖当前工作台的默认推荐问题并立即刷新全局 AI 面板;每次最多 5 条,支持 `{{path.to.value}}` 占位符;需要 `host.ai` 和 `capabilities.aiRecommendations`。 |
| `ai.clearRecommendations()` | 清空当前工作台的推荐问题;需要 `host.ai` 和 `capabilities.aiRecommendations`。 | | `ai.clearRecommendations()` | 清空当前工作台的推荐问题;需要 `host.ai` 和 `capabilities.aiRecommendations`。 |
@@ -364,6 +367,7 @@ const assetUrl = await window.dbxPlugin.readAssetUrl("assets/empty-state.svg");
| `storage` | 本插件独享的持久化键值状态;需要 `host.storage`;见下文。 | | `storage` | 本插件独享的持久化键值状态;需要 `host.storage`;见下文。 |
| `fileTransfer` | 本地文件流式传输、下载与(桌面端)系统拖放;见下文。 | | `fileTransfer` | 本地文件流式传输、下载与(桌面端)系统拖放;见下文。 |
| `clipboard` | 沙箱内的系统剪贴板访问;见下文。 | | `clipboard` | 沙箱内的系统剪贴板访问;见下文。 |
| `floating` | 打开并控制桌面浮动小组件窗口(仅桌面宿主);见[浮动窗口](#浮动窗口)。 |
调用失败会以 Promise rejection 返回,处理时应展示可理解的错误并允许重试。通过 `request` 调用的宿主方法、参数和返回值以当前 Host API 版本为准,不要调用未在协议中声明的 DBX 内部函数。 调用失败会以 Promise rejection 返回,处理时应展示可理解的错误并允许重试。通过 `request` 调用的宿主方法、参数和返回值以当前 Host API 版本为准,不要调用未在协议中声明的 DBX 内部函数。
@@ -680,6 +684,59 @@ await dbxPlugin.ai.openConversation({
`title` 最多 200 字符,`prompt` 最多 32000 字符,`context` 必须是纯 JSON 对象,上限 2 MiB。Agent 只能使用宿主为该插件连接公开的工具;插件不会收到模型回复或模型配置,也不能借此获得数据库执行能力。旧插件不声明推荐问题时仍可正常使用原有 AI API;旧宿主缺少新增 capability 字段时,插件应关闭对应入口并继续提供其他功能。 `title` 最多 200 字符,`prompt` 最多 32000 字符,`context` 必须是纯 JSON 对象,上限 2 MiB。Agent 只能使用宿主为该插件连接公开的工具;插件不会收到模型回复或模型配置,也不能借此获得数据库执行能力。旧插件不声明推荐问题时仍可正常使用原有 AI API;旧宿主缺少新增 capability 字段时,插件应关闭对应入口并继续提供其他功能。
### 浮动窗口
浮动窗口把插件的某个 workbench 放进一个独立的无边框、置顶桌面窗口,而不是塞在 DBX 外壳里——这正是小型常驻小组件需要的表面(播放器胶囊、会话状态徽章、快捷选择器)。它会盖在其他应用之上,可以被拖到桌面任意位置。在屏幕中间松手就停在落点;落到或越过工作区边缘(不管怼得多用力)都会齐着那条边吸附并停靠。停靠不会在落下的那一刻就把小组件藏起来:它先保持整颗可读的胶囊,光标离开约 2.5 秒后才滑到屏外只留一条细边,光标碰到细边就滑回来。重新打开一个上次吸在边上的小组件也是这套时序(先胶囊、后收起);刚唤出的小组件即使默认落点就贴着边,也只停在胶囊态。使用前先判断 `capabilities.floating`:Web 宿主没有窗口,桌面宿主也可能不支持窗口管理。
```js
if (window.dbxPlugin.capabilities.floating) {
// 在标签或 dock 工作台里:打开小组件。
// 一个(插件, workbench contribution)只会有一个窗口,重复调用只是把已有窗口带到前台。
const { windowId } = await window.dbxPlugin.floating.open({
contributionId: "capsule",
title: "Now playing",
width: 260,
height: 60,
context: { queueId: currentQueueId },
});
}
// 在小组件内部(context.surface === "window"):控制自己所在的窗口。
grip.addEventListener("pointerdown", (event) => {
grip.setPointerCapture(event.pointerId);
dragging = false;
});
grip.addEventListener("pointermove", async (event) => {
if (dragging || Math.hypot(event.clientX - downX, event.clientY - downY) < 4) return;
dragging = true;
// 从这一刻起窗口归宿主移动:它自己读原生光标,不需要插件逐帧上报。
await window.dbxPlugin.floating.beginDrag();
});
grip.addEventListener("pointerup", async () => {
if (!dragging) return;
dragging = false;
await window.dbxPlugin.floating.endDrag(); // 吸附并记住位置
});
```
| API | 作用 |
| --- | --- |
| `floating.open(options)` | 为本插件的某个 `workbench` contribution 打开(或前置)浮动窗口。`options`:`contributionId`(必填)、`title`、逻辑像素的 `width`/`height`、物理屏幕像素的 `x`/`y`、`alwaysOnTop`(默认 `true`)、`skipTaskbar`(默认 `true`)、`resizable`(默认 `false`)、`context`。返回 `{ windowId, reused }`;需要 `host.workbench`。 |
| `floating.close(contributionId?)` | 关闭本插件的浮动窗口——指定某个 contribution,或省略 id 关闭本插件的全部浮动窗口。在小组件内部不带参数调用即关闭自己。 |
| `floating.beginDrag()` | 把窗口交给宿主的拖动循环。在 `pointermove` 里、自己的拖动阈值越过之后调用(此时按键还按住)。之后由宿主自己读原生光标,插件没有逐帧调用要做。 |
| `floating.endDrag({ snap? })` | 结束拖动。`snap`(默认 `true`)时宿主把窗口齐着它到达或越过的工作区边缘吸附并停靠在那(先保持整颗胶囊,光标离开一会儿才收起到屏外、只留一条悬停细边),落点在屏幕中间则完整夹回屏内;位置与停靠边都会记住,供下次打开使用。返回物理像素的最终矩形。实践中可不调:宿主在光标静止后也会自己收尾,收不到 pointerup 的小组件不会把窗口一直粘在光标上。 |
| `floating.setSize(width, height)` | 以逻辑像素调整所在窗口大小;宿主会夹到自己的上下限内。 |
小组件决定拖动**何时**开始(哪个元素是拖拽把手、指针要先走多远);窗口由宿主移动,吸附与位置记忆也归宿主。刻意没有逐帧的桥调用:宿主轮询原生光标,webview 忙不过来时小组件也照样贴着指针走,光标静止即收尾,pointerup 丢了也不会一直拖下去。几何类调用(`beginDrag`/`endDrag`/`setSize`)只在浮动窗口内部有效,在其他表面调用会被拒绝,因此标签页永远无法移动它不在其中的窗口。
几条规则让这个表面的行为可预期:
- **一个 contribution 只有一个窗口。** 窗口 id 由插件 id 和 contribution id 推导,所以 `floating.open` 是幂等的:第二次调用会把已开的窗口带到前台,而不是叠出更多小组件。
- **窗口是不透明的。** 宿主自己不画任何外壳,用户看到的就是小组件本身:给页面一个背景加圆角,配合宿主按内容收好的窗口尺寸,读起来就是浮在桌面上的一张卡片。刻意不提供逐像素透明(带镂空角的塑形小组件)——透明区域还收不收鼠标事件各平台不一致,而一个要给用户拖的小组件必须处处点得动。
- **外壳导航会被转发。** 浮动窗口没有标签栏、dock 和面板,所以从它发起的 `openWorkbench` 和 `openFilesystem` 会在 DBX 主窗口里打开,主窗口会自行前置。`executeCommand` 在这个表面完全不提供:每个命令动作都要打开一个外壳表面,调用会成功返回但什么都看不见。
- **位置跨重启保留**,按插件和 contribution 分别记录;当记录的位置已经不在任何已连接的显示器上时会被丢弃(拔掉显示器后退化为工作区默认位置,而不是开到屏幕外)。
- **小组件就是一个完整工作台。** 它拿到和标签页相同的桥、权限、上下文契约和 sidecar RPC;`context.surface` 为 `"window"`,`context.workbenchId` 为窗口 id。它启动的是你 UI 的另一份实例,所以共享状态必须走 sidecar(或 `storage`),不能指望模块内存。
### 主题、布局和静态资源 ### 主题、布局和静态资源
DBX 将主题 tokens 注入文档根元素,并更新 `data-dbx-theme`。自定义组件库(包括 Svelte、shadcn-svelte)应使用这些变量,不要依赖父页面 CSS 自动穿透 iframe: DBX 将主题 tokens 注入文档根元素,并更新 `data-dbx-theme`。自定义组件库(包括 Svelte、shadcn-svelte)应使用这些变量,不要依赖父页面 CSS 自动穿透 iframe:
@@ -723,6 +780,14 @@ UI 必须构建为包内静态资源,不要把 Vite 开发服务器或 CDN 的
宿主会把入口脚本内联进沙箱文档,`ui/` 下的其余资源在运行时通过 `dbx-plugin` 协议保持可寻址:`dbx-plugin://localhost/<插件id>/<ui.root内相对路径>`(WebView2 上映射为 `http://dbx-plugin.localhost/<插件id>/…`)。宿主会把平台对应的形式注入为沙箱文档的 `<base>`,并放行资源类 CSP,因此打包后的插件可以正常动态 `import()` 代码分割的 chunk——前提是构建产物使用**相对**资源地址:Vite 设 `base: "./"`、webpack 设 `publicPath: "./"`,让 chunk 和 CSS 资源地址基于注入的 base 解析而不是宿主 origin。绝对路径 `/assets/…` 携带不了插件 id,会 404。该协议只读文件、限定在每个插件的 `ui.root` 内,且插件更新后不会沿用旧缓存。 宿主会把入口脚本内联进沙箱文档,`ui/` 下的其余资源在运行时通过 `dbx-plugin` 协议保持可寻址:`dbx-plugin://localhost/<插件id>/<ui.root内相对路径>`(WebView2 上映射为 `http://dbx-plugin.localhost/<插件id>/…`)。宿主会把平台对应的形式注入为沙箱文档的 `<base>`,并放行资源类 CSP,因此打包后的插件可以正常动态 `import()` 代码分割的 chunk——前提是构建产物使用**相对**资源地址:Vite 设 `base: "./"`、webpack 设 `publicPath: "./"`,让 chunk 和 CSS 资源地址基于注入的 base 解析而不是宿主 origin。绝对路径 `/assets/…` 携带不了插件 id,会 404。该协议只读文件、限定在每个插件的 `ui.root` 内,且插件更新后不会沿用旧缓存。
#### 内联后的样式表
宿主会读取所有指向 `ui.root` 内部的 `<link rel="stylesheet">`,替换成带同样属性的 `<style>` 元素,因此插件运行时仍然能找到自己的样式表(`document.querySelectorAll("style[data-skin-css]")`)并切换它们。有一处差异需要注意:`disabled` 在 `<style>` 元素上不会像 `<link>` 那样从内容属性反映到 IDL,宿主重新序列化时也无法用 IDL 属性把它带过去。所以自带 disabled 样式表的插件必须在加载后自己重新设置 `sheet.disabled = true`;其余属性(id、`data-*` 标记、`media`)都会原样保留。
#### 全屏
沙箱里的 `requestFullscreen()` 取决于框架的 Permissions-Policy,宿主已经做了委派(`allow="clipboard-write; fullscreen"`)。插件无法自己授予该策略,因此应当用 `document.fullscreenEnabled` 做特性检测,为 `false` 时退化成页面内的最大化布局——否则在不委派该策略的旧宿主上,每次全屏请求都会被拒绝。
## 原生 Sidecar 和 RPC ## 原生 Sidecar 和 RPC
只有浏览器沙箱无法完成的能力才需要原生后端,例如 S3/SSH 协议、系统凭据、长连接或高性能计算。Sidecar 不是操作系统沙箱,会以当前用户权限运行。 只有浏览器沙箱无法完成的能力才需要原生后端,例如 S3/SSH 协议、系统凭据、长连接或高性能计算。Sidecar 不是操作系统沙箱,会以当前用户权限运行。
+66 -1
View File
@@ -321,6 +321,8 @@ Context may contain `null`, booleans, finite numbers, strings, arrays, and plain
Connection provider fields using `binding: "config"` are persisted in `external_config`; fields using `binding: "secret"` are persisted in the Secret Store. Plugin connection configuration keeps `external_config` through create, edit, save, and reconnect flows. Connection provider fields using `binding: "config"` are persisted in `external_config`; fields using `binding: "secret"` are persisted in the Secret Store. Plugin connection configuration keeps `external_config` through create, edit, save, and reconnect flows.
The host also authors three reserved fields on every workbench context: `workbenchId` (a stable host-generated instance id), `restored`, and `surface`. `surface` tells the UI which container it is running in — `"tab"` (the main multi-tab workbench), `"dock"` (the bottom panel), or `"window"` (a floating desktop widget window, see [Floating Windows](#floating-windows)). The same plugin and contribution can be open on several surfaces at once, each with its own context and lifecycle; unknown values should fall back to `"tab"` behavior.
## Frontend Host API ## Frontend Host API
The UI runs in an isolated iframe. DBX exposes the bridge as `window.dbxPlugin`; do not import DBX Vue/Tauri modules or assume that Node.js, local files, or arbitrary network access are available. The UI runs in an isolated iframe. DBX exposes the bridge as `window.dbxPlugin`; do not import DBX Vue/Tauri modules or assume that Node.js, local files, or arbitrary network access are available.
@@ -350,13 +352,14 @@ const assetUrl = await window.dbxPlugin.readAssetUrl("assets/empty-state.svg");
| `sendBinary(channel, data)` / `onBinary(fn)` | Sends or receives binary data; requires framed transport and `host.binary`. | | `sendBinary(channel, data)` / `onBinary(fn)` | Sends or receives binary data; requires framed transport and `host.binary`. |
| `readAsset(path)` / `readAssetUrl(path)` | Reads a packaged asset within the plugin resource root. | | `readAsset(path)` / `readAssetUrl(path)` | Reads a packaged asset within the plugin resource root. |
| `openWorkbench(id, context)` | Opens another workbench from this plugin; requires `host.workbench`. | | `openWorkbench(id, context)` | Opens another workbench from this plugin; requires `host.workbench`. |
| `closeWorkbench()` | Closes the surface hosting this UI — a workbench tab, a dock entry, or this plugin's floating window. It is the same path as the `Ctrl/Cmd+W` shortcut, so a plugin can offer its own close or minimize affordance. |
| `executeCommand(commandId, context?)` | Executes one of this plugin's own declared commands through the same path as a menu placement — re-checks `enablement`, applies singleton reuse, and follows the declared `presentation` (panel commands dock, tab commands open tabs). `context` merges over the command context and scopes `instance_key` `{{path}}` placeholders, so `instance_key: "logs:{{connectionId}}"` yields one panel instance per connection. Resolves `{ error }` for expected outcomes; requires `host.workbench`. | | `executeCommand(commandId, context?)` | Executes one of this plugin's own declared commands through the same path as a menu placement — re-checks `enablement`, applies singleton reuse, and follows the declared `presentation` (panel commands dock, tab commands open tabs). `context` merges over the command context and scopes `instance_key` `{{path}}` placeholders, so `instance_key: "logs:{{connectionId}}"` yields one panel instance per connection. Resolves `{ error }` for expected outcomes; requires `host.workbench`. |
| `openFilesystem(id, context)` | Opens a filesystem entry; requires `host.filesystem`. | | `openFilesystem(id, context)` | Opens a filesystem entry; requires `host.filesystem`. |
| `getPlanCapabilities(connectionId)` | Reads what the host and this connection can plan; requires `host.plans:read`. | | `getPlanCapabilities(connectionId)` | Reads what the host and this connection can plan; requires `host.plans:read`. |
| `explainPlan({ connectionId, database?, schema?, sql, mode, timeoutMs? })` | Returns the estimated plan for `sql`; requires `host.plans:read`. | | `explainPlan({ connectionId, database?, schema?, sql, mode, timeoutMs? })` | Returns the estimated plan for `sql`; requires `host.plans:read`. |
| `getTableMetadata({ connectionId, database?, schema?, table })` | Reads narrow table schema metadata from an already-open connection; requires `host.schema:read`. | | `getTableMetadata({ connectionId, database?, schema?, table })` | Reads narrow table schema metadata from an already-open connection; requires `host.schema:read`. |
| `queryData({ connectionId, database?, schema?, sql, maxRows?, timeoutMs? })` | Runs one read-only SQL statement on a connection the user granted to the plugin; requires `host.data:read`. | | `queryData({ connectionId, database?, schema?, sql, maxRows?, timeoutMs? })` | Runs one read-only SQL statement on a connection the user granted to the plugin; requires `host.data:read`. |
| `capabilities` | `{ downloadFile, planApi, schemaMetadataApi, dataApi, storage, ai, aiRecommendations, clipboardWrite, clipboardRead }` from the init message. A missing or `false` entry means that Host API group is unavailable here, so gate the matching call on it instead of probing with a request. | | `capabilities` | `{ downloadFile, planApi, schemaMetadataApi, dataApi, storage, ai, aiRecommendations, clipboardWrite, clipboardRead, floating }` from the init message. A missing or `false` entry means that Host API group is unavailable here, so gate the matching call on it instead of probing with a request. |
| `ai.openConversation({ title, prompt, context, send?, mode? })` | Opens a new plugin conversation in the built-in AI panel; `send` defaults to `false` and `mode` defaults to `ask`. `mode: "agent"` uses live plugin tools when context includes an open plugin connection; requires `host.ai` and is advertised as `capabilities.ai`. | | `ai.openConversation({ title, prompt, context, send?, mode? })` | Opens a new plugin conversation in the built-in AI panel; `send` defaults to `false` and `mode` defaults to `ask`. `mode: "agent"` uses live plugin tools when context includes an open plugin connection; requires `host.ai` and is advertised as `capabilities.ai`. |
| `ai.setRecommendations({ context, items })` | Replaces the current workbench's default recommendations and refreshes the global AI panel; up to five items are shown and `{{path.to.value}}` placeholders are supported; requires `host.ai` and `capabilities.aiRecommendations`. | | `ai.setRecommendations({ context, items })` | Replaces the current workbench's default recommendations and refreshes the global AI panel; up to five items are shown and `{{path.to.value}}` placeholders are supported; requires `host.ai` and `capabilities.aiRecommendations`. |
| `ai.clearRecommendations()` | Clears recommendations for the current workbench; requires `host.ai` and `capabilities.aiRecommendations`. | | `ai.clearRecommendations()` | Clears recommendations for the current workbench; requires `host.ai` and `capabilities.aiRecommendations`. |
@@ -364,6 +367,7 @@ const assetUrl = await window.dbxPlugin.readAssetUrl("assets/empty-state.svg");
| `storage` | Persistent per-plugin key-value state; requires `host.storage`; see below. | | `storage` | Persistent per-plugin key-value state; requires `host.storage`; see below. |
| `fileTransfer` | Streams local files, downloads, and (desktop) OS drops; see below. | | `fileTransfer` | Streams local files, downloads, and (desktop) OS drops; see below. |
| `clipboard` | System clipboard access from the sandbox; see below. | | `clipboard` | System clipboard access from the sandbox; see below. |
| `floating` | Opens and drives a floating desktop widget window (desktop hosts only); see [Floating Windows](#floating-windows). |
Failed calls reject their Promise; show a useful error and offer retry. Host methods, parameters, and results are versioned API surface—do not call undocumented DBX internals. Failed calls reject their Promise; show a useful error and offer retry. Host methods, parameters, and results are versioned API surface—do not call undocumented DBX internals.
@@ -680,6 +684,59 @@ await dbxPlugin.ai.openConversation({
`title` allows 200 characters and `prompt` allows 32000. `context` must be a plain JSON object and is limited to 2 MiB. An Agent can use only tools exposed by the Host for that plugin connection; the plugin receives no model response or model configuration and gains no database execution capability. Older plugins without recommendations continue to use the existing AI API, and older hosts omit the new capability fields, so disable only the unavailable entry points and keep the rest of the plugin usable. `title` allows 200 characters and `prompt` allows 32000. `context` must be a plain JSON object and is limited to 2 MiB. An Agent can use only tools exposed by the Host for that plugin connection; the plugin receives no model response or model configuration and gains no database execution capability. Older plugins without recommendations continue to use the existing AI API, and older hosts omit the new capability fields, so disable only the unavailable entry points and keep the rest of the plugin usable.
### Floating Windows
A floating window is one of your plugin's workbenches hosted in its own frameless, always-on-top desktop window instead of inside the DBX shell — the surface a small always-visible widget wants (a player capsule, a session badge, a quick picker). It stays on top of other applications and can be dragged anywhere on the desktop. Released mid-screen it stays where it landed; released on or past a work-area edge — however hard it was shoved — it snaps flush onto that edge and docks there. Docking never hides the widget the moment it lands: it stays a fully readable capsule, tucks off-screen behind a thin strip about 2.5 seconds after the cursor leaves it, and slides back out while the cursor is over that strip. Reopening a widget that was left docked behaves the same way (capsule first, then tuck); one that was simply summoned is left as a capsule even though its default placement touches an edge. Gate on `capabilities.floating`: the web host has no windows, and neither does a desktop host that cannot manage them.
```js
if (window.dbxPlugin.capabilities.floating) {
// From a tab or dock workbench: open the widget. One window per
// (plugin, workbench contribution), so a second call focuses the existing one.
const { windowId } = await window.dbxPlugin.floating.open({
contributionId: "capsule",
title: "Now playing",
width: 260,
height: 60,
context: { queueId: currentQueueId },
});
}
// Inside the widget (context.surface === "window"): drive its own window.
grip.addEventListener("pointerdown", (event) => {
grip.setPointerCapture(event.pointerId);
dragging = false;
});
grip.addEventListener("pointermove", async (event) => {
if (dragging || Math.hypot(event.clientX - downX, event.clientY - downY) < 4) return;
dragging = true;
// The host takes over: it follows the native cursor and moves the window.
await window.dbxPlugin.floating.beginDrag();
});
grip.addEventListener("pointerup", async () => {
if (!dragging) return;
dragging = false;
await window.dbxPlugin.floating.endDrag(); // snaps + remembers the position
});
```
| API | Purpose |
| --- | --- |
| `floating.open(options)` | Opens (or focuses) the floating window for one of this plugin's `workbench` contributions. `options`: `contributionId` (required), `title`, `width`/`height` in logical pixels, `x`/`y` in physical screen pixels, `alwaysOnTop` (default `true`), `skipTaskbar` (default `true`), `resizable` (default `false`), `context`. Resolves `{ windowId, reused }`; requires `host.workbench`. |
| `floating.close(contributionId?)` | Closes this plugin's floating window — one contribution, or every floating window of this plugin when the id is omitted. Inside a widget, calling it without an argument closes the widget itself. |
| `floating.beginDrag()` | Hands the window to the host's drag loop. Call it from `pointermove` once your drag threshold trips, while the button is still down. The host reads the native cursor itself from here on, so there is no per-move call to make. |
| `floating.endDrag({ snap? })` | Ends the drag. With `snap` (default `true`) the host pulls the window flush onto a work-area edge it reached or passed — docking it there, capsule first and tucked behind a thin strip once the cursor has been away — or clamps it fully on screen otherwise, and remembers the position (and the dock) for the next open. Resolves the final rect in physical pixels. Optional in practice: the host also ends a drag on its own once the cursor goes quiet, so a widget that never sees the pointerup cannot leave the window glued to it. |
| `floating.setSize(width, height)` | Resizes the hosting window in logical pixels; the host clamps to its own bounds. |
The widget decides *when* a drag starts (which element is a grip, how far the pointer must travel first); the host moves the window and owns the snap and the remembered position. There is deliberately no per-move bridge call: the host polls the native cursor, which keeps the widget under the pointer even when the webview is busy, and ends the drag on a quiet cursor if the pointerup never arrives. Geometry calls (`beginDrag`/`endDrag`/`setSize`) only work inside a floating window and reject elsewhere, so a tab can never move a window it is not in.
A few rules make the surface predictable:
- **One window per contribution.** The window id is derived from the plugin and contribution ids, so `floating.open` is idempotent: the second call focuses the window that is already open instead of stacking widgets.
- **The window is opaque.** The host paints no chrome of its own, so the widget is what the user sees: give your page a background plus rounded corners and it reads as a floating card once the host sizes the window to the content. Per-pixel transparency (a shaped widget with see-through corners) is deliberately not offered — whether a transparent region still receives mouse input differs per platform, and a widget the user is meant to drag has to stay clickable everywhere.
- **Shell navigation is forwarded.** A floating window has no tab strip, dock, or panels, so `openWorkbench` and `openFilesystem` from it open in the main DBX window, which raises itself. `executeCommand` is not offered there at all: every command action opens a shell surface, so it would resolve successfully and show nothing.
- **Position survives restarts** per plugin and contribution, and is discarded when it no longer lands on a connected monitor (an unplugged display falls back to the work-area default rather than opening off-screen).
- **The widget is a full workbench.** It gets the same bridge, permissions, context contract, and sidecar RPC as a tab; `context.surface` is `"window"` and `context.workbenchId` is the window id. It boots its own copy of your UI, so shared state has to travel through your sidecar (or `storage`), not through module memory.
### Themes, Layout, and Static Assets ### Themes, Layout, and Static Assets
DBX injects theme tokens on the document root and updates `data-dbx-theme`. Custom libraries, including Svelte and shadcn-svelte, should consume these variables; parent-page CSS does not cross the iframe: DBX injects theme tokens on the document root and updates `data-dbx-theme`. Custom libraries, including Svelte and shadcn-svelte, should consume these variables; parent-page CSS does not cross the iframe:
@@ -723,6 +780,14 @@ Build the UI as packaged static assets, not references to a Vite server or CDN s
The host inlines the entry script into the sandbox document; further `ui/` assets stay addressable at runtime through the `dbx-plugin` scheme — `dbx-plugin://localhost/<plugin-id>/<path-under-ui.root>` (WebView2 maps it to `http://dbx-plugin.localhost/<plugin-id>/…`). The host injects the platform-correct form as the sandbox document's `<base>` and allows it in the resource CSP, so dynamic `import()` of code-split chunks works in packaged plugins — provided the build emits **relative** asset URLs: set `base: "./"` (Vite) or `publicPath: "./"` (webpack) so chunk and CSS asset URLs resolve against the injected base instead of the host origin. Absolute `/assets/…` references cannot carry the plugin id and will 404. The scheme serves files only, confined to each plugin's `ui.root`, and responses are never cached across plugin updates. The host inlines the entry script into the sandbox document; further `ui/` assets stay addressable at runtime through the `dbx-plugin` scheme — `dbx-plugin://localhost/<plugin-id>/<path-under-ui.root>` (WebView2 maps it to `http://dbx-plugin.localhost/<plugin-id>/…`). The host injects the platform-correct form as the sandbox document's `<base>` and allows it in the resource CSP, so dynamic `import()` of code-split chunks works in packaged plugins — provided the build emits **relative** asset URLs: set `base: "./"` (Vite) or `publicPath: "./"` (webpack) so chunk and CSS asset URLs resolve against the injected base instead of the host origin. Absolute `/assets/…` references cannot carry the plugin id and will 404. The scheme serves files only, confined to each plugin's `ui.root`, and responses are never cached across plugin updates.
#### Inlined stylesheets
The host reads every `<link rel="stylesheet">` that points inside `ui.root` and replaces it with a `<style>` element carrying the same attributes, so a plugin can still address its sheets at runtime (`document.querySelectorAll("style[data-skin-css]")`) and toggle them. One difference matters: `disabled` does not reflect from the content attribute on a `<style>` element the way it does on a `<link>`, and the state cannot survive as an IDL property through the host's re-serialization either. A plugin that ships a disabled stylesheet must re-apply `sheet.disabled = true` itself after load; every other attribute (ids, `data-*` markers, `media`) arrives unchanged.
#### Fullscreen
`requestFullscreen()` inside the sandbox depends on the frame's Permissions-Policy, which the host delegates (`allow="clipboard-write; fullscreen"`). A plugin cannot grant it to itself, so feature-detect `document.fullscreenEnabled` and fall back to an in-page maximized layout when it is `false` — an older host that does not delegate would otherwise reject every fullscreen request.
## Native Sidecars and RPC ## Native Sidecars and RPC
Use a native backend only when the browser sandbox cannot provide the capability, such as S3/SSH protocols, system credentials, long-lived connections, or CPU-heavy work. A Sidecar is not an OS sandbox and runs with the current user's privileges. Use a native backend only when the browser sandbox cannot provide the capability, such as S3/SSH protocols, system credentials, long-lived connections, or CPU-heavy work. A Sidecar is not an OS sandbox and runs with the current user's privileges.
+9 -1
View File
@@ -2,13 +2,14 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "enables the default permissions", "description": "enables the default permissions",
"windows": ["main", "detached-tab-*"], "windows": ["main", "detached-tab-*", "plugin-floating-*"],
"permissions": [ "permissions": [
"core:default", "core:default",
"core:window:allow-show", "core:window:allow-show",
"core:window:allow-hide", "core:window:allow-hide",
"core:window:allow-set-theme", "core:window:allow-set-theme",
"core:window:allow-minimize", "core:window:allow-minimize",
"core:window:allow-unminimize",
"core:window:allow-maximize", "core:window:allow-maximize",
"core:window:allow-unmaximize", "core:window:allow-unmaximize",
"core:window:allow-toggle-maximize", "core:window:allow-toggle-maximize",
@@ -22,8 +23,15 @@
"core:window:allow-set-always-on-top", "core:window:allow-set-always-on-top",
"core:window:allow-is-always-on-top", "core:window:allow-is-always-on-top",
"core:window:allow-set-position", "core:window:allow-set-position",
"core:window:allow-set-skip-taskbar",
"core:window:allow-set-size",
"core:window:allow-inner-position", "core:window:allow-inner-position",
"core:window:allow-outer-position",
"core:window:allow-outer-size",
"core:window:allow-scale-factor", "core:window:allow-scale-factor",
"core:window:allow-available-monitors",
"core:window:allow-current-monitor",
"core:window:allow-cursor-position",
"core:webview:allow-create-webview-window", "core:webview:allow-create-webview-window",
"core:webview:allow-set-webview-zoom", "core:webview:allow-set-webview-zoom",
"clipboard-manager:allow-read-text", "clipboard-manager:allow-read-text",
+8
View File
@@ -1821,6 +1821,14 @@ pub fn run() {
return; return;
} }
if let tauri::WindowEvent::CloseRequested { api, .. } = event { if let tauri::WindowEvent::CloseRequested { api, .. } = event {
// Floating plugin widgets (label prefix shared with the frontend's
// floatingWindowLabel) close like ordinary windows. Hiding them to
// the tray would keep their plugin instance — audio included —
// running invisibly, and the app-wide close prompt belongs to the
// main shell, not to a widget the user dismissed.
if window.label().starts_with("plugin-floating-") {
return;
}
if let Some(tab_id) = window.label().strip_prefix("detached-tab-") { if let Some(tab_id) = window.label().strip_prefix("detached-tab-") {
if commands::app_settings::take_approved_detached_window_close(window.label()) { if commands::app_settings::take_approved_detached_window_close(window.label()) {
return; return;