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 { resolveWindowContext } from "@/lib/app/windowContext";
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 type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostBridge";
@@ -539,6 +540,7 @@ const pluginWorkbenchTabRefs = new Map<string, PluginWorkbenchTabHandle>();
const tabNavigationHistory = ref(createTabNavigationHistory());
let pendingTabHistoryNavigationId: string | null = null;
let detachedEventUnlisteners: Array<() => void> = [];
let floatingEventUnlisteners: Array<() => void> = [];
let detachedCloseInProgress = false;
const detachedDropTargetTabId = ref<string | null>(null);
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 }) {
if (isDetachedWindowContext || !isDetachableTab(tab)) return;
try {
@@ -4422,6 +4472,7 @@ onMounted(async () => {
});
setupCloseActionPromptListener();
void setupDetachedWindowEvents();
void setupFloatingWindowEvents();
console.log(`[STARTUP] onMounted sync done: ${(performance.now() - mountStart).toFixed(0)}ms`);
});
@@ -4432,6 +4483,8 @@ onUnmounted(() => {
connectionLivenessUnlisten = null;
detachedEventUnlisteners.forEach((unlisten) => unlisten());
detachedEventUnlisteners = [];
floatingEventUnlisteners.forEach((unlisten) => unlisten());
floatingEventUnlisteners = [];
cleanupTauriListeners();
cleanupCloseActionPromptListener();
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,
} from "@/lib/plugins/pluginHostBridge";
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 { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
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}`);
/**
* 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. */
function currentBridgeTheme(): PluginBridgeTheme {
const tokens: Record<string, string> = {};
@@ -509,8 +524,12 @@ function createBridge() {
// the single-plugin registry is equivalent here because findCommand /
// findWorkbench / enablement never cross plugins. Panel commands dock,
// tab commands open tabs, §4.1 reuse with `instance_key` placeholder
// scoping — identical to menu execution.
executeCommand: (pluginId, commandId, context) => executePluginCommand(createFrontendPluginRegistry([props.plugin], appLocale.value), useQueryStore(), pluginId, commandId, context),
// scoping — identical to menu execution. Not offered on the floating
// 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),
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).
@@ -541,6 +560,16 @@ function createBridge() {
await api.setPluginDataGrant(pluginId, connectionId, true);
},
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),
downloadFile: isTauriRuntime() ? downloadPluginFile : undefined,
cancelDownload: isTauriRuntime() ? cancelPluginDownload : undefined,
@@ -794,8 +823,8 @@ onBeforeUnmount(() => {
</script>
<template>
<div class="relative flex size-full min-h-40 overflow-hidden bg-background">
<div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center bg-background text-sm text-muted-foreground">
<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 text-sm text-muted-foreground" :class="overlayClass">
<Loader2 class="mr-2 size-4 animate-spin" />
{{ t("pluginPlatform.loadingTitle", { title }) }}
</div>
@@ -804,13 +833,17 @@ onBeforeUnmount(() => {
<span>{{ error }}</span>
</div>
<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
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
phase is visually identical to the host background, and faded out
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" />
{{ t("pluginPlatform.loadingTitle", { title }) }}
</div>
+106 -4
View File
@@ -1,8 +1,20 @@
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 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;
@@ -10,6 +22,64 @@ export function detachedWindowLabel(tabId: string): string {
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 {
if (cachedContext) return cachedContext;
if (!isTauriRuntime()) {
@@ -17,15 +87,32 @@ export function resolveWindowContext(): WindowContext {
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) {
// The window label is not available synchronously from the Tauri API. The
// deterministic label is also what the creator uses, so it is sufficient
// for routing and event targeting during bootstrap.
cachedContext = { kind: "detached-tab", windowLabel: detachedWindowLabel(tabId), tabId };
} else {
cachedContext = { kind: "main", windowLabel: "main" };
return cachedContext;
}
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;
}
@@ -33,6 +120,10 @@ export function isDetachedWindow(): boolean {
return resolveWindowContext().kind === "detached-tab";
}
export function isFloatingPluginWindow(): boolean {
return resolveWindowContext().kind === "plugin-window";
}
export function detachedTabId(): string | undefined {
const context = resolveWindowContext();
return context.kind === "detached-tab" ? context.tabId : undefined;
@@ -44,3 +135,14 @@ export function detachedWindowUrl(tabId: string): string {
url.hash = "";
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 { 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 { floatingWindowLabel } from "@/lib/app/windowContext";
import { parseFloatingWindowRequest, type FloatingRect, type OpenFloatingWindowRequest, type OpenFloatingWindowResult } from "@/lib/plugins/pluginFloatingWindow";
const PLUGIN_MESSAGE_SOURCE = "dbx-plugin";
const HOST_MESSAGE_SOURCE = "dbx-host";
@@ -225,6 +227,27 @@ export interface PluginHostBridgeApi {
/** Persists the grant the user just allowed. */
grantDataAccess?(pluginId: string, connectionId: string): Promise<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. */
saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): 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,
clipboardImageRead: !!this.api.clipboardReadImage,
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:
// portable plugins gate on these flags instead of probing calls.
fileTransfer: {
@@ -933,9 +959,54 @@ export class PluginHostBridge {
await this.api.storageDelete(this.plugin.manifest.id, requireStorageKey(input.key));
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}'`);
}
/** 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> {
const now = Date.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 }));
},
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
// placement takes (enablement, §4.1 reuse, host-authored context),
// scoped to the plugin's own declared commands. The optional context
@@ -1653,6 +1747,12 @@ function requireStorageKey(value: unknown): string {
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 {
const binary = atob(value);
const bytes = new Uint8Array(binary.length);
@@ -97,6 +97,17 @@ async function inlineLocalUiAssets(html: string, pluginId: string): Promise<Plug
resource.replaceWith(script);
} else {
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;
resource.replaceWith(style);
}
+18
View File
@@ -6,6 +6,7 @@ import { retryStartupAfterPreloadFailure } from "@/lib/startup/startupPreloadRec
import { markStartupPhase } from "@/lib/startup/startupTiming";
import { applyLegacyWebViewClass, isBlockingCompatFailure } from "@/lib/ui/legacyWebView";
import { hydrateAppAppearance } from "@/lib/app/appAppearance";
import { isFloatingPluginWindow } from "@/lib/app/windowContext";
function startupErrorMessage(error: unknown): string {
if (error instanceof Error) {
@@ -92,6 +93,23 @@ async function bootstrap() {
// durable appearance record before importing i18n and the theme composable;
// those modules synchronously read the compatibility keys during evaluation.
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")]);
console.log("[STARTUP] frontend modules loaded");
const localeReady = loadSavedLocale();