Skip to content

armgit / dbx

Public Imported from GitHub
0

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

test: drop source-text assertion tests and merge locale checks

t8y28897e1271487
diff --git a/apps/desktop/src/__tests__/searchShortcutRouting.spec.ts b/apps/desktop/src/__tests__/searchShortcutRouting.spec.ts
deleted file mode 100644
index cd1a480393..0000000000
--- a/apps/desktop/src/__tests__/searchShortcutRouting.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../App.vue", import.meta.url), "utf8");
-const sidebarSource = readFileSync(new URL("../components/layout/AppSidebar.vue", import.meta.url), "utf8");
-const connectionTreeSource = readFileSync(new URL("../components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
-const treeItemSource = readFileSync(new URL("../components/sidebar/TreeItem.vue", import.meta.url), "utf8");
-const contentAreaSource = readFileSync(new URL("../components/layout/ContentArea.vue", import.meta.url), "utf8");
-const dataGridSource = readFileSync(new URL("../components/grid/DataGrid.vue", import.meta.url), "utf8");
-const objectBrowserSource = readFileSync(new URL("../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
-const aiAssistantSource = readFileSync(new URL("../components/editor/AiAssistant.vue", import.meta.url), "utf8");
-const settingsSource = readFileSync(new URL("../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-const sqlLibrarySource = readFileSync(new URL("../components/layout/SqlLibraryPanel.vue", import.meta.url), "utf8");
-const historySource = readFileSync(new URL("../components/editor/QueryHistory.vue", import.meta.url), "utf8");
-const driverStoreSource = readFileSync(new URL("../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
-const pluginCenterSource = readFileSync(new URL("../components/plugins/PluginContributionsPanel.vue", import.meta.url), "utf8");
-const connectionDialogSource = readFileSync(new URL("../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
-describe("search shortcut focus routing", () => {
- it("prioritizes the sidebar when Ctrl+F originates in the navigation area", () => {
- expect(appSource).toMatch(/const target = e\.target instanceof Element \? e\.target : null;[\s\S]*target\?\.closest\("\[data-app-sidebar\]"\)[\s\S]*appSidebarRef\.value\?\.focusSearch\(target\)/);
- expect(sidebarSource).toContain("<div data-app-sidebar");
- });
-
- it("routes a focused sidebar table-search control to its own input", () => {
- expect(connectionTreeSource).toMatch(/function focusSearch\(target: Element \| null = null\)[\s\S]*data-sidebar-table-search-control[\s\S]*data-sidebar-table-search-parent-id/);
- expect(treeItemSource).toMatch(/function onTableSearchControlKeydown\(event: KeyboardEvent\)[\s\S]*isFocusSearchShortcut\(event, settingsStore\.editorSettings\.shortcuts\)[\s\S]*data-sidebar-table-search-parent-id/);
- expect(treeItemSource).toContain("data-sidebar-table-search-control");
- });
-
- it("routes a focused table properties panel to its local search input", () => {
- expect(contentAreaSource).toMatch(/function focusSearch\(target: Element \| null = null\)[\s\S]*dataGridRef\.value\?\.focusSearch\(target\)/);
- expect(dataGridSource).toMatch(/function focusSearch\(target: Element \| null = null\)[\s\S]*data-table-info-drawer[\s\S]*data-table-info-search/);
- expect(dataGridSource).toMatch(/focusSearch\(event\.target instanceof Element \? event\.target : document\.activeElement instanceof Element \? document\.activeElement : null\);/);
- expect(objectBrowserSource).toMatch(/function focusSearch\(target: Element \| null = null\)[\s\S]*data-object-table-info-panel[\s\S]*data-table-info-search/);
- });
-
- it("routes auxiliary page and panel searches before the query surface", () => {
- expect(appSource).toMatch(/function focusSearchInAuxiliarySurface\(target: Element \| null\)[\s\S]*data-connection-db-search[\s\S]*data-settings-global-search[\s\S]*data-driver-store-agent-search[\s\S]*data-plugin-marketplace-search[\s\S]*data-history-panel[\s\S]*data-sql-library-panel/);
- expect(appSource).toMatch(/lastFocusedAuxiliarySurface[\s\S]*rememberAuxiliarySearchSurface[\s\S]*data-sql-library-panel/);
- expect(appSource).toMatch(/const targetIsDocument = !target \|\| target === document\.body \|\| target === document\.documentElement;[\s\S]*if \(!targetIsDocument\) return false;/);
- expect(appSource).toMatch(/lastFocusedSidebarSurface[\s\S]*rememberSidebarSearchSurface[\s\S]*data-app-sidebar/);
- expect(appSource).toMatch(/function handleAuxiliarySearchKeydownCapture\(e: KeyboardEvent\)[\s\S]*focusSearchInAuxiliarySurface\(target\)[\s\S]*addEventListener\("keydown", handleAuxiliarySearchKeydownCapture, true\)/);
- expect(appSource).toContain("aiAssistantRef.value.focusSearch()");
- expect(aiAssistantSource).toMatch(/function focusSearch\(\): boolean[\s\S]*setConversationListOpen\(true\)/);
- expect(aiAssistantSource).toContain("data-ai-conversation-search");
- expect(settingsSource).toContain("data-settings-global-search");
- expect(sqlLibrarySource).toContain("data-sql-library-search");
- expect(historySource).toContain("data-history-search");
- expect(driverStoreSource).toContain("data-driver-store-agent-search");
- expect(pluginCenterSource).toContain("data-plugin-marketplace-search");
- expect(connectionDialogSource).toContain("data-connection-db-search");
- });
-
- it("keeps the search shortcut inside the modal connection dialog", () => {
- expect(appSource).toMatch(/if \(showConnectionDialog\.value\) \{[\s\S]*?data-connection-db-search[\s\S]*?return true;\s*\}/);
- });
-});
diff --git a/apps/desktop/src/components/ai/rich/__tests__/AiChartRendererLayout.spec.ts b/apps/desktop/src/components/ai/rich/__tests__/AiChartRendererLayout.spec.ts
deleted file mode 100644
index b4146cae51..0000000000
--- a/apps/desktop/src/components/ai/rich/__tests__/AiChartRendererLayout.spec.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const rendererSource = readFileSync(new URL("../AiChartRenderer.vue", import.meta.url), "utf8");
-
-describe("AiChartRenderer layout", () => {
- it("establishes the chart height on the parent that vue-echarts fills", () => {
- expect(rendererSource).toContain("min-h-60 h-[clamp(15rem,35vw,20rem)]");
- expect(rendererSource).toContain('class="min-h-0 flex-1"');
- expect(rendererSource).toContain('class="h-full w-full p-2"');
- expect(rendererSource).not.toContain('class="h-80 w-full p-2"');
- });
-
- it("uses the native save dialog and binary writer for PNGs in Tauri", () => {
- expect(rendererSource).toContain('await import("@tauri-apps/plugin-dialog")');
- expect(rendererSource).toContain('await import("@tauri-apps/plugin-fs")');
- expect(rendererSource).toContain("await writeFile(path, new Uint8Array(await blob.arrayBuffer()))");
- });
-
- it("surfaces download failures through a localized toast instead of a hardcoded English tooltip", () => {
- expect(rendererSource).toContain("t('ai.chartDownloadPng')");
- expect(rendererSource).toContain('toast(t("ai.chartDownloadFailed"))');
- const savePath = rendererSource.slice(rendererSource.indexOf("await writeFile(path, new Uint8Array(await blob.arrayBuffer()))"));
- expect(savePath).toContain('} catch {\n toast(t("ai.chartDownloadFailed"));\n }');
- expect(rendererSource).not.toContain('title="Download PNG"');
- expect(rendererSource).not.toContain('aria-label="Download PNG"');
- expect(rendererSource).toContain('t("ai.chartData")');
- });
-});
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts
index 5b6312543d..4436b76430 100644
--- a/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts
+++ b/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts
@@ -3,77 +3,14 @@ import { describe, expect, it } from "vitest";
const services = readFileSync(new URL("../ConsulServices.vue", import.meta.url), "utf8");
const health = readFileSync(new URL("../ConsulHealth.vue", import.meta.url), "utf8");
-const overview = readFileSync(new URL("../ConsulOverview.vue", import.meta.url), "utf8");
-const sessions = readFileSync(new URL("../ConsulSessions.vue", import.meta.url), "utf8");
const scope = readFileSync(new URL("../ConsulScope.vue", import.meta.url), "utf8");
const keyBrowser = readFileSync(new URL("../ConsulKeyBrowser.vue", import.meta.url), "utf8");
const mesh = readFileSync(new URL("../ConsulMesh.vue", import.meta.url), "utf8");
const tools = readFileSync(new URL("../ConsulTools.vue", import.meta.url), "utf8");
const operator = readFileSync(new URL("../ConsulOperator.vue", import.meta.url), "utf8");
-const workspace = readFileSync(new URL("../ConsulWorkspace.vue", import.meta.url), "utf8");
const kvBrowser = readFileSync(new URL("../../kv/KvKeyBrowser.vue", import.meta.url), "utf8");
describe("Consul Catalog and Health watch views", () => {
- it("watches both service and node Catalog resources and cancels them on teardown", () => {
- for (const target of ["catalogServices", "catalogServiceNodes", "catalogNodes", "catalogNodeServices"]) {
- expect(services).toContain(`kind: "${target}"`);
- }
- expect(services).toMatch(/onBeforeUnmount\(\(\) => \{\s*void stopWatches\(\);\s*\}\);/);
- expect(services).toContain("switchBrowseMode");
- });
-
- it("supports state, node, and service Health resources with a scoped watch", () => {
- for (const target of ["healthState", "healthNode", "healthServiceInstances"]) {
- expect(health).toContain(`kind: "${target}"`);
- }
- expect(health).toContain('browseMode = ref<"state" | "node" | "service">');
- expect(health).toMatch(/onBeforeUnmount\(\(\) => \{\s*void stopWatch\(\);\s*\}\);/);
- expect(health).toContain("selectedCheck");
- expect(health).toContain("selectedCheck.Definition");
- });
-
- it("filters and paginates Health results without querying on every target keystroke", () => {
- for (const state of ["browseNameDraft", "keywordFilter", "statusFilter", "typeFilter"]) {
- expect(health).toContain(`const ${state} = ref(`);
- }
- for (const collection of ["filteredChecks", "filteredLocalChecks", "pagedChecks", "pagedLocalChecks", "pagedServiceInstances"]) {
- expect(health).toContain(`const ${collection} = computed(`);
- }
- expect(health).toContain('v-model="browseNameDraft"');
- expect(health).toContain('@keydown.enter="applyBrowseTarget"');
- expect(health).toContain("t('consul.ui.searchHealthChecks')");
- expect(health).toContain("<ConsulListPagination");
- expect(health).not.toContain("watch([state, browseMode, browseName]");
- });
-
- it("shows Catalog metadata and independent Overview probe states", () => {
- expect(services).toContain("item.NodeMeta");
- expect(services).toContain("item.ServiceMeta");
- expect(services).toContain("nodeServices?.Node.NodeMeta");
- for (const state of ["loading", "ready", "forbidden", "unsupported", "error"]) {
- expect(overview).toContain(`"${state}"`);
- }
- expect(overview).toContain("probeStates[key]");
- });
-
- it("binds Session renew to connection and scope lifecycle and exposes lock indexes", () => {
- expect(sessions).toContain("connectionActive");
- expect(sessions).toContain("consulStore.generation");
- expect(sessions).toContain("currentScopeKey()");
- expect(sessions).toContain("clearTimeout(renewTimer)");
- expect(sessions).toContain("item.lockIndex");
- expect(sessions).toContain("session.NodeChecks");
- expect(sessions).toContain("session.ServiceChecks");
- expect(sessions).toContain("!isTtlSession(session)");
- expect(sessions).toContain("ConsulListPagination");
- expect(sessions).toContain("filteredSessions");
- expect(sessions).toContain("await inspectLockKey()");
- expect(sessions).toContain("expectedModifyIndex: lockInspection.value.modifyIndex");
- expect(sessions).toContain("heldKeys[session.ID].complete");
- expect(sessions).toContain("value.items.map(normalizeConsulSession)");
- expect(sessions).toContain("withUiTimeout(api.consulSessions(props.connectionId))");
- });
-
it("renders the complete Enterprise delete impact inventory", () => {
for (const resource of ["kvKeys", "healthChecks", "sessions", "intentions", "peerings", "aclTokens", "aclPolicies", "aclRoles", "aclAuthMethods", "aclBindingRules"]) {
expect(scope).toContain(`value.${resource}`);
@@ -82,65 +19,6 @@ describe("Consul Catalog and Health watch views", () => {
expect(scope).toContain("impact.unavailableResources");
});
- it("offers both Agent service maintenance transitions", () => {
- expect(services).toContain("maintenance(service.ID, true)");
- expect(services).toContain("maintenance(service.ID, false)");
- expect(services).toContain('t("consul.ui.enableMaintenance")');
- expect(services).toContain('t("consul.ui.disableMaintenance")');
- expect(services).toContain('v-if="canAgentWrite && !isServiceInMaintenance(service.ID)"');
- expect(services).toContain('v-else-if="canAgentWrite"');
- expect(services).toContain("t(`consul.ui.agentWriteBlocked.${reason}`)");
- expect(services).toContain("{{ agentWriteDisabledMessage }}");
- });
-
- it("keeps Catalog browsing searchable and separates readable Catalog data from Agent actions", () => {
- expect(services).toContain('const browseFilter = ref("");');
- expect(services).toContain("const filteredServiceNames");
- expect(services).toContain("const filteredNodeNames");
- expect(services).toContain("const localServiceItems");
- expect(services).toContain("const filteredLocalServiceItems");
- expect(services).toContain("<Search class=");
- expect(services).toContain("selectedLocalService?.ID === service.ID");
- expect(services).toContain('<Button v-for="name in pagedServiceNames"');
- expect(services).not.toContain("services[name]?.join(', ')");
- expect(services).toContain('@click="selectService(name)"');
- expect(services).toContain('@click="selectNode(name)"');
- expect(services).toContain("Catalog browsing must remain responsive even when an Agent endpoint is slow or unavailable.");
- const loadSource = services.slice(services.indexOf("async function load() {"), services.indexOf("async function loadAgentData("));
- const catalogReady = loadSource.indexOf("loading.value = false;");
- const agentLoad = loadSource.indexOf("if (current === sequence) await loadAgentData(current);");
- expect(catalogReady).toBeGreaterThanOrEqual(0);
- expect(agentLoad).toBeGreaterThan(catalogReady);
- expect(services).toContain("t('consul.ui.searchAllServices')");
- expect(services).toContain("t('consul.ui.searchLocalServices')");
- });
-
- it("loads Consul tools independently and exposes complete event and result details", () => {
- expect(tools).toContain('const activeTab = ref<ToolTab>("queries")');
- for (const loader of ["loadQueries", "loadEvents", "loadCoordinates"]) {
- expect(tools).toContain(`async function ${loader}()`);
- }
- for (const errorState of ["queryError", "eventError", "coordinateError"]) {
- expect(tools).toContain(`const ${errorState} = ref("")`);
- }
- expect(tools).not.toContain("Promise.allSettled");
- expect(tools).toContain('v-model="eventNodeFilter"');
- expect(tools).toContain('v-model="eventServiceFilter"');
- expect(tools).toContain('v-model="eventTagFilter"');
- expect(tools).toContain("queryResult.Nodes");
- expect(tools).toContain("item.Coord.Adjustment");
- expect(tools).toContain("item.Coord.Height");
- });
-
- it("paginates every potentially large service collection before rendering", () => {
- for (const collection of ["pagedServiceNames", "pagedNodeNames", "pagedCatalogInstances", "pagedNodeServices", "pagedLocalServices"]) {
- expect(services).toContain(`const ${collection} = computed(() => paginateConsulItems(`);
- expect(services).toContain(`v-for="${collection === "pagedCatalogInstances" ? "item" : collection.includes("Names") ? "name" : "service"} in ${collection}"`);
- }
- expect(services).toContain("<ConsulListPagination");
- expect(services).toContain(':page-size="CONSUL_LIST_PAGE_SIZE"');
- });
-
it("gates Agent writes on an explicit target that matches the Agent node", () => {
for (const source of [services, health]) {
expect(source).toContain("config.agentTarget || config.agent_target");
@@ -151,82 +29,12 @@ describe("Consul Catalog and Health watch views", () => {
expect(health).toContain("consulAgentWriteTargetSafe(store.getConfig(props.connectionId), identity.value?.node)");
});
- it("supports exact-Key and prefix KV watches and exposes batch atomicity", () => {
- expect(keyBrowser).toContain('watchMode = ref<"key" | "prefix">("prefix")');
- expect(keyBrowser).toContain('prefix: watchMode.value === "prefix"');
- expect(keyBrowser).toContain(':on-watch-key="watchSelectedKey"');
- expect(keyBrowser).toContain("transferReport.atomic");
- expect(keyBrowser).toContain("deleteReport.atomic");
- expect(keyBrowser).toContain("row.opIndex");
- });
-
- it("keeps the Key prefix search first and groups enhanced Consul KV actions after a divider", () => {
- expect(keyBrowser).toContain("<template #toolbar-trailing>");
- expect(keyBrowser).not.toContain('v-model="watchPrefix" class="h-7 w-52 text-xs"');
- expect(kvBrowser).toContain('<slot name="toolbar-trailing" />');
- expect(kvBrowser).toContain('class="mx-1 h-6 w-px shrink-0 bg-border"');
- });
-
- it("keeps exact-Key watch start and stop beside the selected Key", () => {
- expect(keyBrowser).toContain(":watch-active-key=\"watchRunning && watchMode === 'key' ? watchPrefix : null\"");
- expect(keyBrowser).toContain('watchMode.value === "key" && watchPrefix.value === route.key');
- expect(keyBrowser).toContain("await stopWatch();\n return;");
- });
-
- it("serializes search progress polling and invalidates stale pollers", () => {
- expect(keyBrowser).toContain("searchProgressSequence");
- expect(keyBrowser).toContain("searchProgressTimer = setTimeout");
- expect(keyBrowser).toContain("sequence === searchProgressSequence");
- expect(keyBrowser).not.toContain("searchProgressTimer = setInterval");
- });
-
- it("uses a compact Session-protection card and a metadata grid for Consul KV details", () => {
- expect(kvBrowser).toContain('labels.sessionProtected || "Session protected"');
- expect(kvBrowser).toContain('labels.sessionProtectedHint || "Editing and deletion are disabled to protect this distributed lock."');
- expect(kvBrowser).toContain("copyText(selectedMetadata?.session)");
- expect(kvBrowser).toContain('<dl class="grid grid-cols-2 divide-x divide-y sm:grid-cols-3">');
- expect(kvBrowser).not.toContain('["Session", metadata?.session]');
- });
-
- it("exports the current Consul full-text search result set", () => {
- expect(keyBrowser).toContain("async function exportSearchResults()");
- expect(keyBrowser).toContain('format: "dbx-consul-kv-search-results"');
- expect(keyBrowser).toContain('t("consul.tools.exportSearchResults")');
- });
-
- it("carries full-text match metadata into the selected Consul KV detail", () => {
- expect(keyBrowser).toContain("const searchHighlight = ref<{");
- expect(keyBrowser).toContain("matchesKey: result.matchesKey");
- expect(keyBrowser).toContain(':search-highlight="searchHighlight"');
- });
-
- it("offers the same server-backed prefix completion for export, migration, and prefix deletion", () => {
- expect(keyBrowser).toContain('type PrefixSuggestionTarget = "export" | "migration" | "delete"');
- expect(keyBrowser).toContain("const prefixSuggestionDebounceMs = 300;");
- expect(keyBrowser).toContain("function schedulePrefixSuggestions(target: PrefixSuggestionTarget, value: string)");
- expect(keyBrowser).toContain("schedulePrefixSuggestions(target, suggestion.key);");
- expect(keyBrowser).toContain('event.key !== "Enter" && event.key !== "Tab"');
- expect(keyBrowser).toContain("prefixSuggestionIndex.value >= 0 ? prefixSuggestionIndex.value : 0");
- expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('export'");
- expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('migration'");
- expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('delete'");
- expect(keyBrowser).toContain("@keydown=\"onPrefixSuggestionKeydown('migration', $event)\"");
- expect(keyBrowser).toContain("@keydown=\"onPrefixSuggestionKeydown('delete', $event)\"");
- expect(keyBrowser).toContain('<PopoverContent align="start" side="bottom" :collision-padding="12"');
- expect(keyBrowser).toContain("max-h-[var(--reka-popover-content-available-height)]");
- });
-
it("marks the specific locked Key and Session in a prefix-delete preview", () => {
expect(keyBrowser).toContain("'session' in row && row.session ? 'bg-destructive/5' : ''");
expect(keyBrowser).toContain('v-if="\'session\' in row && row.session" variant="destructive"');
expect(keyBrowser).toContain('t("consul.ui.sessionValue", { id: row.session })');
});
- it("shows the server-provided reason when a prefix-delete operation fails", () => {
- expect(keyBrowser).toContain("'message' in row && row.message");
- expect(keyBrowser).toContain(':title="row.message"');
- });
-
it("opens the safe prefix-delete preview from a Consul directory context menu", () => {
expect(keyBrowser).toContain(':on-delete-prefix="openDeletePrefix"');
expect(keyBrowser).toContain('function openDeletePrefix(prefix = "")');
@@ -243,33 +51,4 @@ describe("Consul Catalog and Health watch views", () => {
expect(operator).toContain("keyringWriteVisible");
expect(operator).toContain("props.capabilities?.operatorKeyring");
});
-
- it("keeps workspace actions fixed while only the tab strip scrolls horizontally", () => {
- expect(workspace).toContain("min-w-0 flex-1 overflow-x-auto overflow-y-hidden");
- expect(workspace).toContain("h-8 w-max min-w-max justify-start");
- expect(workspace).toContain('class="h-7 flex-none gap-1.5 px-3 text-xs"');
- expect(workspace).toContain("flex h-11 shrink-0 items-center gap-2 border-b px-3");
- expect(workspace).toContain('class="flex shrink-0 items-center gap-1"');
- });
-
- it("starts with KV and keeps the cluster overview as a sidebar surface", () => {
- expect(workspace).toContain('const activeTab = ref<WorkspaceTab>(restoredUiState.activeTab ?? "kv");');
- expect(workspace).not.toContain('<TabsTrigger value="overview"');
- expect(workspace).not.toContain('<TabsContent value="overview"');
- });
-
- it("shows the real datacenter by default and gates advanced scope controls by capability", () => {
- expect(workspace).toContain("const resolvedDatacenter = computed(() => activeScope.value.datacenter || capabilities.value?.datacenter");
- expect(workspace).toContain('const enterpriseScopeAvailable = computed(() => capabilities.value?.namespaces === "supported" || capabilities.value?.partitions === "supported");');
- expect(workspace).toContain('v-if="enterpriseScopeAvailable"');
- expect(workspace).toContain('v-if="datacenterOptions.length > 1" v-model="scopeDraft.datacenter"');
- });
-
- it("hides only disabled ACLs and Enterprise-only scope tabs", () => {
- expect(workspace).toContain('const aclVisible = computed(() => capabilities.value?.acl !== "disabled");');
- expect(workspace).toContain("const scopeTabVisible = computed(() => enterpriseScopeAvailable.value);");
- expect(workspace).toContain('v-if="aclVisible" value="acl"');
- expect(workspace).toContain('v-if="scopeTabVisible" value="scope"');
- expect(workspace).toContain('if (activeTab.value === "acl" && !aclVisible.value) activeTab.value = "kv";');
- });
});
diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.spec.ts
deleted file mode 100644
index d6910ac072..0000000000
--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.spec.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../SchemaDiffDialog.vue", import.meta.url), "utf8");
-const sessionSource = readFileSync(new URL("../../../composables/useSchemaDiffSession.ts", import.meta.url), "utf8");
-const configStepSource = readFileSync(new URL("../SchemaDiffConfigStep.vue", import.meta.url), "utf8");
-
-describe("SchemaDiffDialog fullscreen layout", () => {
- it("fits the dialog to its portal instead of the viewport width", () => {
- expect(dialogSource).toContain('width: "100%"');
- expect(dialogSource).toContain('height: "100%"');
- expect(dialogSource).not.toContain('width: "100vw"');
- expect(dialogSource).not.toContain('height: "100vh"');
- });
-
- it("removes the normal dialog gutter and minimum width while maximized", () => {
- expect(dialogSource).toContain(":portal-class=\"isMaximized ? 'p-0' : undefined\"");
- expect(dialogSource).toContain("isMaximized ? 'min-w-0' : 'min-w-[800px] resize'");
- });
-
- it("closes the options panel before allowing Escape to dismiss the dialog", () => {
- expect(dialogSource).toContain('@escape-key-down="handleDialogEscape"');
- expect(dialogSource).toContain("if (!showOptionsPanel.value) return;");
- expect(dialogSource).toContain("event.preventDefault();");
- expect(dialogSource).toContain("showOptionsPanel.value = false;");
- });
-
- it("lets the deploy confirm dialog body shrink so a long destructive statement can't push the footer buttons off-screen", () => {
- expect(dialogSource).toContain('<div class="py-2 space-y-3 min-w-0">');
- });
-
- it("lets the config step scroll vertically so the Compare button stays reachable when 'compare specific tables' is enabled", () => {
- // Regression for #6627: the "compare specific tables" feature (#6533/#6540) grows the
- // config step (table multi-select + same-name match). Under a fixed-height dialog that
- // step used to be clipped (`overflow-hidden`), pushing the Compare button below the
- // visible area with no way to scroll to it. The container must scroll on all steps
- // except the result step, which relies on splitpanes to manage its own height.
- expect(dialogSource).toContain("step === 'result' ? 'overflow-hidden' : 'overflow-y-auto'");
- // The config step must not be flex-shrunk (which would swallow its height and suppress
- // the scrollbar); only then does the taller-than-dialog content actually overflow and
- // become reachable via scrolling.
- expect(dialogSource).toMatch(/<SchemaDiffConfigStep\n[\s\S]*?class="shrink-0"/);
- });
-
- it("clears stale result and progress state whenever a new dialog session opens", () => {
- expect(dialogSource).toContain("function resetComparisonResultState() {");
- expect(dialogSource).toMatch(/if \(!isOpen\) return;[\s\S]*?resetComparisonResultState\(\);/);
- expect(dialogSource).toContain("diffObjects.value = [];");
- expect(dialogSource).toContain("lastDiffResult.value = null;");
- expect(dialogSource).toContain("schemaDiffProgress.value = null;");
- });
-
- it("shows real metadata progress and indeterminate comparison phases without fabricated percentages", () => {
- expect(sessionSource).toContain('phase: "loading-table-lists"');
- expect(sessionSource).toContain('phase: "loading-source-details"');
- expect(sessionSource).toContain('phase: "loading-target-details"');
- expect(sessionSource).toContain('phase: "loading-extra-objects"');
- expect(sessionSource).toContain('phase: "comparing"');
- expect(sessionSource).toContain('phase: "generating"');
- expect(sessionSource).toContain("onProgress: (progress) =>");
- expect(dialogSource).toContain("schemaDiffProgressCount");
- expect(dialogSource).toContain('role="progressbar"');
- expect(dialogSource).toContain("schema-diff-progress-indeterminate");
- expect(dialogSource).not.toMatch(/\b(?:20|40|60|80)%/);
- });
-
- it("renders a localized next-step label alongside the current progress state", () => {
- expect(dialogSource).toContain("getSchemaDiffNextProgressStep");
- expect(dialogSource).toContain("schemaDiffNextProgressLabel");
- expect(dialogSource).toContain('t("diff.progress.next"');
- expect(dialogSource).toContain('v-if="schemaDiffNextProgressLabel"');
- expect(dialogSource).toContain("shouldLoadSchemaDiffExtraObjectPhase");
- });
-
- it("clears progress before preserving the existing comparison error flow", () => {
- expect(sessionSource).toContain("session.error = message;");
- expect(sessionSource).toContain('session.status = "failed";');
- expect(dialogSource).toContain("toast(session.error, 5000);");
- expect(dialogSource).toContain('step.value = "config";');
- });
-
- it("keeps an active comparison running after the dialog unmounts", () => {
- expect(dialogSource).toContain("const session = startSchemaDiffSession(");
- expect(dialogSource).toContain("onBeforeUnmount(() => {");
- expect(dialogSource).toContain("componentUnmounted = true;");
- expect(dialogSource).not.toContain("comparisonRequestId");
- });
-
- it("does not restore persisted table matches before source and target identities are ready", () => {
- expect(configStepSource).toContain('if (!isTableIdentityReady("source")) {');
- expect(configStepSource).toContain("clearUnavailableTableSelection();");
- expect(configStepSource).toContain('v-if="restrictTables && canConfigureTableSelection"');
- expect(configStepSource).toContain("restrictTables && localSelectedTables.length && canConfigureTableSelection && isTableIdentityReady('target')");
- });
-
- it("resets stale target schema and object selection when the target identity changes", () => {
- expect(dialogSource).toContain("suppressTargetIdentityReset");
- expect(dialogSource).toContain("clearCompareObjectSelection");
- expect(dialogSource).toContain("runWithoutTargetIdentityReset");
- expect(dialogSource).toContain("watch(targetConnectionId,");
- expect(dialogSource).toContain("watch(targetDatabase,");
- expect(dialogSource).toContain("watch(targetDbType,");
- expect(dialogSource).toContain('targetDatabase.value = ""');
- expect(dialogSource).toContain('targetSchema.value = ""');
- expect(dialogSource).toContain("isSchemaAware(dbType as DatabaseType)");
- expect(dialogSource).toContain("selectedTables: undefined");
- expect(dialogSource).toContain("selectedRoutines: undefined");
- });
-
- it("gates config table-list loading on the tables compare switch", () => {
- expect(configStepSource).toContain("tablesCompareEnabled.value && shouldLoadSchemaDiffTableList");
- });
-
- it("keeps explicit table selection in a shared scope below both sides", () => {
- const comparisonScope = configStepSource.indexOf("<!-- Comparison Scope -->");
- const targetInfo = configStepSource.indexOf("<!-- Target Info -->");
- const options = configStepSource.indexOf("<!-- Options -->");
- const tableSelectors = configStepSource.match(/<TableMultiSelect\b/g) ?? [];
- const tableSelector = configStepSource.indexOf("<TableMultiSelect", comparisonScope);
- const targetMatch = configStepSource.indexOf("<!-- Target Same-Name Match -->", comparisonScope);
-
- expect(comparisonScope).toBeGreaterThan(targetInfo);
- expect(comparisonScope).toBeLessThan(options);
- expect(tableSelectors).toHaveLength(2);
- expect(tableSelector).toBeGreaterThan(comparisonScope);
- expect(tableSelector).toBeLessThan(options);
- expect(targetMatch).toBeGreaterThan(comparisonScope);
- expect(targetMatch).toBeLessThan(options);
- });
-
- it("wires source-to-target table mappings through the selector and compare request", () => {
- expect(configStepSource).toContain('@update:model-value="(value: string) => handleTableMappingUpdate(match.sourceTable, value)"');
- expect(configStepSource).toContain("tableMatchStatus.${match.kind}");
- expect(dialogSource).toContain('@update:table-mappings="handleTableMappingsUpdate"');
- expect(sessionSource).toContain("tableMappings: sessionOptions.selectedTables === undefined ? undefined : sessionOptions.tableMappings");
- expect(sessionSource).toContain("ignoreTableNameCase: sessionOptions.ignoreTableNameCase");
- expect(sessionSource).toContain("ignoreColumnNameCase: sessionOptions.ignoreColumnNameCase");
- expect(dialogSource).toContain("const swappedMappings = swapSchemaDiffTableMappings(currentOptions.tableMappings ?? []);");
- expect(dialogSource).toContain('value="routines"');
- expect(configStepSource).toContain("handleUpdateSelectedRoutines");
- });
-
- it("exposes table and routine compare switches on the config step", () => {
- expect(configStepSource).toContain('import { Switch } from "@/components/ui/switch"');
- expect(configStepSource).toContain("update:compareScope");
- expect(configStepSource).toContain("handleTablesCompareEnabled");
- expect(configStepSource).toContain("handleRoutinesCompareEnabled");
- expect(configStepSource).toContain("effectiveRoutinesEnabled");
- expect(configStepSource).toContain("const routinesEnabled = effectiveRoutinesEnabled.value");
- expect(configStepSource).toContain("if (!tablesEnabled && !routinesEnabled) return false");
- expect(configStepSource).toContain("unrestrictedRoutineLoadTooLarge");
- expect(configStepSource).toContain("SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT");
- expect(configStepSource).toContain('t("diff.routineSelectionTooLarge"');
- expect(configStepSource).toContain('t("diff.tableCompareDisabled")');
- expect(configStepSource).toContain('t("diff.routineCompareDisabled")');
- expect(configStepSource).toContain("schemaDiffRoutineObjectTypesIntersection");
- expect(configStepSource).toContain('t("diff.routineSameNameMatchingOnly")');
- expect(dialogSource).toContain('@update:compare-scope="handleCompareScopeUpdate"');
- expect(dialogSource).toContain("function handleCompareScopeUpdate");
- expect(dialogSource).toContain("const routinesCompareEnabled = computed(() => !!schemaDiffPanelOptions.value.functions)");
- expect(dialogSource).toContain("effectiveRoutinesEnabled");
- expect(dialogSource).not.toContain("functions: value === undefined ? activeConfig.value.options.functions : true");
- expect(sessionSource).toContain("shouldLoadSchemaDiffRoutines");
- expect(sessionSource).toContain("shouldLoadSchemaDiffExtraObjectPhase");
- expect(sessionSource).toContain("const loadTableMetadata = !!(sessionOptions.tables || sessionOptions.views)");
- expect(sessionSource).not.toContain("options.selectedRoutines !== undefined");
- expect(sessionSource).not.toContain("wantRoutines");
- });
-
- it("shows result tabs only for enabled compare scopes", () => {
- expect(dialogSource).toContain("showTableResultTab");
- expect(dialogSource).toContain("showRoutineResultTab");
- expect(dialogSource).toContain("showResultTabList");
- expect(dialogSource).toContain("tablesCompareEnabled");
- expect(dialogSource).toContain("routinesCompareEnabled");
- expect(dialogSource).toContain("effectiveRoutinesEnabled");
- expect(dialogSource).toContain("showNoDifferences");
- expect(dialogSource).not.toContain("showRoutinesNotCompared");
- expect(dialogSource).toContain("showRoutineNoDifferences");
- expect(dialogSource).toContain('t("diff.resultTabTables"');
- expect(dialogSource).toContain('t("diff.resultTabRoutines"');
- expect(dialogSource).toContain('t("diff.noDifferences")');
- expect(dialogSource).toContain("schemaDiffRoutineObjectTypesIntersection");
- expect(dialogSource).toContain('v-if="showResultTabList"');
- expect(dialogSource).toContain('v-if="showTableResultTab"');
- expect(dialogSource).toContain("data-[state=inactive]:hidden");
- expect(dialogSource).toContain("if (!showTableResultTab.value && showRoutineResultTab.value)");
- expect(dialogSource).toContain("loadObjectSourceWithRoutineFallback");
- });
-
- it("defers routine deploy except for postgres-family targets", () => {
- expect(dialogSource).toContain("showRoutineDeployDeferredHint");
- expect(dialogSource).toContain("canDeployRoutines");
- expect(dialogSource).toContain("isSchemaDiffPostgresLike");
- expect(dialogSource).toContain('t("diff.routineSyncDeferredHint")');
- expect(dialogSource).toContain('if (resultTab.value === "routines" && !canDeployRoutines.value) return false');
- expect(dialogSource).toContain("nextStepDeployRoutines");
- expect(dialogSource).toContain('t("diff.nextStepDeploy")');
- expect(dialogSource).toContain(':selectable="canDeployRoutines"');
- expect(configStepSource).toContain("api.listObjects");
- expect(configStepSource).not.toContain("api.listFunctions");
- });
-
- it("uses the object tree for tables and a dedicated list plus text diff for routines", () => {
- expect(dialogSource).toContain('import SchemaDiffObjectTree from "@/components/diff/SchemaDiffObjectTree.vue"');
- expect(dialogSource).toContain('import SchemaDiffRoutineList from "@/components/diff/SchemaDiffRoutineList.vue"');
- expect(dialogSource).toContain('import SideBySideTextDiff, { type TextDiffSide } from "@/components/common/SideBySideTextDiff.vue"');
- expect(dialogSource).toContain('<SchemaDiffObjectTree :groups="tableDiffGroups"');
- expect(dialogSource).toContain("<SchemaDiffDdlPanel");
- expect(dialogSource).toContain("<SchemaDiffRoutineList");
- expect(dialogSource).toContain(':objects="routineDiffObjects"');
- expect(dialogSource).toContain("handleViewRoutineDiff");
- expect(dialogSource).toContain("<SideBySideTextDiff");
- expect(dialogSource).toContain('t("diff.selectRoutineToCompare")');
- expect(dialogSource).not.toContain(':groups="routineDiffGroups"');
- });
-
- it("keeps focused and selected deployment SQL projections separate", () => {
- expect(dialogSource).toContain('const focusedDeploySql = ref("");');
- expect(dialogSource).toContain('const selectedDeploySql = ref("");');
- expect(dialogSource).toContain("const input = selectSchemaDiffInputForObject(result, diffObjects.value, objectId);");
- expect(dialogSource).toContain(':deploy-sql="focusedDeploySql"');
- expect(dialogSource).toContain(':deploy-sql-all="selectedDeploySql"');
- expect(dialogSource).not.toContain("deploySqlAll.value = result.syncSql");
- });
-
- it("executes the selected SQL rather than the focused preview", () => {
- expect(dialogSource).toContain("sql: selectedDeploySql.value");
- expect(dialogSource).toContain("[selectedDeploySql.value]");
- expect(dialogSource).toContain("selectedObjectId.value !== objectId");
- expect(dialogSource).toContain('selectedDeploySql.value = "";');
- expect(dialogSource).toContain("const sql = selectedDeploySql.value.trim();");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.autoRouting.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.autoRouting.spec.ts
deleted file mode 100644
index ee48001913..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.autoRouting.spec.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// #9118: the AI assistant exposes one "Auto" entry at the head of both action
-// menus. These assertions pin the parts of the wiring that a behavioral unit
-// test cannot reach (the component owns a large amount of shared state):
-//
-// - every explicit action stays in the menu, "auto" is only prepended;
-// - the selection starts concrete; Auto is preselected on new conversations
-// only through the Settings > AI "default auto routing" toggle;
-// - "auto" is resolved to a concrete action BEFORE the request is assembled, so
-// `taskContract.action` never carries it (the backend interpolates that value
-// into its system prompt and uses it for final-answer contract validation);
-// - the vector-DB branch (hidden picker, forced `generate`) is untouched;
-// - external explicit triggers (`triggerAction`) bypass the router.
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-function bodyOf(fnSignature: string): string {
- const start = source.indexOf(fnSignature);
- expect(start, `expected to find "${fnSignature}" in AiAssistant.vue`).toBeGreaterThanOrEqual(0);
- const braceStart = source.indexOf("{", start);
- let depth = 0;
- for (let i = braceStart; i < source.length; i++) {
- if (source[i] === "{") depth++;
- else if (source[i] === "}") {
- depth--;
- if (depth === 0) return source.slice(braceStart, i + 1);
- }
- }
- throw new Error(`unbalanced braces reading body of "${fnSignature}"`);
-}
-
-describe("Auto picker entry", () => {
- it("heads both action lists without removing any explicit action", () => {
- const askList = source.slice(source.indexOf("const askActionButtons: AiActionButton[] = ["), source.indexOf("const agentActionButtons: AiActionButton[] = ["));
- const agentList = source.slice(source.indexOf("const agentActionButtons: AiActionButton[] = ["), source.indexOf("const actionButtons = computed"));
-
- for (const [label, list] of [
- ["ask", askList],
- ["agent", agentList],
- ] as const) {
- const autoIdx = list.indexOf("autoActionButton,");
- expect(autoIdx, `${label}: auto entry`).toBeGreaterThanOrEqual(0);
- expect(autoIdx, `${label}: auto must be first`).toBeLessThan(list.indexOf('action: "general"'));
- // The pre-existing actions are all still present.
- expect(list, `${label}: general`).toContain('action: "general"');
- expect(list, `${label}: generate`).toContain('action: "generate"');
- }
- expect(askList).toContain('action: "sampleData"');
- expect(askList).toContain('action: "convert"');
- expect(agentList).toContain('action: "executeAndExplain"');
- expect(agentList).toContain('action: "exploreSchema"');
- expect(agentList).toContain('action: "query"');
- });
-
- it("widens the picker type instead of the transport action union", () => {
- // The menu entry uses the UI-only `AiActionSelection`; `AiAction` (what the
- // request carries) stays a concrete action.
- const buttonInterface = bodyOf("interface AiActionButton {");
- expect(buttonInterface).toContain("action: AiActionSelection;");
- expect(buttonInterface).not.toContain("action: AiAction;");
- expect(source).toContain('import { classifyIntentByLlm, routeIntentByRules, type AiIntentRouteInput } from "@/lib/ai/aiIntentRouter";');
- expect(source).toContain("type AiActionSelection,");
- });
-
- it("keeps resolveDefaultAction concrete; auto preselection flows only through the settings toggle", () => {
- expect(source).toContain('const activeAction = ref<AiActionSelection>("general");');
- const resolveDefault = bodyOf("function resolveDefaultAction(mode: AiAssistantMode): AiAction");
- expect(resolveDefault).not.toContain("auto");
- expect(resolveDefault).toContain("defaultActionForMode(mode)");
-
- const resolveSelection = bodyOf("function resolveDefaultActionSelection(mode: AiAssistantMode): AiActionSelection");
- // Auto only when the Settings > AI toggle is on, and never for vector DBs:
- // their picker is hidden and the task contract must not invite querying.
- expect(resolveSelection).toContain("settings.defaultAutoRouting");
- expect(resolveSelection.indexOf('return "auto";')).toBeGreaterThanOrEqual(0);
- expect(resolveSelection.indexOf('return "auto";')).toBeLessThan(resolveSelection.indexOf("resolveDefaultAction(mode)"));
- expect(resolveSelection).toContain("isVectorDbType(boundConnection.value.db_type)");
- });
-
- it("lands new conversations, mode switches and mount init on the settings-driven default", () => {
- expect(bodyOf("function startNewChat()")).toContain("resolveDefaultActionSelection(mode);");
- expect(bodyOf("watch(assistantMode, (mode) => {")).toContain("resolveDefaultActionSelection(mode);");
- expect(bodyOf('function switchModeActionTab(mode: "ask" | "agent") {')).toContain("resolveDefaultActionSelection(mode);");
- // Mount init applies the default exactly once (apply-once rule shared with
- // the default mode). The picker is panel-scoped: no restore path
- // (`selectConversation`) writes it, so the settings-driven default survives
- // restoring the last conversation.
- expect(source).toContain("activeAction.value = resolveDefaultActionSelection(settings.defaultAiMode);");
- });
-
- it("hides the action list for vector databases and still forces generate there", () => {
- const listStart = source.indexOf("<!-- Action list -->");
- const pickerList = source.slice(listStart, source.indexOf("</PopoverContent>", listStart));
- expect(pickerList).toContain('v-for="button in actionButtons"');
- // The list (Auto included) only renders when the action picker is shown.
- const templateGuardIdx = source.lastIndexOf('<template v-if="showActionButtons">', listStart);
- expect(templateGuardIdx).toBeGreaterThanOrEqual(0);
-
- // Keyed by the conversation's bound connection, not the visible tab: the
- // hidden action must match whichever database this chat actually targets.
- const vectorWatchStart = source.indexOf("() => boundConnection.value?.db_type,");
- const vectorWatch = source.slice(vectorWatchStart, source.indexOf("{ immediate: true },", vectorWatchStart));
- expect(vectorWatch).toContain('activeAction.value = "generate";');
- });
-});
-
-describe("Auto routing at send time", () => {
- it("resolves the selection before the request reaches the backend", () => {
- const sendBody = bodyOf("async function send()");
- const routingIdx = sendBody.indexOf("await resolveAutoAction(");
- const streamIdx = sendBody.indexOf("await runAgentStream(");
- const contractIdx = sendBody.indexOf("action: requestedAction,");
- expect(routingIdx).toBeGreaterThanOrEqual(0);
- expect(streamIdx).toBeGreaterThan(routingIdx);
- expect(contractIdx).toBeGreaterThan(routingIdx);
- // Auto is only routed when it was actually selected; every explicit
- // selection is passed through untouched.
- expect(sendBody).toContain("requestedAction = requestedSelection;");
- // The send pipeline hands the router its frozen run target, so a background
- // send cannot route on the visible conversation's SQL or last error.
- expect(sendBody).toContain("requestedAction = await resolveAutoAction(text, requestedMode, runIsVisible(), tab);");
- // A confirmed-write turn replies with component copy, so the router must not
- // run on it: the mode default keeps the pre-Auto confirmation contract.
- expect(sendBody).toContain("const confirmationContinuation = allowWriteSqlForNextRun || resumingConfirmedWrite;");
- expect(sendBody).toContain("requestedAction = resolveDefaultAction(requestedMode);");
- // A stop/clear/switch that lands during the classifier wait must not start
- // a request nobody can reach.
- expect(sendBody.indexOf("if (!generationCanContinue()) {", routingIdx)).toBeGreaterThan(routingIdx);
- });
-
- it("records the routing outcome on the user message and shows the recognizing indicator", () => {
- const sendBody = bodyOf("async function send()");
- expect(sendBody).toContain('userMessage.routedFrom = "auto";');
- expect(sendBody).toContain("userMessage.routedAction = requestedAction;");
-
- const resolveBody = bodyOf("async function resolveAutoAction(text: string, mode: AiAssistantMode, showProgress: boolean, target: AiContextTarget = aiContextTarget.value): Promise<AiAction>");
- // Zero-latency rule layer first; the classifier (network) only on a miss.
- expect(resolveBody.indexOf("routeIntentByRules(input)")).toBeLessThan(resolveBody.indexOf("classifyIntentByLlm(input,"));
- expect(resolveBody).toContain("if (showProgress) routingInFlight.value = true;");
- expect(resolveBody).toContain("if (showProgress) routingInFlight.value = false;");
- expect(source).toContain("data-ai-auto-routing");
- expect(source).toContain('t("ai.routing.recognizing")');
- });
-
- it("renders the Auto chip on the routed message and switches back to the explicit action", () => {
- expect(source).toContain("data-ai-auto-routed-chip");
- expect(source).toContain('t("ai.routing.chip", { action: actionLabelFor(routedActionOf(msg)) })');
-
- const switchBody = bodyOf("function switchToRoutedAction(action: AiAction | null | undefined)");
- // Reuses the mode-switch suppression handshake so the watch cannot reset the
- // action right after the chip set it.
- expect(switchBody.indexOf("suppressModeActionReset = true;")).toBeLessThan(switchBody.indexOf('assistantMode.value = isValidActionForMode(action, "ask") ? "ask" : "agent";'));
- expect(switchBody.indexOf('assistantMode.value = isValidActionForMode(action, "ask") ? "ask" : "agent";')).toBeLessThan(switchBody.indexOf("activeAction.value = action;"));
- });
-
- it("clears the recognizing indicator on the abandon path, not just the classifier's finally", () => {
- // Dual-path rule for per-request transient state (see
- // AiAssistant.clearAndCancel.spec.ts): the classifier's `finally` covers the
- // normal path, so clearMessages()/selectConversation()/onUnmounted must drop
- // the flag synchronously via resetPendingRequestState().
- expect(bodyOf("function resetPendingRequestState()")).toContain("routingInFlight.value = false;");
- expect(bodyOf("async function resolveAutoAction(text: string, mode: AiAssistantMode, showProgress: boolean, target: AiContextTarget = aiContextTarget.value): Promise<AiAction>")).toContain("if (showProgress) routingInFlight.value = false;");
- });
-
- it("keeps external explicit triggers on the direct path", () => {
- const triggerBody = bodyOf("function triggerAction(action: AiAction, instruction?: string)");
- expect(triggerBody).toContain("activeAction.value = action;");
- expect(triggerBody).not.toContain("resolveAutoAction");
- expect(triggerBody).not.toContain("routeIntentByRules");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.chatTitle.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.chatTitle.spec.ts
deleted file mode 100644
index a54f01980e..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.chatTitle.spec.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Regression coverage for https://github.com/t8y2/dbx/issues/9904:
-//
-// Renaming the current conversation from the history list updates
-// `conversations` and the `renamedConversationTitles` claim map, but the
-// panel header rendered `chatTitle` purely from the first user message of
-// the panel-local `messages` snapshot, so the top-left title stayed stale
-// (reopening the conversation didn't pick the stored title up either).
-// AiAssistant.vue is a ~6000-line SFC the suite never mounts, so these
-// assertions pin the template/computed wiring as text, matching the house
-// source-assertion style.
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-function bodyOf(fnSignature: string): string {
- const start = source.indexOf(fnSignature);
- expect(start, `expected to find "${fnSignature}" in AiAssistant.vue`).toBeGreaterThanOrEqual(0);
- const braceStart = source.indexOf("{", start);
- let depth = 0;
- for (let i = braceStart; i < source.length; i++) {
- if (source[i] === "{") depth++;
- else if (source[i] === "}") {
- depth--;
- if (depth === 0) return source.slice(braceStart, i + 1);
- }
- }
- throw new Error(`unbalanced braces reading body of "${fnSignature}"`);
-}
-
-describe("AI assistant header title tracks the conversation title", () => {
- it("chatTitle prefers the renamed/stored title of the open conversation over the first-message excerpt", () => {
- // The claim map must stay reactive — it is the header's invalidation link
- // to a rename that commits while the save is still in flight.
- expect(source).toContain("const renamedConversationTitles = reactive(new Map<string, string>());");
- const body = bodyOf("const chatTitle = computed");
- // Both the rename-claim map and the conversation list must be reactive
- // dependencies so a commitRenameConversation() write re-renders the header.
- expect(body).toContain("renamedConversationTitles.get(conversationId.value)");
- expect(body).toContain("conversations.value.find(");
- expect(body).toContain("conversation.id === conversationId.value");
- expect(body).toContain("messages.value.find");
- // Same precedence as buildConversationSnapshot(): the rename claim wins,
- // the stored title comes next, and the first-message excerpt is only the
- // fallback for unsaved/new chats. (The toContain guards above keep these
- // index orderings from passing vacuously at -1.)
- expect(body.indexOf("renamedConversationTitles.get(conversationId.value)")).toBeLessThan(body.indexOf("activeConversation?.title"));
- expect(body.indexOf("renamedConversationTitles.get(conversationId.value)")).toBeLessThan(body.indexOf("messages.value.find"));
- expect(body).toContain("messageTitle(first).slice(0, 30)");
- expect(body).toContain('t("ai.newChat")');
- });
-
- it("the header renders chatTitle and rename commits feed the sources chatTitle reads", () => {
- expect(source).toContain("{{ chatTitle }}");
- const commit = bodyOf("async function commitRenameConversation(conv: AiConversation)");
- // The claim must be set before the async save (title race guard) and the
- // list entry replaced afterwards — both writes are what make the header
- // reactive to the rename.
- expect(commit).toContain("renamedConversationTitles.set(conv.id, title);");
- expect(commit.indexOf("renamedConversationTitles.set(conv.id, title);")).toBeLessThan(commit.indexOf("await saveAiConversation(updated)"));
- expect(commit).toContain("conversations.value[i] = updated;");
- // A failed save retracts the claim so the header, the history row and the
- // persisted record all keep the old title.
- expect(commit).toContain("renamedConversationTitles.delete(conv.id);");
- });
-
- it("pending-input recovery keeps a renamed title instead of re-deriving it from the first message", () => {
- // A recovered queued run used to persist `messageTitle(first)` outright,
- // overwriting a renamed title on disk (and, via syncPersistedConversation,
- // in the list the header now reads).
- const recovery = bodyOf("async function persistPendingInputRecovery(");
- expect(recovery).toContain("renamedConversationTitles.get(conversation.id)");
- expect(recovery.indexOf("renamedConversationTitles.get(conversation.id)")).toBeLessThan(recovery.indexOf("messageTitle(first)"));
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts
deleted file mode 100644
index 71bf9980c1..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts
+++ /dev/null
@@ -1,548 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Regression coverage for https://github.com/t8y2/dbx/issues/5941 and the follow-up
-// race identified on https://github.com/t8y2/dbx/pull/6332:
-//
-// When an in-flight AI request is stuck (e.g. a hung MCP tool call / slow provider
-// response), clicking the clear-chat trash icon, "New Chat", deleting the active
-// conversation, or switching to a different saved conversation must (a) cancel the
-// in-flight request so `isGenerating` doesn't stay stranded true forever, and (b)
-// isolate that in-flight request's async event callbacks / catch / finally from
-// whatever conversation is active by the time they run — even if the backend cancel
-// RPC itself is a no-op because the request hadn't registered a session id yet.
-//
-// (b) is what `AiGenerationGuard` (lib/ai/aiGenerationGuard.ts) exists for. Its own
-// spec and aiConversationLifecycle.spec.ts exercise the async ordering directly;
-// this file pins that AiAssistant.vue wires those tested lifecycle helpers into the
-// component paths that own the shared state.
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-function bodyOf(fnSignature: string): string {
- const start = source.indexOf(fnSignature);
- expect(start, `expected to find "${fnSignature}" in AiAssistant.vue`).toBeGreaterThanOrEqual(0);
- const braceStart = source.indexOf("{", start);
- let depth = 0;
- for (let i = braceStart; i < source.length; i++) {
- if (source[i] === "{") depth++;
- else if (source[i] === "}") {
- depth--;
- if (depth === 0) return source.slice(braceStart, i + 1);
- }
- }
- throw new Error(`unbalanced braces reading body of "${fnSignature}"`);
-}
-
-describe("AI assistant uses platform-specific conversation lifecycle", () => {
- it("abandonInFlightRequest() invalidates the generation guard before/regardless of the backend RPC", () => {
- const body = bodyOf("function abandonInFlightRequest(alreadyCancelledSessionId?: string)");
- expect(body).toContain("aiGenerationGuard.invalidate();");
- expect(body).toContain("isGenerating.value = false;");
- expect(body).toContain('currentSessionId.value = "";');
- // Invalidation (and resetting isGenerating/currentSessionId/delta buffers) must
- // happen unconditionally and before the best-effort backend RPC, so a send()
- // that hasn't registered a session id yet is still cut off from shared state.
- expect(body.indexOf("aiGenerationGuard.invalidate();")).toBeLessThan(body.indexOf("if (sessionId && sessionId !== alreadyCancelledSessionId) {"));
- });
-
- it("clearMessages() keeps Web cancellation while Desktop detaches the view", () => {
- const body = bodyOf("function clearMessages()");
- expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
- expect(body).toContain("if (isGenerating.value && backgroundAiRunsEnabled) void persistConversation();");
- // The abandon guard must run before the history is actually wiped, not after.
- expect(body.indexOf("!backgroundAiRunsEnabled) abandonInFlightRequest();")).toBeLessThan(body.indexOf("messages.value = []"));
- });
-
- it("selectConversation() cancels on Web and reattaches to a Desktop run", () => {
- const body = bodyOf("function selectConversation(conv: AiConversation)");
- expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
- expect(body).toContain("desktopAiRun<ChatMessage>(conv.id)");
- expect(body.indexOf("!backgroundAiRunsEnabled) abandonInFlightRequest();")).toBeLessThan(body.indexOf("conversationId.value = conv.id;"));
- });
-
- it("cancelStream() delegates live state readers to the tested stop lifecycle", () => {
- const body = bodyOf("async function cancelStream()");
- expect(body).toContain("await stopAiGenerationWithFallback({");
- expect(body).toContain("currentGeneration: () => aiGenerationGuard.peek()");
- expect(body).toContain("currentAssistantMessageIndex: () => currentAssistantMessageIndex");
- expect(body).toContain("abandon: (sessionId) => abandonInFlightRequest(sessionId)");
- expect(body).toContain("persistConversation,");
- });
-
- it("startNewChat() clears through the guarded path and performDeleteConversation() uses the tested delete lifecycle", () => {
- expect(bodyOf("function startNewChat()")).toContain("clearMessages();");
- const deleteBody = bodyOf("async function performDeleteConversation(id: string)");
- expect(deleteBody).toContain("await deleteConversationWithCancellation({");
- expect(deleteBody).toContain("abandon: () => abandonInFlightRequest()");
- expect(deleteBody).toContain("deletePersisted: () => deleteAiConversation(id).catch(() => {})");
- expect(deleteBody).toContain("if (conversationId.value === id) clearMessages();");
- });
-
- it("deleteConversation() asks for confirmation only when the conversation owns an active task", () => {
- // Parent PRD §4 line 70: deleting a conversation with a running/queued/
- // awaiting task must first ask; a conversation without an active task still
- // deletes directly.
- const deleteBody = bodyOf("async function deleteConversation(id: string)");
- expect(deleteBody).toContain("if (backgroundAiRunsEnabled && conversationHasActiveTask(id)) {");
- expect(deleteBody).toContain("deleteConfirmConversationId.value = id;");
- expect(deleteBody).toContain("await performDeleteConversation(id);");
- const taskBody = bodyOf("function conversationHasActiveTask(id: string)");
- expect(taskBody).toContain('status === "awaiting_write_confirmation"');
- expect(taskBody).toContain('status === "pending_recoverable"');
- });
-
- it("performDeleteConversation() marks desktop runs discardOnFinish so no async write can resurrect them", () => {
- // Reviewed finding (delete-resurrection, HIGH): a queued/running background
- // run's snapshot persists fired AFTER deleteAiConversation committed, so the
- // INSERT OR REPLACE recreated the just-deleted conversation. The delete path
- // must flag the run so every persist site skips it.
- const body = bodyOf("async function performDeleteConversation(id: string)");
- expect(body).toContain("run.discardOnFinish = true;");
- expect(body).toContain('if (run.status === "queued") cancelQueuedDesktopAiRun(run);');
- // The run is never finished here: the delete removes it from the registry
- // immediately and the bounded background cleanup owns finalization, so a
- // finished-but-still-slot-holding run can't wedge the queue.
- expect(body).not.toContain('finishDesktopAiRun(run, "cancelled");');
- expect(body).toContain("releaseDeletedRunSlot(run);");
- // The confirm path must cancel runs in ALL active statuses, including a
- // pending write confirmation and a recovered draft.
- expect(body).toContain('run.status === "awaiting_write_confirmation"');
- expect(body).toContain('run.status === "pending_recoverable"');
- });
-
- it("performDeleteConversation() launches bounded slot release so a deleted-but-hung run cannot wedge the queue", () => {
- // Reviewed finding (slot leak, HIGH): the delete path removed the run from
- // the registry immediately but never released its admittedRunIds slot when
- // the backend stream was hung — after DESKTOP_AI_CONCURRENCY_LIMIT such
- // deletes the global queue wedges permanently. The bounded release waits
- // for the pipeline's settled signal (or the force-abandon deadline) and
- // frees the slot; it also must not block the delete on the cancel RPC.
- const releaseBody = bodyOf("function releaseDeletedRunSlot(run: DesktopAiRunRuntime<ChatMessage>)");
- expect(releaseBody).toContain("if (!run.settled) return;");
- expect(releaseBody).toContain("waitForDesktopRunSettled(run)");
- expect(releaseBody).toContain("releaseDesktopAiRunSlot(run.runId)");
- expect(releaseBody).toContain("requestDesktopRunCancellation(run, deadlineAt, false)");
- const deleteBody = bodyOf("async function performDeleteConversation(id: string)");
- expect(deleteBody).not.toContain("await aiCancelStream(");
- });
-
- it("send() guards every snapshot persist behind discardOnFinish so a deleted conversation can't be resurrected", () => {
- const sendBody = bodyOf("async function send()");
- // All three send()-internal persist sites (queued persist, unslotted
- // early-return, and the pre-stream snapshot) must be guarded — previously
- // some persisted unconditionally.
- const guardedSites = sendBody.match(/if \(!detachedRun\.discardOnFinish\) void runSnapshotScheduler\.save\(detachedRun\);/g) ?? [];
- expect(guardedSites.length).toBe(3);
- // The finally must skip the run snapshot when the run was deleted, and the
- // Web-only conversation fallback must not fire for a deleted Desktop run.
- const finallyIdx = sendBody.indexOf("} finally {");
- const finallyBody = sendBody.slice(finallyIdx);
- expect(finallyBody).toContain("if (!detachedRun.discardOnFinish) {");
- expect(finallyBody).not.toContain("else void persistConversationSnapshot(");
- });
-
- it("send() tags a queued run's FIFO category so restart recovery can classify it", () => {
- const sendBody = bodyOf("async function send()");
- const queueIdx = sendBody.indexOf('if (detachedRun.status === "queued")');
- expect(queueIdx).toBeGreaterThanOrEqual(0);
- const queuedBlock = sendBody.slice(queueIdx);
- expect(queuedBlock).toContain('fifoCategory: resumingConfirmedWrite ? "write_confirmation_resume" : "normal_send"');
- expect(queuedBlock).toContain("pendingInput: resumingConfirmedWrite ? detachedRun.pendingInput : text");
- });
-
- it("send() discards a recovered pending-input run before starting a fresh one", () => {
- const sendBody = bodyOf("async function send()");
- const registerIdx = sendBody.indexOf("const resumableRun = desktopAiRun<ChatMessage>(runConversationId);");
- expect(registerIdx).toBeGreaterThanOrEqual(0);
- const registerBlock = sendBody.slice(registerIdx);
- expect(registerBlock).toContain('resumableRun?.status === "pending_recoverable"');
- expect(registerBlock).toContain("resumableRun.discardOnFinish = true;");
- expect(registerBlock).toContain("removeDesktopAiRun(resumableRun.conversationId);");
- });
-
- it("send() claims a generation id right after setting isGenerating and re-checks it after the first await", () => {
- const sendBody = bodyOf("async function send()");
- const claimIdx = sendBody.indexOf("const myGeneration = aiGenerationGuard.begin();");
- expect(claimIdx).toBeGreaterThanOrEqual(0);
- expect(sendBody.indexOf("isGenerating.value = true;")).toBeLessThan(claimIdx);
- // Must re-validate after the first await point (ensureLoaded()) before doing
- // anything that touches messages/mentions belonging to whatever conversation
- // is current by the time it resolves.
- const ensureLoadedAwaitIdx = sendBody.indexOf("await promptTemplateStore.ensureLoaded()");
- const recheckIdx = sendBody.indexOf("if (!generationCanContinue())", ensureLoadedAwaitIdx);
- expect(ensureLoadedAwaitIdx).toBeGreaterThan(claimIdx);
- expect(recheckIdx).toBeGreaterThan(ensureLoadedAwaitIdx);
- });
-
- it("send() clears the pending write-SQL grant when superseded before it's consumed", () => {
- // Reviewed on PR #6332: at this point in send(), the write-SQL grant
- // (allowWriteSqlForNextRun/confirmedWriteSqlText/...) hasn't been read/reset
- // yet — that happens later, right before runAgentStream(). A bare `return`
- // here would leave a previously-confirmed write grant sitting in the
- // module-scope vars, live to be replayed against whatever unrelated send()
- // the next conversation issues.
- const sendBody = bodyOf("async function send()");
- const ensureLoadedAwaitIdx = sendBody.indexOf("await promptTemplateStore.ensureLoaded()");
- const grantConsumedIdx = sendBody.indexOf("const allowWriteSql = requestedMode", ensureLoadedAwaitIdx);
- const recheckIdx = sendBody.indexOf("if (!generationCanContinue()) {", ensureLoadedAwaitIdx);
- expect(recheckIdx).toBeGreaterThan(ensureLoadedAwaitIdx);
- expect(recheckIdx).toBeLessThan(grantConsumedIdx);
- const recheckEnd = sendBody.indexOf("}", recheckIdx);
- const recheckBlock = sendBody.slice(recheckIdx, recheckEnd);
- expect(recheckBlock).toContain("clearPendingWriteGrant();");
- expect(recheckBlock).toContain("return;");
- });
-
- it("send()'s agent-event callback bails immediately if superseded", () => {
- const sendBody = bodyOf("async function send()");
- const callbackStart = sendBody.indexOf("(event: AgentEvent) => {");
- expect(callbackStart).toBeGreaterThanOrEqual(0);
- const guardIdx = sendBody.indexOf("if (!generationCanContinue()) return;", callbackStart);
- const pushIdx = sendBody.indexOf("agentEvents.push(event);", callbackStart);
- expect(guardIdx).toBeGreaterThan(callbackStart);
- expect(guardIdx).toBeLessThan(pushIdx);
- });
-
- it("send()'s catch block guards the assistant message lookup behind the generation check", () => {
- const sendBody = bodyOf("async function send()");
- const start = sendBody.indexOf("} catch (e: unknown) {");
- expect(start, 'expected to find a "} catch (e: unknown) {" block inside send()').toBeGreaterThanOrEqual(0);
- const end = sendBody.indexOf("} finally {", start);
- const catchBody = sendBody.slice(start, end);
- // Must not index messages.value[assistantIdx] unguarded — if clearMessages()/
- // selectConversation() already replaced the array (or invalidated the
- // generation) while this request was still in flight, an unguarded write would
- // either throw (silently eating the real error) or corrupt a different
- // conversation's transcript.
- expect(catchBody).not.toContain("messages.value[assistantIdx].content =");
- expect(catchBody).toContain("generationCanContinue()");
- expect(catchBody).toContain("const msg = runMessages[assistantIdx];");
- expect(catchBody).toContain("if (msg) {");
- expect(catchBody).toContain("msg.content =");
- // The failure flag rides along with the prefix text (#6467 PR3): the export
- // derives its failure marker from this state, not from the localized text.
- expect(catchBody).toContain("msg.failed = true;");
- });
-
- it("send()'s finally block only mutates shared state (isGenerating, currentSessionId) when still current", () => {
- const sendBody = bodyOf("async function send()");
- const start = sendBody.indexOf("} finally {");
- expect(start).toBeGreaterThanOrEqual(0);
- const finallyBody = sendBody.slice(start);
- const guardIdx = finallyBody.indexOf("if (detachedRun || aiGenerationGuard.isCurrent(myGeneration)) {");
- expect(guardIdx).toBeGreaterThanOrEqual(0);
- const isGeneratingIdx = finallyBody.indexOf("isGenerating.value = false;");
- const sessionResetIdx = finallyBody.indexOf('currentSessionId.value = "";');
- expect(isGeneratingIdx).toBeGreaterThan(guardIdx);
- expect(sessionResetIdx).toBeGreaterThan(guardIdx);
- // Issue #6743 feature 1 dual-path reset: the normal-completion path must stop
- // the 1s status timer and clear the generation-status ref inside the guarded
- // finally (the abandon path clears it via resetPendingRequestState()).
- expect(finallyBody.indexOf("stopStatusTimer();")).toBeGreaterThan(guardIdx);
- expect(finallyBody.indexOf("generationStatus.value = createGenerationStatus(Date.now());")).toBeGreaterThan(guardIdx);
- });
-
- it("the generation-status line exposes a screen-reader live region (role=status) that excludes ticking numerals", () => {
- // Issue #6743 feature 1 a11y: async execution-state updates must be
- // announced. The status block (data-ai-generation-status) must contain a
- // role="status" live region fed by `statusLiveAnnouncement` — which, unlike
- // the visible `statusText`, omits the per-second elapsed/idle numerals so a
- // screen reader hears discrete state changes, not a timer ticking every 1s.
- const statusBlockStart = source.indexOf("data-ai-generation-status");
- expect(statusBlockStart).toBeGreaterThanOrEqual(0);
- const block = source.slice(statusBlockStart);
- expect(block).toContain('role="status"');
- expect(block).toContain('aria-live="polite"');
- expect(block).toContain('aria-atomic="true"');
- expect(block).toContain("statusLiveAnnouncement");
- expect(block).toContain('class="sr-only"');
- });
-
- it("the generation-status line hides once the generation is finished (agent_end) even before isGenerating clears", () => {
- // Issue #6743 fix: agent_end/error arrive via the event callback before
- // runAgentStream()'s promise resolves (CLI teardown / SSE close can take
- // seconds), so the status line must ALSO be gated on phase !== 'finished' —
- // otherwise it lingers below the completed reply showing a reset "0s".
- const statusLineIdx = source.indexOf("data-ai-generation-status");
- expect(statusLineIdx).toBeGreaterThanOrEqual(0);
- const lineStart = source.lastIndexOf("\n", statusLineIdx) + 1;
- const lineEnd = source.indexOf("\n", statusLineIdx);
- const openingTag = source.slice(lineStart, lineEnd);
- expect(openingTag).toContain("generationStatus.phase !== 'finished'");
- expect(openingTag).toContain("data-ai-generation-status");
- });
-
- it("the >60s long-running hint is hidden once the generation is finished", () => {
- // Fix keeps startedAt on the finished phase, so the hint must not reappear
- // under a completed reply during the isGenerating-still-true gap.
- const idx = source.indexOf("const statusLongRunningHintVisible");
- expect(idx).toBeGreaterThanOrEqual(0);
- const line = source.slice(idx, source.indexOf("\n", idx));
- expect(line).toContain('"finished"');
- });
-
- // The three gaps below were called out on review of PR #6332: the generation guard
- // stopped *writes* from a superseded generation, but didn't stop the generation from
- // starting a stream, leaking pending-compaction state, or from surviving unmount.
- it("send() rechecks the generation after EACH context-preparation await, before ever starting the stream", () => {
- const sendBody = bodyOf("async function send()");
- const sqlFilesIdx = sendBody.indexOf("await loadReferencedSqlFiles(");
- const firstRecheckIdx = sendBody.indexOf("if (!generationCanContinue()) return;", sqlFilesIdx);
- const contextIdx = sendBody.indexOf("const context = await buildAiContext(");
- const secondRecheckIdx = sendBody.indexOf("if (!generationCanContinue()) return;", contextIdx);
- const runIdx = sendBody.indexOf("await runAgentStream(", contextIdx);
- // A clear/switch/unmount firing during EITHER await invalidates the generation
- // but doesn't touch the backend (no session registered yet) — without a
- // recheck immediately after each one, send() would resume into further wasted
- // work (buildAiContext() can do real backend/schema work) and eventually call
- // runAgentStream() anyway, starting a request nobody can reach anymore.
- expect(sqlFilesIdx).toBeGreaterThanOrEqual(0);
- expect(firstRecheckIdx).toBeGreaterThan(sqlFilesIdx);
- expect(firstRecheckIdx).toBeLessThan(contextIdx);
- expect(secondRecheckIdx).toBeGreaterThan(contextIdx);
- expect(runIdx).toBeGreaterThan(secondRecheckIdx);
- });
-
- it("send() tracks the current assistant message index alongside currentSessionId, for cancelStream() to finalize", () => {
- // cancelStream()'s forced-abandon path needs to know which message in
- // messages.value belongs to this generation so it can finalize it (see the
- // "finalizes the stuck placeholder message" test above). Must be set at the
- // same point currentSessionId is, and cleared alongside it too.
- const sendBody = bodyOf("async function send()");
- const pushIdx = sendBody.indexOf('runMessages.push({ role: "assistant"');
- const assistantIdxIdx = sendBody.indexOf("const assistantIdx = runMessages.length - 1;", pushIdx);
- const trackIdx = sendBody.indexOf("currentAssistantMessageIndex = assistantIdx;", assistantIdxIdx);
- const sessionSetIdx = sendBody.indexOf("currentSessionId.value = sessionId;", trackIdx);
- expect(pushIdx).toBeGreaterThanOrEqual(0);
- expect(assistantIdxIdx).toBeGreaterThan(pushIdx);
- expect(trackIdx).toBeGreaterThan(assistantIdxIdx);
- expect(sessionSetIdx).toBeGreaterThan(trackIdx);
-
- const start = sendBody.indexOf("} finally {");
- const finallyBody = sendBody.slice(start);
- const sessionResetIdx = finallyBody.indexOf('currentSessionId.value = "";');
- const indexResetIdx = finallyBody.indexOf("currentAssistantMessageIndex = -1;");
- expect(sessionResetIdx).toBeGreaterThanOrEqual(0);
- expect(indexResetIdx).toBeGreaterThan(sessionResetIdx);
- });
-
- it("abandonInFlightRequest() skips the cancel RPC for a session the caller already cancelled", () => {
- // Reviewed on PR #6332 (efficiency): cancelStream() awaits aiCancelStream()
- // itself before deciding to force-abandon, so re-firing it unconditionally
- // here would double-RPC the same session. Must still fire for a session
- // registered AFTER the caller's own RPC attempt (i.e. not simply skipped
- // whenever a caller happened to pass an argument).
- const body = bodyOf("function abandonInFlightRequest(alreadyCancelledSessionId?: string)");
- expect(body).toContain("if (sessionId && sessionId !== alreadyCancelledSessionId) {");
- expect(body).not.toContain("if (sessionId) {\n aiCancelStream(sessionId).catch(() => {});\n }");
- });
-
- it("resetPendingRequestState() resets all per-request transient state, and abandonInFlightRequest() uses it", () => {
- // Reviewed on PR #6332: this reset logic used to be duplicated inline across
- // send()'s finally, abandonInFlightRequest(), and flushAssistantDeltas() —
- // duplication that already let the pendingCompaction reset get missed once.
- // Consolidating it into one function means a newly-added piece of per-request
- // state only needs to be added here to be covered by the abandon path.
- const resetBody = bodyOf("function resetPendingRequestState()");
- expect(resetBody).toContain("cancelAnimationFrame(assistantDeltaFrame);");
- expect(resetBody).toContain("assistantDeltaFrame = null;");
- expect(resetBody).toContain('pendingAssistantDelta = "";');
- expect(resetBody).toContain('pendingAssistantReasoning = "";');
- expect(resetBody).toContain("pendingAssistantIndex = -1;");
- // A context_compacted event on the abandoned generation may have already set
- // pendingCompaction before invalidation took effect. It's request-owned, not
- // conversation-owned, so it must be reset here — otherwise the next send() (in
- // a brand-new, just-cleared conversation) would splice the OLD conversation's
- // compaction summary into the NEW conversation's transcript in its finally
- // block.
- expect(resetBody).toContain("pendingCompaction.value = null;");
- // Issue #6743 feature 1: the live generation-status line is per-request
- // transient state too — the 1s status timer and the status ref must be reset
- // here, otherwise switching conversations leaks a stale status line (and a
- // running interval) into the next generation.
- expect(resetBody).toContain("stopStatusTimer();");
- expect(resetBody).toContain("generationStatus.value = createGenerationStatus(Date.now());");
-
- const abandonBody = bodyOf("function abandonInFlightRequest(alreadyCancelledSessionId?: string)");
- expect(abandonBody).toContain("resetPendingRequestState();");
- });
-
- it("onUnmounted() invalidates the generation instead of only firing the best-effort cancel RPC", () => {
- const body = bodyOf("onUnmounted(() => {");
- // Plain cancelStream() leaves the generation current: a request still mid-await
- // when the component unmounts would resume, call runAgentStream(), and its event
- // callback/catch/finally would keep writing into refs this now-unmounted
- // instance's closures still hold. Must go through the same invalidating path as
- // clearMessages()/selectConversation().
- expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
- expect(body).not.toContain("cancelStream();");
- });
-
- it("queues simultaneous background auto-sends instead of overwriting a single pending target", () => {
- // Several detached runs can settle in the same turn. A single mutable
- // `pendingAutoSend` slot lost whichever queued input was scheduled first.
- expect(source).toContain("const pendingAutoSends: PendingAutoSend[] = [];");
- const sendBody = bodyOf("async function send()");
- expect(sendBody).toContain("const auto = pendingAutoSends.shift() ?? null;");
- const scheduleBody = bodyOf("function scheduleAutoSend(");
- expect(scheduleBody).toContain("pendingAutoSends.push(");
- });
-
- it("makes successfully persisted background conversations navigable without reopening the list", () => {
- const snapshotBody = bodyOf("async function persistDesktopRunSnapshot(");
- expect(snapshotBody).toContain(".then(() => syncPersistedConversation(conversation))");
- const syncBody = bodyOf("function syncPersistedConversation(conversation: AiConversation)");
- expect(syncBody).toContain("conversations.value.unshift(conversation);");
- expect(syncBody).toContain("conversations.value.sort(");
- });
-
- it("reorders recovered conversations before restoring the most recent one", () => {
- const recoveryBody = bodyOf("async function persistPendingInputRecovery(");
- expect(recoveryBody).toContain(".then(() => syncPersistedConversation(snapshot))");
- const mountedBody = bodyOf("onMounted(async () => {");
- expect(mountedBody.indexOf("initialConversationStateLoaded = true;")).toBeLessThan(mountedBody.indexOf("restoreInitialConversation();"));
- });
-
- it("does not replace an in-memory desktop run when the AI panel remounts", () => {
- const mountedBody = bodyOf("onMounted(async () => {");
- expect(mountedBody).toContain("const liveRun = desktopAiRun<ChatMessage>(persistedRun.conversationId);");
- expect(mountedBody).toContain("if (liveRun) {");
- expect(mountedBody).toContain("continue;");
- });
-
- it("agent step cards render a running-tool tail and a computed duration tail", () => {
- // Issue #6743 (feature-1 gap): per-tool execution time in the agent step cards —
- // mockup shows a spinner + "执行中…" tail on running steps and `0.8s`/`1.2s` on
- // completed steps. The step-row template must special-case running tool steps
- // (spinner icon + executing tail) and completed tool steps (tabular duration).
- const stepsStart = source.indexOf('v-for="step in msg.agentSteps"');
- expect(stepsStart, "expected to find the agent-steps v-for in AiAssistant.vue").toBeGreaterThanOrEqual(0);
- const stepsBlock = source.slice(stepsStart);
- // Running tool step: spinner leading icon + right-aligned "executing…" tail.
- expect(stepsBlock).toContain("step.tone === 'active' && step.toolName");
- expect(stepsBlock).toContain('t("ai.agentSteps.executing")');
- // Completed tool step: right-aligned tabular duration tail.
- expect(stepsBlock).toContain("formatToolDurationMs(step.durationMs)");
- });
-
- it("the status-line idle branch swaps Clock for Hourglass (mockup alignment)", () => {
- // Mockup: idle state shows a non-spinning hourglass (spinner animation stops);
- // only the >60s hint below keeps the Clock. The swap must live in the status
- // line's spinner/clock slot, not touch the hint.
- const statusLineIdx = source.indexOf("data-ai-generation-status");
- expect(statusLineIdx).toBeGreaterThanOrEqual(0);
- const statusBlock = source.slice(statusLineIdx);
- expect(statusBlock).toContain("<Hourglass v-else");
- });
-
- // --- Review findings on background AI session tasks (see the two findings
- // evaluated in this session) ---
-
- it("persists detached streaming snapshots incrementally from the delta flush path", () => {
- // Finding 1: detached deltas were flushed only into memory (plus a scroll
- // callback), so a crash/quit mid-response lost everything after the
- // pre-stream snapshot. The flush path must now schedule throttled,
- // serialized snapshot persistence.
- const sendBody = bodyOf("async function send()");
- const bufferIdx = sendBody.indexOf("createDetachedAssistantDeltaBuffer(runMessages, () => {");
- expect(bufferIdx).toBeGreaterThanOrEqual(0);
- const flushBlock = sendBody.slice(bufferIdx, sendBody.indexOf(": undefined", bufferIdx));
- expect(flushBlock).toContain("runSnapshotScheduler.schedule(detachedRun);");
- // The pre-stream snapshot and the finally go through the same serialized
- // scheduler so a slow write can never reorder around them.
- expect(sendBody).toContain("void runSnapshotScheduler.save(detachedRun)");
- // The scheduler itself lives at module scope (the flush callback and the
- // stop path both use it), configured with the streaming interval.
- expect(source).toContain("const runSnapshotScheduler = createDesktopAiRunSnapshotScheduler<ChatMessage>({");
- expect(source).toContain("intervalMs: RUN_SNAPSHOT_PERSIST_INTERVAL_MS");
- });
-
- it("send() resolves the run's settled signal on every exit path so a stop can wait for the real terminal event", () => {
- // Finding 2: the stop path must not finalize the run itself; it waits for
- // the pipeline's terminal event via the run's `settled` promise. Every
- // exit path of send() must resolve it (finally + three pre-stream early
- // returns), or a stop fired there would sit out the full timeout.
- const sendBody = bodyOf("async function send()");
- expect(sendBody).toContain("detachedRun.settled = new Promise<void>((resolve) => {");
- const finallyIdx = sendBody.indexOf("} finally {");
- const finallyBody = sendBody.slice(finallyIdx);
- expect(finallyBody).toContain("resolveDetachedRunSettled();");
- const settledCalls = sendBody.match(/resolveDetachedRunSettled\(\);/g) ?? [];
- expect(settledCalls.length).toBeGreaterThanOrEqual(4);
- });
-
- it("the finally skips finalization for a run that no longer owns its registry slot", () => {
- // Finding 2: after a stop-side force-abandon (or a delete/replacement send)
- // retires the run, the old pipeline's finally must not re-run the finish
- // chain - updateDesktopAiRun() re-inserts unconditionally, which would
- // resurrect the retired run over whatever now owns the conversation.
- const sendBody = bodyOf("async function send()");
- const finallyIdx = sendBody.indexOf("} finally {");
- const finallyBody = sendBody.slice(finallyIdx);
- expect(finallyBody).toContain("const runStillOwned = detachedRun ? desktopAiRun(detachedRun.conversationId) === detachedRun : false;");
- expect(finallyBody).toContain("if (detachedRun && runStillOwned) {");
- expect(finallyBody).toContain("runSnapshotScheduler.cancel(detachedRun.runId);");
- expect(finallyBody).toContain("void runSnapshotScheduler.save(detachedRun).finally(");
- expect(finallyBody).toContain("} else if (!detachedRun) {");
- });
-
- it("stopDesktopAiRun keeps a background run active until the pipeline settles, force-abandoning after the timeout", () => {
- // Finding 2: the old stop path finished+retired immediately, so a hung or
- // cancellation-pending stream went invisible while still occupying its slot.
- // The shared helper must reflect the request but defer finalization to the
- // pipeline's finally or the bounded force-abandon.
- const body = bodyOf("async function stopDesktopAiRun(");
- expect(body).toContain("run.cancelRequested = true;");
- expect(body).toContain("waitForDesktopRunSettled(run)");
- expect(body).toContain("requestDesktopRunCancellation(run, deadlineAt)");
- expect(body).toContain("await forceAbandonDesktopAiRun(run);");
- // Only the never-admitted queued branch finalizes immediately.
- expect(body).toContain('if (run.status === "queued")');
- expect(body).toContain("cancelQueuedDesktopAiRun(run);");
- });
-
- it("the stop path consumes the aiCancelStream acknowledgement and retries while unacknowledged", () => {
- // Finding 2: aiCancelStream() returns a boolean (true only when the session
- // id is registered with the backend) that was discarded. The retry loop
- // lands the cancellation once the session registers during context
- // preparation.
- const body = bodyOf("async function requestDesktopRunCancellation(");
- expect(body).toContain("const acknowledged = await aiCancelStream(run.currentSessionId).catch(() => false);");
- expect(body).toContain("if (acknowledged) return;");
- expect(body).toContain("DESKTOP_CANCEL_ACK_RETRY_MS");
- });
-
- it("stopDesktopAiRun fire-and-forgets the cancel retry so a hung IPC cannot block the bounded force-abandon", () => {
- // Reviewed finding (deadlock, HIGH): stopDesktopAiRun() awaited
- // requestDesktopRunCancellation(), which awaits aiCancelStream() directly.
- // If the IPC never returned, the STOP_FORCE_ABANDON_MS race was never read
- // and the stop never force-abandoned — a hung cancel RPC stranded the run
- // exactly like the hung stream it was meant to recover from.
- const body = bodyOf("async function stopDesktopAiRun(");
- expect(body).toContain("void requestDesktopRunCancellation(run, deadlineAt);");
- expect(body).not.toContain("await requestDesktopRunCancellation(run, deadlineAt);");
- // The bounded settle race drives the force-abandon, not the cancel RPC.
- expect(body).toContain("if (await settled) {");
- });
-
- it("both stop entry points delegate to the shared stopDesktopAiRun helper", () => {
- const cancelBody = bodyOf("async function cancelStream()");
- expect(cancelBody).toContain("await stopDesktopAiRun(run);");
- expect(cancelBody).not.toContain('finishDesktopAiRun(run, "cancelled")');
- const rowBody = bodyOf("async function stopConversationRun(");
- expect(rowBody).toContain("await stopDesktopAiRun(run);");
- });
-
- it("keeps long task summaries out of the fixed-width history popover", () => {
- // The history popover is always w-72, but min-[430px] responds to viewport
- // width. On desktop it displayed long summaries inside the compact row,
- // squeezing the conversation title and forcing horizontal scrolling. The
- // status icon still exposes the full text through its title/ARIA metadata.
- const historyStart = source.indexOf('<PopoverContent align="end" class="w-72 gap-0 p-0"');
- const history = source.slice(historyStart);
- expect(history).toContain(":title=\"conversationRowDetail(conv).summary ?? t('ai.runStatusCompleted')\"");
- expect(history).toContain(":title=\"conversationRowDetail(conv).reason ?? t(conversationRowDetail(conv).status === 'interrupted' ? 'ai.runStatusInterrupted' : 'ai.runStatusFailed')\"");
- expect(history).not.toContain("conversationRowDetail(conv).summary }}</span>");
- expect(history).not.toContain("conversationRowDetail(conv).reason }}</span>");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
index c23abd8af5..ee48180b1f 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
@@ -9,9 +9,9 @@ import { describe, expect, it } from "vitest";
// connection back onto that tab — so every conversation shared one connection
// and the composer's database selection leaked between chats.
//
-// AiAssistant.vue is a ~6000-line SFC the suite never mounts, so these
-// assertions pin the wiring as text, matching the house source-assertion style
-// used by AiAssistant.chatTitle.spec.ts. The binding *rules* themselves are
+// AiAssistant.vue is a ~6000-line SFC the suite never mounts, so the checks
+// that keep AI writes and runs on the bound connection pin the wiring as text
+// until they have mounted coverage. The binding *rules* themselves are
// unit-tested in lib/ai/__tests__/aiConversationBinding.spec.ts.
const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
@@ -45,25 +45,6 @@ describe("AI conversation owns its connection binding (#9902)", () => {
expect(body).toContain("rebindConversation(");
});
- it("persists a rebind onto the conversation record", () => {
- const body = bodyOf("async function rebindConversation(");
-
- expect(body).toContain("connectionId: connection.id");
- expect(body).toContain("saveAiConversation(updated)");
- // A chat that has no record yet stages the choice until its first snapshot.
- expect(body).toContain("draftBinding.value =");
- });
-
- it("resets the composer's database selection when the conversation changes", () => {
- // The key must include the conversation id: `selectedDatabases` is one ref
- // for the whole panel, so a key without it kept the previous chat's
- // database selected — the "bound database is not isolated" report.
- const watcherStart = source.indexOf("watch(\n () => `${boundConnectionId.value}");
- expect(watcherStart).toBeGreaterThanOrEqual(0);
- const watcher = source.slice(watcherStart, source.indexOf(");", watcherStart));
- expect(watcher).toContain("conversationId.value");
- });
-
it("sends against the bound connection, not the visible tab", () => {
const body = bodyOf("async function send()");
@@ -82,55 +63,6 @@ describe("AI conversation owns its connection binding (#9902)", () => {
expect(source).toContain("const productionContext = computed(() => productionContextOf(activeRunBinding.value));");
});
- it("clears a staged draft binding when the shown chat changes", () => {
- expect(bodyOf("function selectConversation(conv: AiConversation)")).toContain("draftBinding.value = null;");
- expect(bodyOf("function clearMessages()")).toContain("draftBinding.value = null;");
- });
-
- it("shows the composer's connection and schema selectors from the binding", () => {
- expect(source).toContain(':model-value="boundConnectionId"');
- expect(source).toContain(":model-value=\"boundSchema || ''\"");
- expect(source).not.toContain(":model-value=\"connection?.id || ''\"");
- });
-
- it("labels each history row with the connection it is bound to", () => {
- // Which database a conversation talks to has to be readable without opening
- // it — the binding is per conversation, and several can be live at once.
- expect(source).toContain("{{ conv.connectionName }}");
- expect(source).toContain("conversationRowDetail(conv).connectionMissing");
- expect(bodyOf("function conversationRowDetail(conv: AiConversation)")).toContain("connectionMissing: !!conv.connectionId && !connectionStore.getConfig(conv.connectionId)");
- });
-
- it("retargets the conversation on a cross-connection table drop too", () => {
- // Reverses the old "reject a foreign table" contract: with the conversation
- // owning its binding, the drop can retarget it instead of being discarded.
- const start = source.indexOf("function onTableReferenceDropEvent");
- const body = source.slice(start, source.indexOf("\n}", start));
-
- expect(body).toContain("void bindConversation({ connectionId: payload.connectionId, database: payload.database, schema: payload.schema })");
- expect(body).toContain("addSelectedMention(");
- expect(body).not.toContain("context:");
- });
-
- it("retargets the conversation when a table is picked from another connection", () => {
- // Sliced between anchors rather than via bodyOf(): the parameter's
- // `{ schema?: string; table: string }` annotation is the first "{" after the
- // signature, so bodyOf would return the type, not the function body.
- const start = source.indexOf("function addTableMention(");
- const body = source.slice(start, source.indexOf("function clearContextReferences", start));
-
- expect(body).toContain("void bindConversation(binding)");
- expect(body).toContain("addSelectedMention(");
-
- const apply = bodyOf("async function bindConversation(binding: AiConversationBinding)");
- // The previous target's mentions and schema options no longer apply...
- expect(apply).toContain("clearContextReferences();");
- // ...and the new target goes onto the conversation, never the editor.
- expect(apply).toContain("rebindConversation(connection, binding.database, binding.schema)");
- expect(apply).not.toContain("queryStore.");
- expect(apply).not.toContain("activeConnectionId");
- });
-
it("freezes the binding for a background auto-send instead of reading the visible one", () => {
// An auto-send for conversation A runs while B may be on screen, so it must
// carry its own binding: reading the live one would target B's database.
@@ -172,14 +104,6 @@ describe("AI conversation owns its connection binding (#9902)", () => {
}
});
- it("compares the whole namespace when deciding whether to retarget", () => {
- // Comparing only the connection id would treat db1 -> db2 on one server as
- // "no change" and skip the rebind.
- const body = bodyOf("async function bindConversation(binding: AiConversationBinding)");
- expect(body).toContain("sameConversationBinding(binding, conversationBinding.value)");
- expect(body).not.toContain("binding.connectionId === boundConnectionId.value");
- });
-
it("judges production write protection and routing against the run's frozen binding", () => {
// A run's target is frozen at send time, so a rebind mid-run (or while the
// confirmation card is up) must not move the production verdict or the
@@ -219,29 +143,6 @@ describe("AI conversation owns its connection binding (#9902)", () => {
expect(body).toContain("confirmationBindingForNextRun = runBinding;");
});
- it("keeps the snapshot's connection name and id on the same source", () => {
- // Taking the name from the caller (a run, so connection A) while the id comes
- // from the conversation record (B after a mid-run rebind) would save a
- // record that displays A but targets B.
- const body = bodyOf("function buildConversationSnapshot(");
- expect(body).toContain("connectionName: binding.connectionId ? (connectionStore.getConfig(binding.connectionId)?.name ?? connectionName) : connectionName,");
- expect(body).toContain("connectionId: binding.connectionId,");
- // The caller-supplied name is only a fallback now, never stored bare next to
- // an id taken from a different source.
- expect(body).toContain(": connectionName," + String.fromCharCode(10));
- });
-
- it("uses a run's frozen target for the first desktop snapshot", () => {
- const persist = bodyOf("async function persistDesktopRunSnapshot(run: DesktopAiRunRuntime<ChatMessage>)");
- expect(persist).toContain("{ connectionId: run.connectionId, database: run.database, schema: run.schema }");
- const snapshot = bodyOf("function buildConversationSnapshot(");
- expect(snapshot).toContain("snapshotBinding(targetConversationId, fallbackBinding)");
- expect(snapshot).toContain("schema: binding.schema");
- // Leaving the new chat also invokes this ordinary save path before the
- // run's scheduled snapshot; it must use the active run's target too.
- expect(bodyOf("async function persistConversation()")).toContain("const binding = activeRunBinding.value;");
- });
-
it("persists the assistant turn's target for Web confirmation after remount", () => {
expect(source).toContain("sourceBinding: runBinding");
expect(bodyOf("function buildConversationSnapshot(")).toContain("sourceBinding: m.sourceBinding");
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationExport.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationExport.spec.ts
deleted file mode 100644
index b32121c70b..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationExport.spec.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-describe("AI assistant conversation export", () => {
- it("passes native save-dialog short extensions, never the bare format key", () => {
- expect(source).toContain('saveTextFile(result.content, result.defaultFileName, format === "markdown" ? "Markdown" : "HTML", format === "markdown" ? "md" : "html")');
- expect(source).not.toMatch(/saveTextFile\([^)]*,\s*format\)/);
- });
-
- it("records the failure on the message state at the same point the prefix text is written", () => {
- expect(source).toContain("msg.failed = true;");
- });
-
- it("persists the failed flag through both conversation snapshot paths", () => {
- // buildConversationSnapshot and persistPendingInputRecovery both whitelist
- // fields on the way to storage; serde drops unknown fields on the Rust
- // side, so a path that forgets `failed` silently loses the marker.
- expect(source).toContain("...(m.failed ? { failed: true } : {})");
- expect(source).toContain("failed: m.failed === true ? true : undefined");
- });
-
- it("derives the export failure marker from persisted state and run status, not locale text", () => {
- expect(source).toContain("failed: msg.failed === true || (runFailed && msg === failedTurnAssistant)");
- expect(source).not.toContain('msg.content.startsWith(t("ai.requestFailed"))');
- });
-
- it("attributes run-status failure only to an assistant reply after the latest user turn", () => {
- // Restart-before-first-delta regression: when a run is restored as
- // interrupted before producing any output, the last reply in the transcript
- // belongs to the PRECEDING successful turn — it must stay unmarked.
- expect(source).toContain("let lastUserIndex = -1;");
- expect(source).toContain("i > lastUserIndex");
- expect(source).toContain("failedTurnAssistant = candidate;");
- expect(source).not.toContain("lastVisibleAssistant");
- });
-
- it("consults the run registry / fallback status map for background-failed turns", () => {
- expect(source).toContain("function isCurrentRunFailed()");
- expect(source).toContain('return status === "failed" || status === "interrupted";');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.messageWrap.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.messageWrap.spec.ts
deleted file mode 100644
index fce498305a..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.messageWrap.spec.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-describe("AI assistant message wrapping", () => {
- it("allows long unbroken user text such as comma-separated SQL arrays to wrap", () => {
- expect(source).toContain('data-ai-user-message-content class="whitespace-pre-wrap">{{ msg.content }}</div>');
- expect(source).toContain(".ai-message-scroll :deep([data-ai-user-message-content])");
- expect(source).toContain("overflow-wrap: anywhere;");
- });
-
- it("allows long unbroken fenced code to wrap inside the message bubble", () => {
- expect(source).toContain('class="ai-code-block whitespace-pre-wrap break-words [overflow-wrap:anywhere]');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.scrollRing.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.scrollRing.spec.ts
deleted file mode 100644
index 485a4ded05..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.scrollRing.spec.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Regression coverage for the AI status ring on the scroll-to-bottom button:
-//
-// While a run is active for the visible conversation (`isGenerating`), the
-// scroll-to-bottom button must stay visible even when the user is already at
-// the bottom, and must render a decorative rotating arc ring (an "assistant is
-// working" marker, Si-Octo-style). The ring is aria-hidden decoration driven
-// purely by `isGenerating` — the scroll-driven hysteresis (`showScrollToBottom`
-// + the MESSAGE_SCROLL_BUTTON_* thresholds) must stay the single source of the
-// scroll path, and clicking must still force-scroll to the bottom.
-//
-// AiAssistant.vue is a ~6000-line SFC the suite never mounts (see
-// .trellis/spec/app-tests/frontend/component-guidelines.md): these assertions
-// pin the template wiring as text, matching the house source-assertion style.
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-const buttonMatch = source.match(/<button[^>]*v-if="showScrollToBottom \|\| isGenerating"[\s\S]*?<\/button>/);
-
-function buttonEl(): string {
- if (!buttonMatch) {
- throw new Error('scroll-to-bottom button gated on "showScrollToBottom || isGenerating" not found in AiAssistant.vue');
- }
- return buttonMatch[0];
-}
-
-describe("AI assistant scroll-to-bottom button status ring", () => {
- it("keeps the button visible while a run is active, not only when scrolled away", () => {
- expect(buttonEl()).toContain('v-if="showScrollToBottom || isGenerating"');
- });
-
- it("renders the decorative rotating arc ring only while generating", () => {
- const button = buttonEl();
- const ring = button.match(/<svg[\s\S]*?<\/svg>/);
- if (!ring) throw new Error("expected the inline status-ring <svg> inside the scroll-to-bottom button");
- const ringEl = ring[0];
- expect(ringEl).toContain('v-if="isGenerating"');
- // Decorative: flagged for tests/e2e, excluded from the accessibility tree.
- expect(ringEl).toContain("data-ai-scroll-ring");
- expect(ringEl).toContain('aria-hidden="true"');
- // House spinner idiom + the firm prefers-reduced-motion opt-out convention.
- expect(ringEl).toContain("animate-spin");
- expect(ringEl).toContain("motion-reduce:animate-none");
- // Semantic token color — theme/dark-mode support comes free via currentColor.
- expect(ringEl).toContain("text-primary");
- // The ring must never swallow clicks, and fill="none" keeps the open arc
- // from rendering as a filled pie slice.
- expect(ringEl).toContain("pointer-events-none");
- expect(ringEl).toContain('fill="none"');
- // Open ~288° arc (statement-gutter spinner geometry scaled to the 32-unit
- // ring box), round-capped like every other arc/spinner in the repo.
- expect(ringEl).toContain("M29 16a13 13 0 1 1-8.98-12.36");
- expect(ringEl).toContain('stroke-linecap="round"');
- });
-
- it("keeps the force scroll-to-bottom behavior and the arrow icon intact", () => {
- const button = buttonEl();
- expect(button).toContain("scrollToBottom({ force: true })");
- expect(button).toContain("<ArrowDown");
- expect(button).toContain('t("ai.scrollToBottom")');
- });
-
- it("leaves the scroll hysteresis thresholds untouched", () => {
- // Visibility is an OR over the existing state machine; the thresholds must
- // remain the single source of the scroll-driven path (show 120 > hide 48).
- expect(source).toContain("MESSAGE_SCROLL_BUTTON_SHOW_THRESHOLD_PX = 120;");
- expect(source).toContain("MESSAGE_SCROLL_BUTTON_HIDE_THRESHOLD_PX = 48;");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.templateDefaults.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.templateDefaults.spec.ts
deleted file mode 100644
index 322406eb27..0000000000
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.templateDefaults.spec.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Regression coverage for https://github.com/t8y2/dbx/issues/7649: per-db_type
-// prompt template defaults + last-used fallback. The resolution rules live in
-// lib/ai/promptTemplateDefaults.ts (unit-tested separately); this file pins
-// that AiAssistant.vue wires them into the panel lifecycle:
-// - auto-apply once when the AI selection + templates are loaded,
-// - re-resolve on connection/database/schema switch (defaults only opt-in),
-// - record what was actually sent as the db_type's last-used templates.
-const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
-
-describe("AI assistant applies per-db_type prompt template defaults", () => {
- it("panel-open resolution uses defaults-else-last-used through the tested helper and enforces the char cap", () => {
- const maybeBody = source.slice(source.indexOf("async function maybeApplyAutoTemplates()"), source.indexOf("// Reset template selection when the user switches"));
- expect(maybeBody).toContain("resolveAutoTemplateIds({");
- expect(maybeBody).toContain("defaultTemplatesByDbType: settings.aiDefaultTemplatesByDbType");
- expect(maybeBody).toContain("lastUsedTemplatesByDbType: settings.aiLastUsedTemplatesByDbType");
- expect(maybeBody).toContain("applyResolvedTemplateIds(");
- // The char cap lives in the shared apply helper both paths funnel through.
- const applyBody = source.slice(source.indexOf("function applyResolvedTemplateIds("), source.indexOf("async function maybeApplyAutoTemplates()"));
- expect(applyBody).toContain("capTemplateIdsToCharLimit(ids, promptTemplateStore.templates, ACTIVE_TEMPLATES_TOTAL_MAX)");
- });
-
- it("auto-apply waits for the AI selection load, runs once, and skips failed template loads", () => {
- const maybeBody = source.slice(source.indexOf("async function maybeApplyAutoTemplates()"), source.indexOf("// Reset template selection when the user switches"));
- expect(maybeBody).toContain("if (autoTemplatesInitialized || !settings.isAiConfigLoaded) return;");
- expect(maybeBody).toContain("if (!(await promptTemplateStore.ensureLoaded())) return;");
- expect(maybeBody).toContain("autoTemplatesInitialized = true;");
- expect(maybeBody).toContain("applyResolvedTemplateIds(");
- });
-
- it("namespace switch re-resolves defaults only when both stores are loaded, otherwise clears", () => {
- const watcherBody = source.slice(source.indexOf("aiTemplateNamespaceKey,"), source.indexOf("function toggleTemplateId("));
- expect(watcherBody).toContain("if (!settings.isAiConfigLoaded || !promptTemplateStore.isLoaded) {");
- expect(watcherBody).toContain("activeTemplateIds.value = [];");
- // The switch path must resolve through the defaults-only helper; the
- // mount resolver (defaults-else-last-used) would resurrect cleared
- // selections. Pin the exact call so an indirect last-used fallback
- // cannot hide behind a shared helper again.
- expect(watcherBody).toContain("resolveDefaultTemplateIds(templateDbType.value, settings.aiDefaultTemplatesByDbType)");
- expect(watcherBody).not.toContain("resolveAutoTemplateIds");
- expect(watcherBody).not.toContain("lastUsedTemplatesByDbType");
- });
-
- it("keys defaults, last-used, and the badge by the effective AI database type", () => {
- // Same axis aiDatabaseTypeForConnection established for schema selection:
- // gbase → mysql, doris-over-mysql protocol → doris, jdbc → inferred
- // dialect. Raw db_type keying would never match for those connections.
- expect(source).toContain("const templateDbType = computed(() => (!pluginContext.value && boundConnection.value ? aiDatabaseTypeForConnection(boundConnection.value) : undefined));");
- expect(source).toContain("aiDatabaseTypeForConnection");
- });
-
- it("panel-open resolution bails when the namespace switched during the load await", () => {
- const maybeBody = source.slice(source.indexOf("async function maybeApplyAutoTemplates"), source.indexOf("watch(", source.indexOf("async function maybeApplyAutoTemplates")));
- expect(maybeBody).toContain("const namespaceAtStart = aiTemplateNamespaceKey.value;");
- expect(maybeBody).toContain("if (namespaceAtStart !== aiTemplateNamespaceKey.value) return;");
- });
-
- it("selector-open load retry also applies pending defaults", () => {
- const watcherBody = source.slice(source.indexOf("watch(showTemplateSelector"), source.indexOf("// Auto-apply per-db_type"));
- expect(watcherBody).toContain("void promptTemplateStore.ensureLoaded().then(() => void maybeApplyAutoTemplates());");
- });
-
- it("send records the sent templates as the db_type's last-used selection", () => {
- const sendIdx = source.indexOf("activeTemplates: runPluginContext ? [] : [...activeTemplates.value],");
- const recordIdx = source.indexOf("settings.recordLastUsedTemplates(templateDbType.value, [...activeTemplateIds.value]);");
- expect(sendIdx).toBeGreaterThan(-1);
- expect(recordIdx).toBeGreaterThan(sendIdx);
- // No length guard: an empty selection must also reach the store so the
- // remembered entry is cleared instead of resurrecting old templates.
- const guard = source.slice(sendIdx, recordIdx);
- expect(guard).toContain("if (templateDbType.value) {");
- expect(guard).not.toContain("activeTemplates.value.length > 0");
- });
-
- it("the template selector marks defaults for the current connection db_type", () => {
- expect(source).toContain('v-if="isDefaultTemplateForCurrentDb(tpl.id)"');
- expect(source).toContain("settings.aiDefaultTemplatesByDbType[dbType]?.includes(id) ?? false");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSearchPanel.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSearchPanel.spec.ts
index d743071d75..79849a8eed 100644
--- a/apps/desktop/src/components/editor/__tests__/EditorSearchPanel.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/EditorSearchPanel.spec.ts
@@ -5,13 +5,6 @@ import { createQueryEditorSearchKeymap, replaceFallbackKey } from "@/lib/editor/
const editorSearchPanelSource = readFileSync(new URL("../EditorSearchPanel.vue", import.meta.url), "utf8");
const queryEditorSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
const contentAreaSource = readFileSync(new URL("../../layout/ContentArea.vue", import.meta.url), "utf8");
-const nacosConsoleSource = readFileSync(new URL("../../nacos/NacosAdminConsole.vue", import.meta.url), "utf8");
-
-describe("EditorSearchPanel corner style", () => {
- it("uses the configurable five-pixel radius token for editor inputs", () => {
- expect(editorSearchPanelSource).toContain("border-radius: var(--dbx-radius-fixed-5);");
- });
-});
describe("QueryEditor search shortcuts", () => {
it("opens search and replace in editable editors", () => {
@@ -60,11 +53,6 @@ describe("QueryEditor search shortcuts", () => {
expect(replaceFallbackKey("Linux x86_64")).toBe("Mod-h");
});
- it("routes the Nacos console replace fallback through the same platform helper", () => {
- expect(nacosConsoleSource).toContain("key: replaceFallbackKey()");
- expect(nacosConsoleSource).not.toContain('key: "Mod-h"');
- });
-
it("allows search but consumes replace without opening it in read-only editors", () => {
const openSearch = vi.fn(() => true);
const openReplace = vi.fn(() => true);
@@ -87,18 +75,4 @@ describe("QueryEditor search shortcuts", () => {
expect(editorSearchPanelSource).toContain('e.key === "Enter" && !e.shiftKey');
expect(editorSearchPanelSource).toContain('e.key === "Enter" && e.shiftKey');
});
-
- it("registers the find binding before the formatSql binding so an occupied default would shadow formatSql", () => {
- // The runtime keymap is first-match-wins: the find binding (shortcuts.find,
- // Mod+F) is spread into QueryEditor.vue's Prec.high keymap before the
- // formatSql binding (shortcuts.formatSql). A reserved-key repair that reset
- // find to its default Mod+F while the user had explicitly bound formatSql to
- // Mod+F would make formatSql unreachable — this ordering is why
- // normalizeShortcutSettings clears such a repair instead of applying it.
- const findIndex = queryEditorSource.indexOf("...binding(shortcuts.find, openSearch),");
- const formatIndex = queryEditorSource.indexOf("...binding(shortcuts.formatSql,");
- expect(findIndex).toBeGreaterThan(-1);
- expect(formatIndex).toBeGreaterThan(-1);
- expect(findIndex).toBeLessThan(formatIndex);
- });
});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiConfigDeepLinkTabHijack.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiConfigDeepLinkTabHijack.spec.ts
deleted file mode 100644
index 1855b85ed6..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiConfigDeepLinkTabHijack.spec.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-
-// Regression for https://github.com/t8y2/dbx/issues/7874: after using an AI
-// config deep link (dbx://settings/ai/new?...) once, every later "open
-// Settings" (even a plain click on the gear icon) got forcibly yanked back to
-// the AI tab. Root cause: `settingsAiConfigDraft`/`settingsAiConfigRequestId`
-// in App.vue are set once by `openAiConfigDeepLink` and never cleared, while
-// the dialog's own "already handled this request" guard
-// (`handledAiConfigRequestId`) is a plain local variable that resets to 0
-// every time the dialog remounts (it's `v-if`-toggled in App.vue, so closing
-// Settings destroys the instance). On the next open, `requestId !==
-// handledAiConfigRequestId` is true again even though nothing new happened,
-// so `applyPendingAiConfigDeepLinkDraft` reapplies the stale draft and jumps
-// the user back into "ai" tab / edit mode forever, once per app run.
-describe("EditorSettingsDialog AI config deep-link tab hijack", () => {
- function applyDraftBlock(): string {
- const start = dialogSource.indexOf("async function applyPendingAiConfigDeepLinkDraft()");
- const end = dialogSource.indexOf("\n}\n", start);
- if (start < 0 || end < 0) throw new Error("Missing applyPendingAiConfigDeepLinkDraft function block");
- return dialogSource.slice(start, end);
- }
-
- it("emits an event once the deep-link draft has been consumed", () => {
- expect(dialogSource).toContain('"ai-config-deep-link-handled": []');
- expect(applyDraftBlock()).toContain('emit("ai-config-deep-link-handled")');
- });
-
- it("App.vue clears the draft/request state once notified, so a remounted dialog can't reapply it", () => {
- expect(appSource).toContain('@ai-config-deep-link-handled="settingsAiConfigDraft = null"');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiTestIsolation.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiTestIsolation.spec.ts
deleted file mode 100644
index 1afcd9592a..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.aiTestIsolation.spec.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { readFileSync } from "node:fs";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-describe("EditorSettingsDialog AI test result isolation", () => {
- it("clears the previous test result when opening another configuration", () => {
- expect(dialogSource).toMatch(/function aiEnterEditMode\(configId\?: string\) \{\s*syncAiEditState\(\);/);
- });
-
- it("clears the previous test result when changing provider in the editor", () => {
- expect(dialogSource).toMatch(/if \(presetId === aiEditProviderPresetId\.value\) return;\s*\n\s*syncAiEditState\(\);/);
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.applyError.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.applyError.spec.ts
deleted file mode 100644
index 94b937d2fe..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.applyError.spec.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// Regression for https://github.com/t8y2/dbx/issues/6485: applying editor
-// settings (e.g. the editor font) could appear to "do nothing" because
-// persistSettings() has several awaited persistence steps with no error
-// handling. On a rejected save, "Apply" was completely silent and "Apply &
-// Close" never called closeSettings(), leaving the dialog stuck open with no
-// feedback at all.
-describe("EditorSettingsDialog apply persistence error handling", () => {
- it("shares a single apply entrypoint between Apply and Apply & Close", () => {
- // Both buttons must go through one shared persist/apply routine instead of
- // each calling persistSettings() directly with divergent semantics.
- const block = dialogSource.slice(dialogSource.indexOf("function applySettingsErrorToast"), dialogSource.indexOf("async function restartDbxForDuckDbIsolation()"));
- const entrypointCalls = (block.match(/await applySettingsForResult\(\)/g) || []).length;
- // one call in applySettings() + one (guarded) call in applySettingsAndClose()
- expect(entrypointCalls).toBeGreaterThanOrEqual(2);
- // the shared entrypoint exists and wraps persistSettings
- expect(block).toContain("async function applySettingsForResult(): Promise<boolean>");
- expect(block).toContain("await persistSettings();");
- });
-
- it("never closes the dialog before persistence succeeds", () => {
- // "Apply & Close" must only proceed to closeSettings() after a successful
- // apply. Before the fix, closeSettings() ran unconditionally after
- // `await persistSettings()`, so a rejected save left the dialog stuck open.
- const block = dialogSource.slice(dialogSource.indexOf("async function applySettingsAndClose()"), dialogSource.indexOf("async function restartDbxForDuckDbIsolation()"));
- expect(block).toMatch(/if \(await applySettingsForResult\(\)\) \{\s*\n\s*closeSettings\(\);/);
- });
-
- it("surfaces persistence failures instead of silently swallowing them", () => {
- const resultBlock = dialogSource.slice(dialogSource.indexOf("async function applySettingsForResult()"), dialogSource.indexOf("async function applySettings()"));
- expect(resultBlock).toContain("try {");
- expect(resultBlock).toContain("catch (error)");
- expect(resultBlock).toContain("applySettingsErrorToast(error)");
- expect(resultBlock).toContain("return false;");
- // a user-facing message is wired up (and translated in every locale)
- expect(dialogSource).toContain('toast(t("settings.applyFailed"');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.choiceCardLayout.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.choiceCardLayout.spec.ts
deleted file mode 100644
index a9587c9fff..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.choiceCardLayout.spec.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-import { cn } from "@/lib/common/utils";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-const buttonSource = readFileSync(new URL("../../ui/button/index.ts", import.meta.url), "utf8");
-const templateSource = dialogSource.slice(dialogSource.indexOf("<template>"));
-const buttonBaseClass = /cva\(\s*"([^"]+)"/.exec(buttonSource)?.[1];
-if (!buttonBaseClass) throw new Error("Missing shared Button base class contract");
-
-const affectedChoiceKeys = ["tabLayoutScroll", "tabLayoutWrap", "dataTabReuseAlwaysNew", "dataTabReuseSameTable", "dataTabReuseActiveTab", "routineSourceOpenModeQueryTab", "routineSourceOpenModeDialog"] as const;
-
-function sourceIndexForKey(key: string): number {
- const index = templateSource.indexOf(`t("settings.${key}")`);
- if (index < 0) throw new Error(`Missing settings key: ${key}`);
- return index;
-}
-
-function buttonBlockForKey(key: string): string {
- const keyIndex = sourceIndexForKey(key);
- const start = templateSource.lastIndexOf("<Button", keyIndex);
- const end = templateSource.indexOf("</Button>", keyIndex);
- if (start < 0 || end < 0) throw new Error(`Missing Button for settings key: ${key}`);
- return templateSource.slice(start, end + "</Button>".length);
-}
-
-function openingTag(source: string, element: string): string {
- const start = source.indexOf(`<${element}`);
- const end = tagEnd(source, start);
- if (start < 0 || end < 0) throw new Error(`Missing <${element}> opening tag`);
- return source.slice(start, end + 1);
-}
-
-function elementTagForKey(key: string, element = "div"): string {
- const keyIndex = sourceIndexForKey(key);
- const start = templateSource.lastIndexOf(`<${element}`, keyIndex);
- const end = tagEnd(templateSource, start);
- if (start < 0 || end < 0) throw new Error(`Missing <${element}> for settings key: ${key}`);
- return templateSource.slice(start, end + 1);
-}
-
-function elementTagForKeyInButton(buttonKey: string, key: string, element = "div"): string {
- const block = buttonBlockForKey(buttonKey);
- const keyIndex = block.indexOf(`t("settings.${key}")`);
- const start = block.lastIndexOf(`<${element}`, keyIndex);
- const end = tagEnd(block, start);
- if (keyIndex < 0 || start < 0 || end < 0) throw new Error(`Missing <${element}> for settings key ${key} in ${buttonKey}`);
- return block.slice(start, end + 1);
-}
-
-function tagEnd(source: string, start: number): number {
- let quote: '"' | "'" | null = null;
- for (let index = start; index < source.length; index += 1) {
- const char = source[index];
- if (quote) {
- if (char === quote && source[index - 1] !== "\\") quote = null;
- } else if (char === '"' || char === "'") {
- quote = char;
- } else if (char === ">") {
- return index;
- }
- }
- return -1;
-}
-
-function classNameFromTag(tag: string): string {
- const match = /\sclass="([^"]+)"/.exec(tag);
- if (!match) throw new Error(`Missing static class attribute in: ${tag}`);
- return match[1];
-}
-
-function expectClassTokens(className: string, tokens: readonly string[]) {
- const classes = new Set(className.split(/\s+/));
- for (const token of tokens) expect(classes.has(token), `${className} should include ${token}`).toBe(true);
-}
-
-describe("EditorSettingsDialog choice card containment", () => {
- it("shows the persistent filter-editor preference only for fixed filter views", () => {
- const key = 't("settings.dataGridKeepFilterEditorExpanded")';
- const keyIndex = templateSource.indexOf(key);
- const configurationStart = templateSource.indexOf("<div v-if=\"editDataGridFilterEditorView !== 'quick'\"");
- expect(keyIndex).toBeGreaterThan(-1);
- expect(configurationStart).toBeGreaterThan(-1);
- expect(configurationStart).toBeLessThan(keyIndex);
- expect(templateSource).not.toContain("dataGridAutoHideFilterBuilder");
- });
-
- it("overrides the shared Button nowrap contract on two- and three-column cards", () => {
- for (const key of affectedChoiceKeys) {
- const cardClass = classNameFromTag(openingTag(buttonBlockForKey(key), "Button"));
- expectClassTokens(cardClass, ["settings-choice-card", "min-w-0", "whitespace-normal", "overflow-hidden"]);
-
- const mergedClass = cn(buttonBaseClass, cardClass);
- expectClassTokens(mergedClass, ["min-w-0", "whitespace-normal", "overflow-hidden"]);
- expect(mergedClass.split(/\s+/)).not.toContain("whitespace-nowrap");
- }
- });
-
- it("lets long two-column descriptions wrap inside a shrinkable text container", () => {
- for (const key of ["tabLayoutScroll", "tabLayoutWrap", "routineSourceOpenModeQueryTab", "routineSourceOpenModeDialog"] as const) {
- const block = buttonBlockForKey(key);
- expect(block).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\btext-left\b[^"]*">/);
- }
-
- for (const [buttonKey, descriptionKey] of [
- ["tabLayoutScroll", "tabLayoutScrollDescription"],
- ["tabLayoutWrap", "tabLayoutWrapDescription"],
- ["routineSourceOpenModeQueryTab", "routineSourceOpenModeQueryTabDescription"],
- ["routineSourceOpenModeDialog", "routineSourceOpenModeDialogDescription"],
- ] as const) {
- expectClassTokens(classNameFromTag(elementTagForKeyInButton(buttonKey, descriptionKey)), ["whitespace-normal", "break-words"]);
- }
- });
-
- it("keeps three-column titles shrinkable without allowing help icons to collapse", () => {
- for (const key of ["dataTabReuseAlwaysNew", "dataTabReuseSameTable", "dataTabReuseActiveTab"] as const) {
- const block = buttonBlockForKey(key);
- expect(block).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\btext-left\b[^"]*">/);
- expect(block).toMatch(/<div class="[^"]*\bflex\b[^"]*\bmin-w-0\b[^"]*\bitems-center\b[^"]*">/);
- expectClassTokens(classNameFromTag(elementTagForKey(key)), ["min-w-0", "break-words"]);
- expect(block).toMatch(/<span class="[^"]*\bshrink-0\b[^"]*cursor-help[^"]*"[^>]*>/);
- }
- });
-
- it("preserves intentional single-line truncation for cards with tooltips", () => {
- for (const key of ["appLayoutSeparatedDescription", "appLayoutClassicDescription"] as const) {
- expectClassTokens(classNameFromTag(elementTagForKey(key)), ["truncate"]);
- }
- });
-
- it("keeps large icon theme choices in appearance and debug logs in About", () => {
- expect(sourceIndexForKey("iconTheme")).toBeLessThan(sourceIndexForKey("debugLoggingEnabled"));
- expect(templateSource).toContain("data-icon-theme-settings");
- for (const key of ["iconThemeDefault", "iconThemeBlack"] as const) {
- const block = buttonBlockForKey(key);
- expectClassTokens(classNameFromTag(openingTag(block, "Button")), ["settings-choice-card", "h-auto", "min-w-0", "whitespace-normal", "overflow-hidden"]);
- expect(block).toContain('class="h-12 w-12 shrink-0"');
- }
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts
index 1729a02f6f..9e18116c4d 100644
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts
@@ -4,104 +4,6 @@ import { createMcpQueryTimeoutHarness } from "./mcpQueryTimeoutHarness";
const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-function handlerBlock(): string {
- const start = dialogSource.indexOf("function onMcpQueryTimeoutInput(");
- const end = dialogSource.indexOf("const mcpSelectableConnections", start);
- if (start < 0 || end < 0) throw new Error("Missing onMcpQueryTimeoutInput handler block");
- return dialogSource.slice(start, end);
-}
-
-// Regression for the MCP query-timeout input: decimal values like 1.5 were
-// silently Math.round-ed to 2 and saved, contradicting the "non-negative whole
-// number" label. The UI must reject non-integers with the existing invalid
-// toast instead of silently rewriting them.
-describe("EditorSettingsDialog MCP query timeout validation", () => {
- it("rejects non-integers instead of rounding them", () => {
- const block = handlerBlock();
- // The invalid path must test for integer-ness, not just finite + non-negative.
- expect(block).toMatch(/Number\.isInteger\(parsed\)/);
- // The valid save path must NOT wrap the value in Math.round anymore.
- expect(block).not.toContain("Math.round(parsed)");
- // A decimal input falls through to the invalid toast + revert branch.
- expect(block).toContain('toast(t("settings.mcpQueryTimeoutInvalid"), 5000)');
- expect(block).toMatch(/mcpQueryTimeoutInput\.value\s*=\s*reverted/);
- });
-
- it("keeps null (inherit) and zero (no limit) working", () => {
- const block = handlerBlock();
- // Empty input still schedules null (inherit the connection).
- expect(block).toContain("mcpQueryTimeoutPendingValue = null");
- // A valid integer is scheduled with the exact value.
- expect(block).toContain("mcpQueryTimeoutPendingValue = parsed");
- // The invalid branch cancels any pending save instead of persisting garbage.
- expect(block).toContain("mcpQueryTimeoutPendingValue = undefined");
- });
-});
-
-// Regression for #8616: the input previously bound @change (fires only on
-// blur/Enter), so typing a value and closing the window dropped the change and
-// the persisted policy kept its old value. The fix binds @input (fires on every
-// keystroke), debounces the write, and flushes any pending value on close.
-describe("EditorSettingsDialog MCP query timeout persistence", () => {
- it("binds @input instead of @change so typing schedules a save immediately", () => {
- const inputLine = dialogSource.split("\n").find((line) => line.includes('id="mcp-query-timeout"'));
- expect(inputLine).toBeTruthy();
- // The legacy @change binding must not come back.
- expect(inputLine).not.toContain("@change");
- // Typing must trigger the save path on every keystroke.
- expect(inputLine).toContain('@input.capture="onMcpQueryTimeoutInput"');
- });
-
- it("uses capture-phase input handling so the handler reads the fresh native value before Input's passive v-model update", () => {
- const inputLine = dialogSource.split("\n").find((line) => line.includes('id="mcp-query-timeout"'));
- expect(inputLine).toBeTruthy();
- expect(inputLine).toContain('v-model="mcpQueryTimeoutInput"');
- expect(inputLine).toContain('@input.capture="onMcpQueryTimeoutInput"');
- });
-
- it("handler reads the value from the native event target, not the ref", () => {
- const block = handlerBlock();
- expect(block).toContain("onMcpQueryTimeoutInput(event: Event)");
- expect(block).toMatch(/const target = event\.currentTarget as HTMLInputElement/);
- expect(block).toContain("target.value.trim()");
- });
-
- it("debounces the persist so rapid typing coalesces into one write", () => {
- const block = handlerBlock();
- expect(block).toContain("MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS");
- expect(block).toMatch(/setTimeout\([\s\S]*MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS\)/);
- expect(block).toContain("clearTimeout(mcpQueryTimeoutSaveTimer)");
- expect(block).toContain("flushMcpQueryTimeoutSave()");
- });
-
- it("flushes the pending value when the settings dialog closes", () => {
- const closeBlockStart = dialogSource.indexOf("function requestCloseSettings(");
- const closeBlockEnd = dialogSource.indexOf("function onSettingsRootOpenChange", closeBlockStart);
- expect(closeBlockStart).toBeGreaterThan(-1);
- expect(closeBlockEnd).toBeGreaterThan(closeBlockStart);
- const closeBlock = dialogSource.slice(closeBlockStart, closeBlockEnd);
- expect(closeBlock).toContain("flushMcpQueryTimeoutSave()");
-
- // The unmount path must also flush, covering a hard window close.
- const unmountIndex = dialogSource.lastIndexOf("onUnmounted(() =>");
- expect(unmountIndex).toBeGreaterThan(-1);
- const unmountTail = dialogSource.slice(unmountIndex);
- expect(unmountTail).toContain("flushMcpQueryTimeoutSave()");
- });
-
- it("persists through saveMcpPolicy with the pending value", () => {
- const flushBlockStart = dialogSource.indexOf("function flushMcpQueryTimeoutSave()");
- const flushBlockEnd = dialogSource.indexOf("const mcpSelectableConnections", flushBlockStart);
- expect(flushBlockStart).toBeGreaterThan(-1);
- expect(flushBlockEnd).toBeGreaterThan(flushBlockStart);
- const flushBlock = dialogSource.slice(flushBlockStart, flushBlockEnd);
- // The debounced timer hands the pending value to the existing save path.
- expect(flushBlock).toContain("queryTimeoutSecs: value");
- // A cleared pending value (no recent input) is a no-op.
- expect(flushBlock).toContain("mcpQueryTimeoutPendingValue === undefined");
- });
-});
-
// Behavioral coverage for the debounce/flush runtime (review finding): the
// string assertions above cannot catch a broken runtime path, so this harness
// extracts the real debounce block from the .vue source, compiles it, and
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewCleanup.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewCleanup.spec.ts
deleted file mode 100644
index 2716496296..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewCleanup.spec.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-
-describe("EditorSettingsDialog preview cleanup", () => {
- it("keeps the existing draft lifecycle independent from page activity", () => {
- expect(dialogSource).toContain("const settingsVisible = computed(() => isSettingsPage.value || props.open === true);");
- expect(dialogSource).toContain("syncEditorSettingsDraftFromStore();");
- });
-
- it("clears previews when a mounted settings page becomes inactive", () => {
- expect(appSource).toContain('v-if="settingsPageTabOpen"');
- expect(appSource).toContain('v-show="settingsStore.settingsPageActive"');
- expect(dialogSource).toContain("() => settingsStore.settingsPageActive");
- expect(dialogSource).toContain("if (isSettingsPage.value && !active)");
- expect(dialogSource).toContain("clearThemePalettePreview();");
- expect(dialogSource).toContain("clearUiFontFamilyPreview();");
- expect(dialogSource).toContain("restoreLocaleOptionPreview();");
- });
-
- it("coalesces pointer previews while keeping keyboard previews immediate", () => {
- expect(dialogSource).toContain('@update:open="onLocaleOpenChange"');
- expect(dialogSource).toContain('@pointerleave="restoreLocaleOptionPreview"');
- expect(dialogSource).toContain('@pointerenter="scheduleLocaleOptionPreview(locale.value)"');
- expect(dialogSource).toContain('@focus="previewLocaleOption(locale.value)"');
- expect(dialogSource).toContain('@pointerenter="scheduleThemePalettePreview(option.value)"');
- expect(dialogSource).toContain('@focus="previewThemePaletteOption(option.value)"');
- expect(dialogSource).toContain('@option-hover="scheduleUiFontOptionPreview"');
- expect(dialogSource).toContain('@option-highlight="previewUiFontOption"');
- expect(dialogSource).toContain("createDelayedPreview");
- });
-
- it("keeps scale as an unapplied draft", () => {
- expect(dialogSource).toContain('@update:model-value="onUiScaleChange"');
- expect(dialogSource).not.toContain("useUiScalePreview");
- expect(dialogSource).not.toContain("previewUiScaleOption");
- expect(dialogSource).not.toContain("createUiScalePreviewRestore");
- expect(appSource).toContain("createUiScaleApplyQueue");
- expect(appSource).not.toContain("useUiScalePreview");
- expect(appSource).toContain("() => settingsStore.editorSettings.uiScale");
- expect(appSource).toContain("applyUiScale(scale)");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewPosition.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewPosition.spec.ts
deleted file mode 100644
index 9935a0f62a..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.previewPosition.spec.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-const editorSectionStart = dialogSource.indexOf(`<section v-if="activeSettingsTab === 'editor'"`);
-const formatterSectionStart = dialogSource.indexOf(`activeSettingsTab === 'formatter'`, editorSectionStart);
-const editorSection = dialogSource.slice(editorSectionStart, formatterSectionStart);
-const editorPreviewStart = dialogSource.indexOf("data-editor-live-preview");
-const settingsSearchResultsStart = dialogSource.indexOf('v-if="settingsSearchVisible"', editorPreviewStart);
-const editorPreview = dialogSource.slice(editorPreviewStart, settingsSearchResultsStart);
-const dataSectionStart = dialogSource.indexOf(`activeSettingsTab === 'data'`);
-const shortcutsSectionStart = dialogSource.indexOf(`activeSettingsTab === 'shortcuts'`, dataSectionStart);
-const dataSection = dialogSource.slice(dataSectionStart, shortcutsSectionStart);
-
-describe("EditorSettingsDialog live preview placement", () => {
- it("keeps the live preview below search and outside the editor settings scroller", () => {
- const fontFamily = editorSection.indexOf('t("settings.fontFamily")');
- const theme = editorSection.indexOf('t("settings.theme")');
- const fontSize = editorSection.indexOf('t("settings.fontSize")');
- const previewControls = editorSection.indexOf("data-editor-preview-controls");
- const executeMode = editorSection.indexOf("executeModeLabel");
- const searchInput = dialogSource.indexOf("settingsSearchInputContainerRef");
- const scroller = dialogSource.indexOf('ref="settingsContentScrollRef"');
-
- expect(editorSectionStart).toBeGreaterThanOrEqual(0);
- expect(formatterSectionStart).toBeGreaterThan(editorSectionStart);
- expect(fontFamily).toBeGreaterThanOrEqual(0);
- expect(theme).toBeGreaterThan(fontFamily);
- expect(fontSize).toBeGreaterThan(theme);
- expect(previewControls).toBeGreaterThan(fontSize);
- expect(executeMode).toBeGreaterThan(previewControls);
- expect(editorPreviewStart).toBeGreaterThan(searchInput);
- expect(editorPreviewStart).toBeLessThan(scroller);
- expect(dialogSource.indexOf("activeSettingsTab === 'editor' && !settingsSearchVisible", searchInput)).toBeLessThan(editorPreviewStart);
- expect(editorPreview).toContain('ref="previewRef"');
- expect(editorPreview).toContain("settings-editor-live-preview-surface");
- expect(dialogSource.match(/ref="previewRef"/g)).toHaveLength(1);
- expect(editorSection).not.toContain('ref="previewRef"');
-
- for (const id of ["editor-show-statement-run-buttons", "editor-show-line-numbers", "editor-show-current-statement-frame", "editor-sql-semantic-diagnostics", "editor-show-table-ddl-hover-preview"]) {
- expect(editorSection.indexOf(`id="${id}"`)).toBeGreaterThan(previewControls);
- expect(editorSection.indexOf(`id="${id}"`)).toBeLessThan(executeMode);
- expect(editorSection.match(new RegExp(`id="${id}"`, "g"))).toHaveLength(1);
- }
- });
-
- it("unmounts the preview for search results and safely cancels pending initialization or updates", () => {
- expect(dialogSource).toContain("watch(previewRef, async (el) => {");
- expect(dialogSource).toContain("if (!el) {");
- expect(dialogSource).toContain("cleanupPreviewEditor();");
- expect(dialogSource).toContain("const previewHost = el;");
- expect(dialogSource).toContain("previewRef.value !== previewHost");
- expect(dialogSource).toContain("parent: previewHost");
- expect(dialogSource).toContain("const currentPreviewView = previewView.value;");
- expect(dialogSource).toContain("previewView.value !== currentPreviewView");
- expect(dialogSource).toContain("currentPreviewView.dispatch({");
- expect(dialogSource).toContain(".settings-editor-live-preview-surface {");
- expect(dialogSource).toContain("max-height: min(16rem, 34vh);");
- });
-
- it("places execution behavior before SQL completion with high-priority controls first", () => {
- const completionSection = editorSection.indexOf("data-editor-sql-completion-settings");
- const completionTriggerMode = editorSection.indexOf('t("settings.completionTriggerMode")');
- const selectFirstCompletion = editorSection.indexOf('t("settings.selectFirstCompletionOnOpen")');
- const executionSection = editorSection.indexOf("data-editor-execution-settings");
- const executeMode = editorSection.indexOf("executeModeLabel", executionSection);
-
- expect(executionSection).toBeGreaterThan(editorSection.indexOf("data-editor-preview-controls"));
- expect(executeMode).toBeGreaterThan(executionSection);
- expect(completionSection).toBeGreaterThan(executeMode);
- expect(completionTriggerMode).toBeGreaterThan(completionSection);
- expect(selectFirstCompletion).toBeGreaterThan(completionTriggerMode);
- expect(editorSection).not.toContain('t("settings.sqlCompletionSection")');
- expect(editorSection).toContain('class="settings-item flex items-start justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2" data-editor-completion-trigger-mode');
- expect(editorSection).toContain('<SelectTrigger class="h-8 w-44 shrink-0">');
- expect(editorSection).toContain('class="grid gap-4 md:grid-cols-2" data-editor-execution-settings');
- expect(editorSection).toContain('class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2 md:col-span-2" data-editor-execute-mode');
- expect(editorSection.match(/:model-value="editCompletionTriggerMode"/g)).toHaveLength(1);
- expect(editorSection.match(/id="editor-select-first-completion-on-open"/g)).toHaveLength(1);
- });
-
- it("groups related execution and unsaved SQL controls without removing saved-target behavior", () => {
- const executionGroup = editorSection.indexOf("data-editor-execution-settings");
- const executionGroupEnd = editorSection.indexOf("data-editor-sql-completion-settings", executionGroup);
- const unsavedGroup = editorSection.indexOf("data-editor-unsaved-sql-settings");
- const unsavedGroupEnd = editorSection.indexOf("generate-sql-include-database-name", unsavedGroup);
-
- for (const id of ["editor-execute-all-on-blank-line", "editor-show-execution-target-picker", "editor-confirm-dangerous-sql", "editor-continue-on-error"]) {
- expect(editorSection.indexOf(`id="${id}"`)).toBeGreaterThan(executionGroup);
- expect(editorSection.indexOf(`id="${id}"`)).toBeLessThan(executionGroupEnd);
- expect(editorSection.match(new RegExp(`id="${id}"`, "g"))).toHaveLength(1);
- }
- for (const id of ["editor-confirm-unsaved-sql-close", "app-close-unsaved-tabs-mode"]) {
- expect(editorSection.indexOf(`id="${id}"`)).toBeGreaterThan(unsavedGroup);
- expect(editorSection.indexOf(`id="${id}"`)).toBeLessThan(unsavedGroupEnd);
- }
- expect(editorSection).toContain('id="editor-saved-sql-open-target"');
- expect(editorSection).toContain('class="flex min-w-0 items-start justify-between gap-4"');
- expect(editorSection).toContain('id="app-close-unsaved-tabs-mode" class="h-8 w-44 shrink-0"');
- expect(editorSection).not.toContain('id="editor-click-table-navigation-ddl"');
- expect(editorSection).not.toContain('id="editor-prefill-new-query"');
- });
-
- it("describes the execute shortcut below the mode selector in every supported locale", () => {
- expect(editorSection.indexOf("executeModeDescription")).toBeGreaterThan(editorSection.indexOf("executeModeLabel"));
-
- for (const locale of ["zh-CN", "zh-TW", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "az"]) {
- const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- expect(source, locale).toContain("executeModeDescription:");
- }
- });
-
- it("shows a concise description for the selected completion trigger mode", () => {
- expect(dialogSource).toContain("const completionTriggerModeDescription = computed(() => {");
- expect(editorSection).toContain("{{ completionTriggerModeDescription }}");
- expect(editorSection).not.toContain('t("settings.completionTriggerModeDescription")');
-
- for (const locale of ["zh-CN", "zh-TW", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "az"]) {
- const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- for (const key of ["completionTriggerModeManualDescription", "completionTriggerModeRequirePrefixDescription", "completionTriggerModePositionalDescription"]) {
- expect(source, `${locale}:${key}`).toContain(`${key}:`);
- }
- }
- });
-
- it("moves table navigation and query prefill controls to Navigation", () => {
- const navigationSection = dialogSource.slice(dialogSource.indexOf(`activeSettingsTab === 'navigation'`));
-
- for (const id of ["editor-click-table-navigation-ddl", "editor-prefill-new-query"]) {
- expect(navigationSection).toContain(`id="${id}"`);
- expect(dialogSource.match(new RegExp(`id="${id}"`, "g"))).toHaveLength(1);
- }
- });
-
- it("groups navigation settings by data tabs and sidebar browsing flow", () => {
- const navigationSection = dialogSource.slice(dialogSource.indexOf(`activeSettingsTab === 'navigation'`));
- const adjacentDataTabs = navigationSection.indexOf('id="open-data-tabs-next-to-active"');
- const objectDisplay = navigationSection.indexOf('t("settings.sidebarObjectDisplay")');
- const routineOpenMode = navigationSection.indexOf('t("settings.routineSourceOpenMode")');
- const tableNavigation = navigationSection.indexOf('id="editor-click-table-navigation-ddl"');
- const browseObjectsOnDatabaseActivation = navigationSection.indexOf('id="sidebar-browse-objects-on-database-activation"');
- const tableSearch = navigationSection.indexOf('id="sidebar-table-search-enabled"');
- const activeNodeSelection = navigationSection.indexOf('id="auto-select-active-sidebar-node"');
-
- expect(browseObjectsOnDatabaseActivation).toBeGreaterThanOrEqual(0);
- expect(adjacentDataTabs).toBeGreaterThan(browseObjectsOnDatabaseActivation);
- expect(objectDisplay).toBeGreaterThan(adjacentDataTabs);
- expect(routineOpenMode).toBeGreaterThan(objectDisplay);
- expect(tableNavigation).toBeGreaterThan(routineOpenMode);
- expect(tableSearch).toBeGreaterThan(tableNavigation);
- expect(activeNodeSelection).toBeGreaterThan(tableSearch);
- });
-
- it("puts the data grid filter view first with flat choices and a live preview", () => {
- const filterView = dataSection.indexOf('data-settings-search-id="data-grid-filter-view"');
- const dataGridDisplay = dataSection.indexOf('t("settings.dataGridDisplay")');
-
- expect(dataSectionStart).toBeGreaterThanOrEqual(0);
- expect(shortcutsSectionStart).toBeGreaterThan(dataSectionStart);
- expect(filterView).toBeGreaterThanOrEqual(0);
- expect(filterView).toBeLessThan(dataGridDisplay);
- expect(dataSection).toContain(`:class="['overflow-hidden rounded-md border bg-muted/20', settingsSearchTargetClass('data-grid-filter-view')]"`);
- expect(dataSection).toContain("data-data-grid-filter-view-options");
- expect(dataSection).toContain('v-if="dataGridFilterViewPreviewExpanded" class="pointer-events-none select-none overflow-hidden border-t bg-background" data-data-grid-filter-view-preview');
- expect(dataSection).toContain("data-data-grid-filter-view-preview-toggle");
- expect(dataSection).toContain(':aria-expanded="dataGridFilterViewPreviewExpanded"');
- expect(dataSection).toContain('t("settings.dataGridFilterViewPreview")');
- expect(dataSection).toContain("dataGridFilterViewPreviewExpanded = !dataGridFilterViewPreviewExpanded");
- expect(dataSection).toContain("data-data-grid-filter-preview-quick");
- expect(dataSection).toContain("data-data-grid-filter-preview-conditions");
- expect(dataSection).toContain("data-data-grid-filter-preview-text");
- expect(dataSection.match(/text-muted-foreground\/70">\{\{ t\("grid.applyFilter"\) \}\}/g)).toHaveLength(2);
- expect(dataSection).not.toContain('rounded bg-primary px-2 py-1 text-primary-foreground">{{ t("grid.applyFilter") }}');
- expect(dataSection.match(/editDataGridFilterEditorView = '(quick|conditions|text)'/g)).toHaveLength(3);
- expect(dataSection).not.toContain('<SelectTrigger id="data-grid-filter-view"');
-
- for (const locale of ["zh-CN", "zh-TW", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "az"]) {
- const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- for (const key of ["dataGridFilterViewPreview", "dataGridFilterViewPreviewExpand", "dataGridFilterViewPreviewCollapse"]) {
- expect(source, `${locale}:${key}`).toContain(`${key}:`);
- }
- }
- });
-
- it("updates preview line-number visibility from the unsaved editor draft", () => {
- expect(dialogSource).toContain("showLineNumbers: editShowLineNumbers.value");
- expect(dialogSource).toContain('import { buildQueryEditorLineNumbersExtension } from "@/lib/editor/queryEditorLineNumbers";');
- expect(dialogSource).toContain('let previewLineNumbersComp: import("@codemirror/state").Compartment | null = null;');
- expect(dialogSource).toContain('const previewBasicSetup = (basicSetup as readonly import("@codemirror/state").Extension[]).slice(2);');
- expect(dialogSource).toContain("previewLineNumbersComp.of(buildPreviewLineNumbersExtension(ss.showLineNumbers))");
- expect(dialogSource).toContain("currentPreviewLineNumbersComp.reconfigure(buildPreviewLineNumbersExtension(ss.showLineNumbers))");
- expect(dialogSource).toContain("return buildQueryEditorLineNumbersExtension(previewLineNumbersFactory, enabled");
- });
-
- it("uses the unsaved font draft for the preview CSS variables", () => {
- expect(dialogSource).toContain("EDITOR_FONT_FAMILY_CSS_VAR");
- expect(dialogSource).toContain("EDITOR_FONT_SIZE_CSS_VAR");
- expect(dialogSource).toContain("const previewFontStyle = computed<Record<string, string>>");
- expect(dialogSource).toContain("[EDITOR_FONT_FAMILY_CSS_VAR]: editFontFamily.value");
- expect(dialogSource).toContain("[EDITOR_FONT_SIZE_CSS_VAR]: `${editFontSize.value}px`");
- expect(dialogSource).toContain(":style=\"{ minWidth: '100%', ...previewFontStyle }\"");
- expect(dialogSource).toContain("watch([editFontFamily, editFontSize], () => {");
- expect(dialogSource).toContain("previewView.value?.requestMeasure();");
- });
-
- it("creates the preview editor as read-only so demo edits cannot desync the Apply buttons", () => {
- expect(dialogSource).toContain("EditorState.readOnly.of(true)");
- expect(dialogSource).toContain("EditorView.editable.of(false)");
- expect(dialogSource).toContain('EditorView.contentAttributes.of({ tabindex: "0" })');
- });
-
- it("explains the intentional syntax-error demo below the preview when diagnostics are enabled", () => {
- const preview = editorPreview.indexOf('ref="previewRef"');
- expect(editorPreview).toContain('v-if="editSqlSemanticDiagnosticsEnabled"');
- expect(editorPreview.indexOf('t("settings.previewSyntaxErrorHint")')).toBeGreaterThan(preview);
- });
-
- it.each(["en", "zh-CN", "zh-TW", "es", "pt-BR", "it", "ja", "ko", "tr", "az"])("locale %s translates settings.previewSyntaxErrorHint", (locale) => {
- const localeSource = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- expect(localeSource).toMatch(/previewSyntaxErrorHint: ".+"/);
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.redisDatabaseDisplayLimitClamp.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.redisDatabaseDisplayLimitClamp.spec.ts
deleted file mode 100644
index c3c90097f4..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.redisDatabaseDisplayLimitClamp.spec.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// Regression found while verifying issue #1236 (Redis sidebar database list
-// limit): updateEditorSettings() silently clamps an out-of-range
-// redisDatabaseDisplayLimit to [MIN, MAX], but persistSettings() only
-// re-synced the dirty-check baseline (editEditorSettingsBase), not the input's
-// own v-model ref. Typing a below-minimum value and clicking Apply left the
-// draft (the unclamped value) permanently out of sync with the saved
-// (clamped) value, so the dialog kept reporting unsaved changes forever after
-// a successful apply.
-describe("EditorSettingsDialog Redis database display limit clamp resync", () => {
- it("reflects the clamped value back into the input after a successful apply", () => {
- const block = dialogSource.slice(dialogSource.indexOf("async function persistSettings()"), dialogSource.indexOf("function applySettingsErrorToast"));
- expect(block).toContain("editEditorSettingsBase.value = editorSettingsDraftFromSettings(settingsStore.editorSettings);");
- expect(block).toContain("editRedisDatabaseDisplayLimit.value = settingsStore.editorSettings.redisDatabaseDisplayLimit;");
- // The resync must happen after the clamp-and-persist step, inside the same
- // "there is a pending editor-settings patch" branch, not unconditionally.
- const clampResyncIndex = block.indexOf("editRedisDatabaseDisplayLimit.value = settingsStore.editorSettings.redisDatabaseDisplayLimit;");
- const persistIndex = block.indexOf("await settingsStore.persistEditorSettings();");
- expect(clampResyncIndex).toBeGreaterThan(persistIndex);
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCapture.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCapture.spec.ts
deleted file mode 100644
index 25e8d5df94..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCapture.spec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// Regression for https://github.com/t8y2/dbx/issues/9881: the shortcut draft was
-// written straight from the captured key event, while persistence re-normalizes it
-// and swaps "another platform's default" literals for the local platform default.
-// The draft then never equaled the stored value again, so `hasChanges()` stayed true
-// forever: "Apply" looked like it did nothing and "Apply and Close" always asked
-// about unsaved changes — the shortcut (and every other pending edit) could never be
-// saved. The capture path must therefore write the same value the store will keep.
-describe("EditorSettingsDialog shortcut capture normalization", () => {
- it("round-trips a captured combination through the persistence normalizer", () => {
- expect(dialogSource).toContain("resolveCapturedShortcutEdit,");
- expect(dialogSource).toContain("const captured = resolveCapturedShortcutEdit(actionId, shortcut, editShortcuts.value);");
- });
-
- it("refuses combinations the store would rewrite, keeping the previous shortcut", () => {
- expect(dialogSource).toContain('toast(t("settings.shortcutPlatformDefault"), 3000);');
-
- const guardStart = dialogSource.indexOf("if (captured.rejectedByPlatformDefault) {");
- const guardEnd = dialogSource.indexOf("if (captured.changed) {", guardStart);
-
- expect(guardStart).toBeGreaterThan(-1);
- expect(guardEnd).toBeGreaterThan(guardStart);
- // 拒绝分支必须先结束编辑、且不得写入草稿(保留原值 → 草稿仍是落盘值的不动点)
- const guardBody = dialogSource.slice(guardStart, guardEnd);
- expect(guardBody).toContain("editingShortcutId.value = null;");
- expect(guardBody).toContain("return;");
- expect(guardBody).not.toContain("editShortcuts.value =");
- });
-
- it("adopts the normalized result so the draft can never diverge from the stored value", () => {
- expect(dialogSource).toContain("editShortcuts.value = captured.shortcuts;");
- });
-
- it("re-syncs the shortcut draft from the store after a successful apply", () => {
- const bodyStart = dialogSource.indexOf("async function persistSettings() {");
- const bodyEnd = dialogSource.indexOf("function applySettingsErrorToast(", bodyStart);
-
- expect(bodyStart).toBeGreaterThan(-1);
- expect(bodyEnd).toBeGreaterThan(bodyStart);
- expect(dialogSource.slice(bodyStart, bodyEnd)).toContain("editShortcuts.value = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCaptureInputWidth.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCaptureInputWidth.spec.ts
deleted file mode 100644
index 5e012ffb1a..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutCaptureInputWidth.spec.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// @vitest-environment happy-dom
-// Source-assertion regression for #9144: the shortcut-capture input width must
-// come from measuring a hidden mirror span (same box + typography as the real
-// inputs), not from `label.length + 2em` char-count arithmetic — CJK fallback
-// fonts can advance wider than 1em and clip the last placeholder glyph. The
-// dialog cannot be mounted (a 10k-line SFC whose imports pull the whole
-// editor + stores), so this follows the same `?raw` pattern as
-// EditorSettingsDialog.mcpQueryTimeout.integration.spec.ts.
-import { describe, expect, it } from "vitest";
-import dialogSource from "../EditorSettingsDialog.vue?raw";
-
-function templateOnly(): string {
- // The root <template> block, not the first "</template>" — this SFC is full
- // of nested slot <template> elements, so the first closing tag (and the
- // naive slice up to it) lands inside the template and misses most of it.
- return dialogSource.slice(dialogSource.search(/^<template>$/m), dialogSource.lastIndexOf("</template>"));
-}
-
-describe("EditorSettingsDialog shortcut capture input width (#9144)", () => {
- it("mounts exactly one hidden mirror span carrying the shared typography/box classes", () => {
- const template = templateOnly();
-
- // The ref token appears exactly once in the template: the mirror span.
- // (The two script occurrences are the ref declaration and the
- // useMeasuredWidth call.)
- expect(template.match(/shortcutPlaceholderMirrorRef/g)).toHaveLength(1);
- expect(dialogSource.match(/shortcutPlaceholderMirrorRef/g)).toHaveLength(3);
-
- // Same box + typography classes as the capture inputs so the measured
- // border-box width includes padding, border, letter-spacing and
- // fallback-font advances. Asserted against the span's own tag (not the
- // whole template) — the capture inputs share these classes, so a
- // template-wide match would pass even with the span stripped.
- const spanTag = template.match(/<span ref="shortcutPlaceholderMirrorRef"[^>]*>/)?.[0];
- expect(spanTag).toBeTruthy();
- for (const cls of ["font-mono", "text-[13px]", "font-semibold", "px-2.5", "border", "whitespace-pre", "invisible"]) {
- expect(spanTag).toContain(cls);
- }
-
- // The label must be interpolated in-band with the span tags, not as
- // template text between newlines — whitespace-pre would otherwise widen
- // the measured box.
- expect(template).toMatch(/<span ref="shortcutPlaceholderMirrorRef"[^>]*>\{\{ shortcutPressShortcutLabel \}\}<\/span>/);
- });
-
- it("binds all three capture inputs to the measured width ref", () => {
- // Two width bindings gate on the row-level editing state (formatter table
- // + shortcuts table), one on the SQL-shortcut dialog editing state. Each
- // conditional token appears in exactly one kind of binding.
- expect(dialogSource.match(/editingShortcutId === definition\.id \? shortcutPressShortcutInputWidth/g)).toHaveLength(2);
- expect(dialogSource.match(/editingSqlShortcutInputId === 'dialog' \? shortcutPressShortcutInputWidth/g)).toHaveLength(1);
-
- // Account for every usage of the width ref: 1 fallback initializer,
- // 1 watcher application, 3 capture-input bindings.
- expect(dialogSource.match(/shortcutPressShortcutInputWidth/g)).toHaveLength(5);
- });
-
- it("wires the measured width to the shared mirror ref with the label as revalidate source", () => {
- expect(dialogSource).toContain("useMeasuredWidth(shortcutPlaceholderMirrorRef, 0, [shortcutPressShortcutLabel])");
-
- // The applied width adds a ~2px cushion and rounds up so sub-pixel
- // rounding never under-sizes.
- expect(dialogSource).toContain("${Math.ceil(width) + 2}px");
- });
-
- it("keeps the char-count formula only as the ref fallback initializer", () => {
- // The legacy `length + 2em` estimate survives solely as the pre-measurement
- // initializer of the ref.
- expect(dialogSource).toContain("shortcutPressShortcutInputWidth = ref(`${shortcutPressShortcutLabel.value.length + 2}em`)");
-
- // No computed re-derives the width from char count anymore.
- expect(dialogSource).not.toMatch(/computed\(\(\) => `\$\{shortcutPressShortcutLabel\.value\.length \+ 2\}em`\)/);
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.integration.spec.ts
index 48c4f779bd..f49ac46dd4 100644
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.integration.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.integration.spec.ts
@@ -6,12 +6,11 @@ import { createPinia } from "pinia";
import { SHORTCUT_DEFINITIONS } from "@/lib/editor/shortcutRegistry";
import { formatShortcutDisplay } from "@/lib/editor/shortcutDisplay";
-// Reviewer follow-up to the source-contract spec
-// (EditorSettingsDialog.shortcutResetEditState.spec.ts): prove the actual UI
-// state transition for #9066 — entering a shortcut row's capture state and
-// clicking restore-defaults must return the row to its initial pill display,
-// for both the per-tab footer button and the About tab's full reset (whose
-// click path is reachable because the capture state survives tab switches).
+// Proves the actual UI state transition for #9066 — entering a shortcut row's
+// capture state and clicking restore-defaults must return the row to its
+// initial pill display, for both the per-tab footer button and the About tab's
+// full reset (whose click path is reachable because the capture state survives
+// tab switches).
vi.mock("vue-i18n", async () => {
const { ref } = await import("vue");
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.spec.ts
deleted file mode 100644
index b2f0e13bed..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutResetEditState.spec.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// Regression for https://github.com/t8y2/dbx/issues/9066: clicking a shortcut
-// row's edit button enters the per-row capture state (editingShortcutId), and
-// clicking the footer "restore defaults" button afterwards reset the shortcut
-// values but left the row stuck in the editing state ("press shortcut"
-// capture input still active). Restoring defaults must also exit the edit
-// mode so the row returns to its initial pill display. The clear happens at
-// the top of both reset entrypoints because the edit state can leak across
-// tab switches (the shortcuts and formatter tables share it).
-describe("EditorSettingsDialog shortcut restore-defaults exits edit state", () => {
- it("resetDefaultsForTab clears the in-progress shortcut capture before resetting values", () => {
- const head = dialogSource.slice(dialogSource.indexOf("function resetDefaultsForTab(tab: SettingsCategory) {"), dialogSource.indexOf('if (tab === "editor") {'));
- expect(head).toContain("editingShortcutId.value = null;");
- });
-
- it("resetAllDefaults clears the in-progress shortcut capture too", () => {
- const start = dialogSource.indexOf("function resetAllDefaults() {");
- const head = dialogSource.slice(start, dialogSource.indexOf("editFontFamily.value = DEFAULT_EDITOR_SETTINGS.fontFamily;", start));
- expect(head).toContain("editingShortcutId.value = null;");
- });
-
- it("keeps the footer restore-defaults button wired to resetDefaultsForTab", () => {
- expect(dialogSource).toContain('@click="resetDefaultsForTab(activeSettingsTab as SettingsCategory)"');
- expect(dialogSource).toContain('{{ t("settings.resetDefaults") }}');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.integration.spec.ts
index 63caed4456..bf5202159c 100644
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.integration.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.integration.spec.ts
@@ -6,13 +6,12 @@ import { createPinia } from "pinia";
import { DEFAULT_EDITOR_SETTINGS } from "@/stores/settingsStore";
import { SHORTCUT_DEFINITIONS } from "@/lib/editor/shortcutRegistry";
-// Behaviour proof for the scope-grouping / two-tier conflict work, on top of the
-// source-contract spec (EditorSettingsDialog.shortcutScopeGroups.spec.ts). The
+// Behaviour proof for the scope-grouping / two-tier conflict work. The
// load-bearing claim is the tier split:
// · L1 same-scope duplicate -> blocking (red pill, footer reason, Apply gate)
// · L2 cross-scope overlap -> informational only (amber pill, never blocking)
-// The source spec pins the wiring; this one drives the real rendered controls so
-// a wrong tier can't hide behind a passing string assertion.
+// This drives the real rendered controls so a wrong tier can't hide behind a
+// passing string assertion.
const hoisted = vi.hoisted(() => ({ shortcuts: {} as Record<string, string> }));
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.spec.ts
deleted file mode 100644
index 9ac768994f..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.shortcutScopeGroups.spec.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// The shortcuts tab groups its 78 actions by scope (global → editor → grid →
-// search → sidebar) and reports conflicts on two levels:
-// · same-scope duplicates → blocking (Apply stays disabled, pill turns red)
-// · cross-scope same chord → informational only (thin amber pill border)
-// These assertions pin the load-bearing parts of that split: cross-scope
-// overlaps must never reach the apply gate, the group order must keep matching
-// the runtime dispatch order, and the L1 red must win over the L2 amber.
-describe("EditorSettingsDialog shortcut scope grouping", () => {
- const shortcutsTab = dialogSource.slice(dialogSource.indexOf("activeSettingsTab === 'shortcuts'"), dialogSource.indexOf('data-settings-search-id="sql-shortcuts"'));
-
- it("groups the shortcuts tab by scope and drops the per-row scope badge", () => {
- expect(shortcutsTab).toContain('v-for="group in shortcutScopeGroups"');
- expect(shortcutsTab).toContain(':is="shortcutScopeIcon(group.scope)"');
- // The scope chip moved into the group header; rows must not repeat it
- // (the template literal lookup used by the old row badge is gone).
- expect(dialogSource).not.toContain("shortcutScope${definition.scope");
- });
-
- it("keeps the group order equal to the runtime dispatch order", () => {
- const order = dialogSource.slice(dialogSource.indexOf("const SHORTCUT_SCOPE_ORDER"), dialogSource.indexOf("function shortcutScopeLabelKey"));
- expect(order).toContain('["global", "editor", "grid", "search", "sidebar"]');
- });
-
- it("keeps same-scope conflicts blocking and cross-scope overlaps informational", () => {
- // L1 comes from findShortcutConflict only…
- const conflictMap = dialogSource.slice(dialogSource.indexOf("const shortcutConflictMap = computed"), dialogSource.indexOf("const shortcutConflicts = computed(() => Object.keys"));
- expect(conflictMap).toContain("findShortcutConflict(");
- expect(conflictMap).not.toContain("findCrossScopeShortcutConflicts");
- // …and the apply gate must not learn about the cross-scope tier.
- const blocker = dialogSource.slice(dialogSource.indexOf("const hasBlockingShortcutConflicts = computed"), dialogSource.indexOf("const hasBlockingFormatterConfig"));
- expect(blocker).toContain("hasShortcutConflicts.value || hasSqlShortcutConflicts.value");
- expect(blocker).not.toContain("crossScope");
- });
-
- it("explains a disabled Apply in the footer now that rows carry no inline message", () => {
- expect(dialogSource).toContain('v-if="hasBlockingShortcutConflicts"');
- expect(dialogSource).toContain('t("settings.shortcutConflictBlocksApply"');
- expect(shortcutsTab).not.toContain('{{ t("settings.shortcutConflict") }}');
- expect(shortcutsTab).toContain(':text="shortcutConflictHintText(definition)"');
- });
-
- it("lets the blocking red win over the informational amber on the pill", () => {
- // Both states tint the same pill; the cross-scope rule must exclude
- // aria-invalid rows, otherwise a row that is both would render amber.
- expect(dialogSource).toContain('.settings-shortcut-row[data-cross-scope="true"] .settings-shortcut-pill:not([aria-invalid="true"])');
- expect(dialogSource).toContain("border-color: color-mix(in srgb, var(--warning) 45%, transparent);");
- });
-
- it("keeps the capture pill's measured-width contract untouched", () => {
- // The non-editing pill branch is a separate, deliberate formula (see
- // .trellis/spec/dbx/frontend/keyboard-shortcuts.md, contract 5) — do not
- // unify it with the measured capture-input width.
- expect(shortcutsTab).toContain("Math.max(4, formatShortcutPill(editShortcuts[definition.id]).length + 3)}ch");
- expect(shortcutsTab).toContain("editingShortcutId === definition.id ? shortcutPressShortcutInputWidth");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.unsavedClose.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.unsavedClose.spec.ts
deleted file mode 100644
index 1ea130c2dd..0000000000
--- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.unsavedClose.spec.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-// Regression for https://github.com/t8y2/dbx/issues/5905: changing a shortcut
-// or the sidebar activation mode (and every other draft-gated editor
-// setting) was silently discarded whenever the dialog closed any way other
-// than the explicit "Apply"/"Apply and Close" buttons — Escape, clicking
-// outside, the X button, and every tab's "Close" footer button all bypassed
-// the draft entirely. Users only noticed after a later app restart (e.g. to
-// install an update) surfaced the still-default values, making it look like
-// the update itself had reset their settings.
-describe("EditorSettingsDialog unsaved-changes close guard", () => {
- it("imports the shared unsaved-changes decision helper", () => {
- // Keep in sync with the (oxfmt-formatted) multi-line import block in EditorSettingsDialog.vue.
- expect(dialogSource).toContain('shouldConfirmEditorSettingsDialogClose,\n type EditorSettingsDraft,\n type EditorSettingsDraftKey,\n} from "@/lib/settings/editorSettingsDraft"');
- });
-
- it("routes every close path through the same guard instead of emitting update:open directly", () => {
- expect(dialogSource).toContain("function requestCloseSettings(nextOpen: boolean) {");
- expect(dialogSource).toContain("if (shouldConfirmEditorSettingsDialogClose(nextOpen, hasChanges())) {");
- expect(dialogSource).toContain("showUnsavedSettingsCloseConfirm.value = true;");
-
- // Escape / outside click / the dialog's own X button
- expect(dialogSource).toContain("function onSettingsRootOpenChange(value: boolean) {\n if (isSettingsPage.value) return;\n requestCloseSettings(value);\n}");
- // Every tab footer's "Close" button — must work in both dialog and page
- // (variant="page") mode, since App.vue relies on closeSettings() emitting
- // update:open(false) in page mode too (see @update:open on EditorSettingsPage).
- expect(dialogSource).toContain("function closeSettings() {\n requestCloseSettings(false);\n}");
-
- // Neither close entrypoint may emit update:open directly anymore - only requestCloseSettings does.
- const closeSettingsBody = dialogSource.slice(dialogSource.indexOf("function closeSettings()"), dialogSource.indexOf("function cancelUnsavedSettingsClose()"));
- expect(closeSettingsBody).not.toContain('emit("update:open"');
- });
-
- it("lets the user cancel back into the dialog without losing the draft", () => {
- expect(dialogSource).toContain("function cancelUnsavedSettingsClose() {\n showUnsavedSettingsCloseConfirm.value = false;\n}");
- });
-
- it("only actually closes (dropping the draft) once the user explicitly confirms discarding", () => {
- expect(dialogSource).toContain('function discardUnsavedSettingsAndClose() {\n showUnsavedSettingsCloseConfirm.value = false;\n emit("update:open", false);\n}');
- });
-
- it("renders a confirmation dialog wired to the guard state and both actions", () => {
- expect(dialogSource).toContain('<Dialog :open="showUnsavedSettingsCloseConfirm" @update:open="(value: boolean) => !value && cancelUnsavedSettingsClose()">');
- expect(dialogSource).toContain('{{ t("settings.unsavedChangesCloseTitle") }}');
- expect(dialogSource).toContain('{{ t("settings.unsavedChangesCloseMessage") }}');
- expect(dialogSource).toContain('@click="cancelUnsavedSettingsClose"');
- expect(dialogSource).toContain('@click="discardUnsavedSettingsAndClose"');
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.cteNavigationWiring.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.cteNavigationWiring.spec.ts
deleted file mode 100644
index dd396b28d4..0000000000
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.cteNavigationWiring.spec.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-/**
- * CTE 接线(hover 溯源、Ctrl+点击跳转、语义模型缓存)分布在独立模块中。
- * 此处保留结构断言,模块行为另由 useQueryEditorHover 和
- * useQueryEditorObjectNavigation 的直接测试覆盖。
- *
- * 这里锁定回归成本最高的两类契约:分支先后顺序、关键调用参数。算法本身由
- * cteNavigation.spec.ts / model.spec.ts / sqlNavigation.spec.ts 覆盖。
- */
-const componentSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
-const source = [readFileSync(new URL("../useQueryEditorHover.ts", import.meta.url), "utf8"), readFileSync(new URL("../useQueryEditorObjectNavigation.ts", import.meta.url), "utf8")].join("\n");
-
-/** 截取模块中的函数体,避免跨函数误匹配。 */
-const metadataSource = readFileSync(new URL("../useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
-
-function functionBody(name: string): string {
- const functionSource = name === "getEditorSemanticModel" ? metadataSource : source;
- const start = functionSource.indexOf(`function ${name}(`);
- expect(start, `QueryEditor.vue 缺少函数 ${name}`).toBeGreaterThanOrEqual(0);
- const end = functionSource.indexOf("\n }", start);
- expect(end, `${name} 函数体未闭合`).toBeGreaterThan(start);
- return functionSource.slice(start, end);
-}
-
-function positionOf(fragment: string): number {
- const index = source.indexOf(fragment);
- expect(index, `QueryEditor.vue 缺少片段: ${fragment}`).toBeGreaterThanOrEqual(0);
- return index;
-}
-
-/**
- * 结构片段的归一化:去掉全部空白与"闭合前的尾逗号"。
- * oxfmt(lint-staged 钩子会执行)会在单行与多行之间重排数组/对象字面量,
- * 归一化后断言只对代码结构敏感,不会因为纯格式变动而误报。
- */
-function normalizeCode(text: string): string {
- return text.replace(/\s+/g, "").replace(/,(?=[)\]}])/g, "");
-}
-
-const normalizedSource = normalizeCode(source);
-
-/** 期望片段照常写成可读形式,比较时两侧一起归一化。 */
-function expectSourceToContain(fragment: string): void {
- expect(normalizedSource).toContain(normalizeCode(fragment));
-}
-
-describe("QueryEditor hover 的语义模型缓存接线", () => {
- it("连接独立的 hover 和对象导航入口及监听器生命周期", () => {
- expect(componentSource).toContain("hoverTooltip((currentView, pos) => resolveSqlHoverTooltip(currentView, pos))");
- expect(componentSource).toContain("mousedown: onEditorMouseDown");
- expect(componentSource).toContain("objectNavigation.attach();");
- expect(componentSource).toContain("objectNavigation.dispose();");
- });
- it("hover 复用 getEditorSemanticModel,而不是每次重新解析", () => {
- expect(source).toContain("semanticModel = getEditorSemanticModel(sql, pos, currentView.state);");
- // 换回逐次解析会让 hover 在每次移动时重复建模型(原实现即为此形态)。
- expect(source).not.toContain("buildSqlSemanticModel(sql, pos, sqlCompletionDialectOptions())");
- });
-
- it("缓存键覆盖文档/编辑器状态/位置/数据库类型/方言,且只在拿到 doc 时写缓存", () => {
- const body = functionBody("getEditorSemanticModel");
-
- expect(body).toContain("if (!SEMANTIC_SQL_COMPLETION_ENABLED) return null;");
- for (const key of ["editorSemanticModelCache?.doc === doc", "editorSemanticModelCache.editorState === editorState", "editorSemanticModelCache.position === position", "editorSemanticModelCache.databaseType === props.databaseType", "editorSemanticModelCache.dialect === dialect"]) {
- expect(body, `缓存键缺少 ${key}`).toContain(key);
- }
- // 没有 doc(手动构造的 state)时不能留下无法复用的缓存项。
- expect(body).toMatch(/if \(doc\) \{\s*editorSemanticModelCache = \{/);
- });
-});
-
-describe("QueryEditor hover 的 CTE 溯源接线", () => {
- it("CTE 分支排在通用表/列回退之前", () => {
- const cteBranch = positionOf("const cteColumn = await resolveCteColumnHoverColumn(semanticModel, name, qualifier);");
- const genericFallback = positionOf("const hoverTarget = completionMetadataTarget({");
-
- expect(cteBranch).toBeLessThan(genericFallback);
- });
-
- it("命中物理列后按 类型/来源/注释 生成悬浮内容,未命中则回退", () => {
- expectSourceToContain('createHoverDom(cteColumn.name, cteColumn.dataType || "column", undefined, [cteColumn.schema ? `${cteColumn.schema}.${cteColumn.table}` : cteColumn.table, ...(cteColumn.comment?.trim() ? [cteColumn.comment.trim()] : [])])');
- // 只有拿到列才提前返回,否则继续走原有表/列逻辑。
- expect(source).toContain("if (cteColumn) {");
- });
-});
-
-describe("resolveCteColumnHoverColumn 的溯源接线", () => {
- const body = functionBody("resolveCteColumnHoverColumn");
-
- it("未命中或不可溯源时返回 null,交由上层回退", () => {
- expect(body).toContain("const hit = findCteColumnResolution(semanticModel, columnName, qualifier);");
- expect(body).toContain("if (!hit) return null;");
- expect(body).toContain("const origins: CteColumnOrigin[] = resolveCteColumnOrigins(semanticModel, hit, columnName);");
- expect(body).toContain("if (origins.length === 0) return null;");
- // 元数据抓取异常同样只降级为回退,不能把 hover 打崩。
- expect(body).toMatch(/catch \{\s*return null;\s*\}/);
- });
-
- it("复用共享列缓存并做大小写不敏感匹配,取第一个命中", () => {
- expect(body).toContain("const reference = referencedTableLikeFromSemanticSource(origin.source);");
- expect(body).toContain("await ensureColumnsForTable(reference, reference);");
- expect(body).toContain("const columns = cachedColumnsByTable.get(completionCacheKey(reference));");
- expect(body).toContain("candidate.name.toLowerCase() === origin.column.toLowerCase()");
- expect(body).toContain("return matched.find((column) => column != null) ?? null;");
- });
-
- it("多星号产生的多个来源并发取元数据,顺序即优先级,第一个命中者胜出", () => {
- const body = functionBody("resolveCteColumnHoverColumn");
-
- // 顺序即优先级:谁先取到真实列元数据就用谁(歧义 SQL 的裁决点就在这里)。
- expect(body).toContain("origins.map(async (origin) => {");
- expect(body).toContain("?? null;");
- expect(body.indexOf("origins.map(async (origin) => {")).toBeLessThan(body.indexOf("return matched.find((column) => column != null) ?? null;"));
-
- // 第二个来源直接复用第一个来源已建好的缓存,不会重复发起元数据查询。
- expect(body).toContain("cachedColumnsByTable.get(completionCacheKey(reference))");
- });
-
- it("把语义来源映射成列缓存所需的表标识(含引号与 schema)", () => {
- const mapBody = functionBody("referencedTableLikeFromSemanticSource");
-
- expect(mapBody).toContain("const identifierParts = source.qualifiedName?.parts ?? [];");
- expect(mapBody).toContain("name: source.name,");
- expect(mapBody).toContain("nameQuoted: !!identifierParts[identifierParts.length - 1]?.quote,");
- expect(mapBody).toContain("database: source.metadataTarget?.database,");
- expect(mapBody).toContain("schema: source.qualifierParts[source.qualifierParts.length - 1],");
- expect(mapBody).toContain("schemaQuoted: source.qualifierParts.length > 0 ? !!identifierParts[identifierParts.length - 2]?.quote : undefined,");
- });
-});
-
-describe("QueryEditor Ctrl+点击的 CTE 跳转接线", () => {
- it("CTE 分支排在本地表缓存之前", () => {
- const cteBranch = positionOf("const cteModel = getEditorSemanticModel(doc, pos, currentView.state);");
- const localTableCache = positionOf("// 1. Local table lookup with the resolved scope");
-
- expect(source).toContain("// 0. CTE (WITH ... AS) in-editor navigation");
- expect(cteBranch).toBeLessThan(localTableCache);
- });
-
- it("CTE 引用名命中时跳到定义名 token,并高亮整个 CTE 定义", () => {
- expect(source).toContain("const referenceHit = findCteReferenceAt(cteModel, pos);");
- expect(source).toContain("if (referenceHit?.definition.nameSpan) {");
- expectSourceToContain("{ from: referenceHit.definition.nameSpan.start, to: referenceHit.definition.nameSpan.end }");
- expectSourceToContain("{ from: referenceHit.definition.sourceSpan.start, to: referenceHit.definition.sourceSpan.end }");
- });
-
- it("CTE 列命中时跳到 output 的 jumpSpan 或 body 星号,限定符取倒数列段", () => {
- expect(source).toContain("const clickQualifier = identity.parts.length >= 2 ? identity.parts[identity.parts.length - 2]?.value : undefined;");
- expect(source).toContain("const columnHit = findCteColumnResolution(cteModel, identity.name, clickQualifier);");
- expect(source).toContain("const columnTargetSpan = columnHit?.output?.jumpSpan ?? columnHit?.stars?.[0]?.starSpan;");
- expect(source).toContain("if (columnHit && columnTargetSpan) {");
- expectSourceToContain("{ from: columnTargetSpan.start, to: columnTargetSpan.end }");
- });
-
- it("解析失败只告警,不阻断后续表/列跳转", () => {
- expect(source).toContain('console.warn("[DBX] CTE ctrl+click resolution failed:", error);');
-
- const cteBlock = source.slice(positionOf("const cteModel = getEditorSemanticModel(doc, pos, currentView.state);"), positionOf("// 1. Local table lookup with the resolved scope"));
- // 两个成功分支各自提前 return;catch 分支只能 warn,否则会吞掉原有的表/列跳转。
- expect(cteBlock.match(/return;/g) ?? []).toHaveLength(2);
- expect(cteBlock).not.toMatch(/catch \(error\) \{[\s\S]*?return/);
- });
-});
-
-describe("jumpToCteRange 的跳转范围处理", () => {
- const body = functionBody("jumpToCteRange");
-
- it("缺少视图或 CodeMirror 模块时直接返回", () => {
- expect(body).toContain("if (!currentView || !codeMirrorRuntime.editorViewModule || !codeMirrorRuntime.setResultSourceRangeEffect) return;");
- });
-
- it("把目标与高亮范围都收敛到文档长度内", () => {
- expect(body).toContain("const docLength = currentView.state.doc.length;");
- expect(body).toContain("const targetFrom = Math.max(0, Math.min(target.from, docLength));");
- expect(body).toContain("const targetTo = Math.max(targetFrom, Math.min(target.to, docLength));");
- expect(body).toContain("const highlightFrom = Math.max(0, Math.min(highlight.from, docLength));");
- expect(body).toContain("const highlightTo = Math.max(highlightFrom, Math.min(highlight.to, docLength));");
- });
-
- it("空目标不动光标,命中时选中目标 token 并高亮整个定义块", () => {
- expect(body).toContain("if (targetFrom >= targetTo) return;");
- expect(normalizeCode(body)).toContain(normalizeCode("selection: { anchor: targetFrom, head: targetTo }"));
- expectSourceToContain("codeMirrorRuntime.setResultSourceRangeEffect.of({ from: highlightFrom, to: highlightTo })");
- expectSourceToContain('codeMirrorRuntime.editorViewModule.EditorView.scrollIntoView(targetFrom, { y: "center" })');
- expect(body).toContain("currentView.focus();");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.imeCompletionAcceptance.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.imeCompletionAcceptance.spec.ts
deleted file mode 100644
index f44e46ac80..0000000000
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.imeCompletionAcceptance.spec.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const editorSource = readFileSync(new URL("../useQueryEditorCompletionKeys.ts", import.meta.url), "utf8");
-
-function functionSource(name: string) {
- const start = editorSource.indexOf(`function ${name}(`);
- const end = editorSource.indexOf("\n }", start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return editorSource.slice(start, end);
-}
-
-// Regression test for #8029: while an IME composition is active, Enter and the
-// completion-accept shortcut belong to the IME candidate list. The acceptance
-// handlers gate on the same isEditorComposing helper the completion providers
-// already use, and the delayed retries must drop their queued acceptance once
-// a composition starts instead of accepting over (or after) it.
-describe("QueryEditor IME-safe completion acceptance", () => {
- it("gates the Enter handler on IME composition before any acceptance", () => {
- const source = functionSource("handleEnter");
- const composingGuard = source.indexOf("if (isEditorComposing(view)) return false;");
- const acceptCall = source.indexOf("codeMirrorAcceptCompletion?.(view)");
-
- expect(composingGuard).toBeGreaterThanOrEqual(0);
- expect(acceptCall).toBeGreaterThan(composingGuard);
- });
-
- it("gates the Tab completion-accept handler on IME composition", () => {
- const source = functionSource("acceptCompletionOrNextSnippetField");
- const composingGuard = source.indexOf("if (isEditorComposing(view)) return false;");
- const selectionCheck = source.indexOf("view.state.selection.ranges.every");
-
- expect(composingGuard).toBeGreaterThanOrEqual(0);
- expect(selectionCheck).toBeGreaterThan(composingGuard);
- });
-
- it("drops the pending Tab acceptance retry when an IME composition starts", () => {
- const source = functionSource("waitForCompletionTab");
- const retry = source.indexOf("const retry = () => {");
- const composingGuard = source.indexOf("if (isEditorComposing(view)) return;", retry);
-
- expect(retry).toBeGreaterThanOrEqual(0);
- expect(composingGuard).toBeGreaterThan(retry);
- });
-
- it("passes an IME guard to the Enter acceptance retry helper", () => {
- const source = functionSource("handleEnter");
- expect(source.includes("isComposing: () => isEditorComposing(view)")).toBe(true);
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.sqlServerRoutineDiagnosticsWiring.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.sqlServerRoutineDiagnosticsWiring.spec.ts
deleted file mode 100644
index 30a9b01a7b..0000000000
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.sqlServerRoutineDiagnosticsWiring.spec.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-/**
- * SQL Server 例程批次的语法诊断接线(#9315)写在诊断 composable 内部,
- * 无法直接 import,因此沿用仓库既有做法(QueryEditor.cteNavigationWiring.spec.ts)
- * 对源码做结构断言。规则本身由 sqlServerRoutineSyntaxDiagnostics.test.ts 覆盖,
- * 批次/视口裁剪由 sqlSemanticDiagnostics.test.ts 覆盖,这里只锁定接线契约。
- */
-const source = readFileSync(new URL("../useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
-
-function normalizeCode(text: string): string {
- return text.replace(/\s+/g, "").replace(/,(?=[)\]}])/g, "");
-}
-
-const normalizedSource = normalizeCode(source);
-
-function expectSourceToContain(fragment: string): void {
- expect(normalizedSource).toContain(normalizeCode(fragment));
-}
-
-describe("QueryEditor 的 SQL Server 例程语法诊断接线", () => {
- it("例程批次被跳过整个语义范围后仍单独取回", () => {
- // sqlSemanticDiagnosticRangesForViewport 对例程批次返回空,所以必须再取一次。
- expectSourceToContain('const sqlServerRoutineRanges = props.databaseType === "sqlserver" ? sqlServerRoutineDefinitionRangesForViewport(sql, visibleRanges) : [];');
- // 例程批次不能因为普通范围为空就提前 return,否则过程体永远不检查。
- expectSourceToContain("if (diagnosticRanges.length === 0 && sqlServerRoutineRanges.length === 0) {");
- });
-
- it("例程批次只跑 token 规则,不做引用分析", () => {
- expectSourceToContain("nextDiagnostics.push(...offsetSqlSemanticDiagnostics(buildSqlServerRoutineSyntaxDiagnostics(range.sql, props.databaseType), range, sql));");
- });
-
- it("增量刷新时把例程批次一并纳入替换范围,避免旧诊断残留", () => {
- expectSourceToContain("replaceSemanticDiagnosticsInRanges(nextDiagnostics, [...diagnosticRanges, ...sqlServerRoutineRanges], sql);");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditorContextMenu.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditorContextMenu.spec.ts
index 9e7f06ab14..d3c7e3cefb 100644
--- a/apps/desktop/src/components/editor/__tests__/QueryEditorContextMenu.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/QueryEditorContextMenu.spec.ts
@@ -1,83 +1,10 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import path from "node:path";
import { computed, createApp, defineComponent, h, nextTick, ref } from "vue";
import { describe, expect, it } from "vitest";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
-const source = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/QueryEditor.vue"), "utf8");
-
-const menuSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/QueryEditorContextMenu.vue"), "utf8");
-
-const documentSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
-const batchSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts"), "utf8");
-
-const completionSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorCompletion.ts"), "utf8");
-const completionKeysSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorCompletionKeys.ts"), "utf8");
-const extensionsSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/queryEditorSqlExtensions.ts"), "utf8");
-
describe("QueryEditor context menu lifecycle", () => {
- it("keeps heavyweight context derivation out of the per-update path", () => {
- const updateStart = source.indexOf("EditorView.updateListener.of((update) => {");
- const updateEnd = source.indexOf("initializedRuntime.fontThemeComp.of(", updateStart);
- const updateSource = source.slice(updateStart, updateEnd);
-
- expect(updateStart).toBeGreaterThanOrEqual(0);
- expect(updateEnd).toBeGreaterThan(updateStart);
- expect(updateSource).toContain("syncEditorSelectionState(update.view);");
- expect(updateSource).toContain("schedulePreviewContextRefresh(update.view);");
- expect(updateSource).not.toContain("syncContextMenuState(update.view);");
- });
-
- it("does not suppress legitimate external model updates", () => {
- expect(source).not.toContain("lastEmittedModelValue");
- expect(documentSource).toContain("if (val !== currentEditorDocText(view.value)) {");
- });
-
- it("resynchronizes context state after restoring a tab document", () => {
- const activateStart = documentSource.indexOf("function activateTabDocument");
- const activateEnd = documentSource.indexOf("\n watch([() => props.tabId", activateStart);
- const activateSource = documentSource.slice(activateStart, activateEnd);
-
- expect(activateStart).toBeGreaterThanOrEqual(0);
- expect(activateEnd).toBeGreaterThan(activateStart);
- expect(activateSource).toContain("syncContextMenuState(currentView);");
- expect(activateSource).toContain('emit("previewChangesAvailable", !!previewContextSql.value);');
- });
-
- it("guards deferred preview refresh against stale selection ranges", () => {
- expect(source).toContain("const expectedSelection = currentView.state.selection.main;");
- expect(source).toContain("currentSelection.from !== expectedSelection.from");
- expect(source).toContain("currentSelection.to !== expectedSelection.to");
- });
-
- it("resolves menu items after synchronizing the right-click target", () => {
- const syncStart = source.indexOf("function syncContextMenuStateAtEvent");
- const syncEnd = source.indexOf("\n}", syncStart);
- const syncSource = source.slice(syncStart, syncEnd);
- const syncIndex = source.indexOf("syncContextMenuStateAtEvent(view, e);");
- const openIndex = source.indexOf("onContextMenu(e);", syncIndex);
- const getterStart = menuSource.indexOf("function currentContextMenuItems()");
- const getterEnd = menuSource.indexOf("\n}", getterStart);
- const getterSource = menuSource.slice(getterStart, getterEnd);
-
- expect(syncStart).toBeGreaterThanOrEqual(0);
- expect(syncEnd).toBeGreaterThan(syncStart);
- expect(syncSource).toContain("if (pos == null)");
- expect(syncSource).toContain("contextObjectTarget.value = null;");
- expect(syncIndex).toBeGreaterThanOrEqual(0);
- expect(openIndex).toBeGreaterThan(syncIndex);
- expect(getterStart).toBeGreaterThanOrEqual(0);
- expect(getterEnd).toBeGreaterThan(getterStart);
- expect(getterSource).toContain("return contextMenuItems.value;");
- expect(getterSource).not.toContain("nextTick");
- expect(getterSource).not.toContain("setTimeout");
- expect(menuSource).toContain(':items="currentContextMenuItems"');
- expect(source).toContain(':get-state="getContextMenuState"');
- expect(menuSource).not.toContain('<CustomContextMenu :items="contextMenuItems"');
- });
-
it("uses the target synchronized in the current context-menu event", async () => {
const target = ref<string | null>(null);
const openedTargets: string[] = [];
@@ -142,70 +69,3 @@ describe("QueryEditor context menu lifecycle", () => {
container.remove();
});
});
-
-describe("QueryEditor batch column selection", () => {
- it("keeps the confirmation action visible during pinyin filtering and supports keyboard toggling", () => {
- const bypassFilterStart = completionSource.indexOf("function completionItemsForBypassedFilter");
- const bypassFilterEnd = completionSource.indexOf("\n }\n\n function localCompletionDatabaseNames", bypassFilterStart);
- const bypassFilterSource = completionSource.slice(bypassFilterStart, bypassFilterEnd);
-
- expect(bypassFilterStart).toBeGreaterThanOrEqual(0);
- expect(bypassFilterEnd).toBeGreaterThan(bypassFilterStart);
- expect(bypassFilterSource).toContain("if (isBatchColumnSelectionAction(item)) return true;");
- expect(source).toContain('key: "Space"');
- expect(source).toContain("run: toggleSelectedBatchColumnSelection");
- expect(completionKeysSource).toContain("codeMirrorSelectedCompletion?.(view.state)");
- });
-
- it("applies checked columns directly through Enter and the completion Tab shortcut", () => {
- const handleEnterStart = completionKeysSource.indexOf("function handleEnter");
- const handleEnterEnd = completionKeysSource.indexOf("\n }", handleEnterStart);
- const tabStart = completionKeysSource.indexOf("function acceptCompletionOrNextSnippetField");
- const tabEnd = completionKeysSource.indexOf("\n }", tabStart);
-
- expect(batchSource).toContain("function applySelectedBatchColumnSelection");
- expect(completionKeysSource.slice(handleEnterStart, handleEnterEnd)).toContain("if (isBatchColumnSelectionCompletionActive(codeMirrorRuntime.codeMirrorCompletionStatus?.(view.state) ?? null) && applySelectedBatchColumnSelection(view)) return true;");
- expect(completionKeysSource.slice(handleEnterStart, handleEnterEnd)).toContain("if (codeMirrorRuntime.codeMirrorAcceptCompletion?.(view)) return true;");
- expect(completionKeysSource.slice(tabStart, tabEnd)).toContain("if (isBatchColumnSelectionCompletionActive(completionStatus) && applySelectedBatchColumnSelection(view)) return true;");
- expect(extensionsSource).toContain("defaultKeymap: false");
- expect(source).toContain('{ key: "ArrowDown", run: (view) => moveCompletion(view, true) }');
- expect(source).toContain('{ key: "ArrowUp", run: (view) => moveCompletion(view, false) }');
- });
-
- it("marks the insertion action so the completion menu can keep it sticky", () => {
- expect(completionSource).toContain("dbxBatchColumnSelectionAction: { sessionKey: item.sessionKey, ...(item.batchColumnSelectionToggleAll ? { toggleAll: true as const } : {}) }");
- expect(extensionsSource).toContain('optionClass: (completion) => ((completion as QueryCompletionOption).dbxBatchColumnSelectionAction ? "cm-batch-column-selection-action" : "")');
- });
-
- it("updates the insertion count while a mouse selection is still in progress", () => {
- const dragUpdateStart = batchSource.indexOf("function updateBatchColumnSelectionAtPoint");
- const dragUpdateEnd = batchSource.indexOf("\n }\n\n const BATCH_COLUMN_SELECTION_AUTO_SCROLL_EDGE_PX", dragUpdateStart);
-
- expect(batchSource).toContain("function updateBatchColumnSelectionActionLabel");
- expect(batchSource.slice(dragUpdateStart, dragUpdateEnd)).toContain("updateBatchColumnSelectionActionLabel(state.view, state.sessionKey);");
- expect(batchSource).toContain("const batchColumnSelectionTooltipParents = new WeakMap<EditorViewType, HTMLElement>();");
- expect(batchSource).toContain("batchColumnSelectionTooltipParents.set(currentView, tooltipParent);");
- expect(batchSource).toContain("const batchColumnSelectionActionMarkers = new WeakMap<HTMLElement, { sessionKey: string; toggleAll: boolean }>();");
- expect(batchSource).toContain("!markerState || markerState.sessionKey !== sessionKey");
- expect(batchSource).toContain("renderBatchColumnSelectionActionMarker");
- });
-
- it("cancels stale scroll restoration before a new drag can begin", () => {
- const refreshStart = batchSource.indexOf("function scheduleBatchColumnSelectionRefresh");
- const refreshEnd = batchSource.indexOf("\n }\n\n function finishBatchColumnSelectionDrag", refreshStart);
- const dragStart = batchSource.indexOf("function startBatchColumnSelectionDrag");
- const dragEnd = batchSource.indexOf("\n }\n\n function renderBatchColumnSelectionCheckbox", dragStart);
-
- expect(batchSource).toContain("let batchColumnSelectionRefreshCleanup: (() => void) | null = null;");
- expect(batchSource.slice(refreshStart, refreshEnd)).toContain("cancelBatchColumnSelectionRefresh();");
- expect(batchSource.slice(dragStart, dragEnd)).toContain("cancelBatchColumnSelectionRefresh();");
- expect(batchSource).toContain("if (restoreStartTimer) window.clearTimeout(restoreStartTimer);");
- });
-
- it("only expands rendering for batch field selection", () => {
- expect(batchSource).toContain("function setBatchColumnSelectionExpandedRendering");
- expect(batchSource).toContain("setBatchColumnSelectionExpandedRendering(true);");
- expect(batchSource).toContain("setBatchColumnSelectionExpandedRendering(false);");
- expect(extensionsSource).toContain("maxRenderedOptions: batchSelection.expandedRendering ? Number.MAX_SAFE_INTEGER : 100,");
- });
-});
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditorGotoLineWiring.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditorGotoLineWiring.spec.ts
deleted file mode 100644
index 3aa8f3bea6..0000000000
--- a/apps/desktop/src/components/editor/__tests__/QueryEditorGotoLineWiring.spec.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const queryEditorSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
-
-describe("QueryEditor goto-line wiring", () => {
- it("binds the platform goto-line shortcut next to find, before formatSql", () => {
- const gotoLineIndex = queryEditorSource.indexOf("...binding(shortcuts.gotoLine, openGotoLine),");
- const findIndex = queryEditorSource.indexOf("...binding(shortcuts.find, openSearch),");
- const formatIndex = queryEditorSource.indexOf("...binding(shortcuts.formatSql,");
-
- expect(findIndex).toBeGreaterThan(-1);
- expect(gotoLineIndex).toBeGreaterThan(findIndex);
- // 非 mac 上 Ctrl+G 同时是 CodeMirror 内置的 find-next,运行时的 Prec.high
- // keymap 先匹配先执行,因此跳转绑定必须注册在搜索键位之前。
- expect(formatIndex).toBeGreaterThan(gotoLineIndex);
- });
-
- it("routes the panel toggles through the exposed handles", () => {
- expect(queryEditorSource).toContain("function openGotoLine(): boolean {\n return gotoLinePanelRef.value?.openGotoLine() ?? false;\n}");
- expect(queryEditorSource).toContain('<EditorGotoLinePanel ref="gotoLinePanelRef" :view="view" @open="searchPanelRef?.closeSearch()" />');
- expect(queryEditorSource).toContain('<EditorSearchPanel ref="searchPanelRef" :view="view" @open="gotoLinePanelRef?.closeGotoLine()" />');
- });
-});
diff --git a/apps/desktop/src/components/etcd/__tests__/EtcdDashboardConcurrency.spec.ts b/apps/desktop/src/components/etcd/__tests__/EtcdDashboardConcurrency.spec.ts
deleted file mode 100644
index 147e0c598d..0000000000
--- a/apps/desktop/src/components/etcd/__tests__/EtcdDashboardConcurrency.spec.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dashboardSource = readFileSync(new URL("../EtcdDashboard.vue", import.meta.url), "utf8");
-
-describe("EtcdDashboard refresh concurrency", () => {
- it("skips overlapping refreshes for the same connection", () => {
- expect(dashboardSource).toContain("if (loading.value && loadingConnectionId === connectionId) return");
- });
-
- it("discards responses from an obsolete load generation", () => {
- expect(dashboardSource).toContain("const generation = ++loadGeneration");
- expect(dashboardSource).toContain("if (generation !== loadGeneration || props.connectionId !== connectionId) return");
- });
-});
diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanNodeTree.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanNodeTree.spec.ts
index 288dc712a4..7567ee13ca 100644
--- a/apps/desktop/src/components/explain/__tests__/ExplainPlanNodeTree.spec.ts
+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanNodeTree.spec.ts
@@ -1,8 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { readCascadeCss } from "../../../styles/__tests__/cascadeCss";
-const nodeTreeSource = readFileSync(new URL("../ExplainPlanNodeTree.vue", import.meta.url), "utf8");
const globalStyles = readCascadeCss();
type Rgb = [number, number, number];
@@ -61,43 +59,6 @@ function blend(foreground: Rgb, background: Rgb, opacity: number): Rgb {
}
describe("ExplainPlanNodeTree interactions", () => {
- it("keeps a concise preview of the most useful details in the tree row", () => {
- expect(nodeTreeSource).toContain('const detailPreviewEntries = computed(() => detailEntries.value.filter((detail) => detail.label !== "Actual Rows").slice(0, 2))');
- expect(nodeTreeSource).toContain('<div v-if="detailPreviewEntries.length"');
- expect(nodeTreeSource).toContain('v-for="(detail, index) in detailPreviewEntries"');
- expect(nodeTreeSource).toContain('class="min-w-0 flex-1 truncate"');
- expect(nodeTreeSource).not.toContain("text-muted-foreground/40");
- });
-
- it("shows long details in a click-triggered, selectable popover", () => {
- expect(nodeTreeSource).toContain('import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"');
- expect(nodeTreeSource).toContain('<Popover v-if="detailEntries.length">');
- expect(nodeTreeSource).toContain("<PopoverTrigger as-child>");
- expect(nodeTreeSource).toContain('<PopoverContent align="end"');
- expect(nodeTreeSource).toContain('data-native-clipboard class="max-h-');
- expect(nodeTreeSource).toContain("select-text whitespace-pre-wrap break-words");
- expect(nodeTreeSource).not.toContain("node.details.join");
- expect(nodeTreeSource).not.toContain("{{ detailEntries.length }}");
- expect(nodeTreeSource.match(/\{\{ t\("explain\.details"\) \}\}/g)).toHaveLength(1);
- });
-
- it("keeps detail fields distinct and tree disclosure on its own button", () => {
- expect(nodeTreeSource).toContain('const separatorIndex = detail.indexOf(":")');
- expect(nodeTreeSource).toContain('v-if="detail.label"');
- expect(nodeTreeSource).toContain('<Button v-if="hasChildren"');
- expect(nodeTreeSource).toContain(':aria-expanded="!collapsed"');
- expect(nodeTreeSource).toContain('@click="toggleCollapsed"');
- expect(nodeTreeSource).not.toContain("cursor-pointer");
- expect(nodeTreeSource).not.toContain('@click="toggle"');
- });
-
- it("uses semantic foreground tokens instead of fixed status hues", () => {
- expect(nodeTreeSource).toContain("text-foreground/80");
- expect(nodeTreeSource).toContain("text-popover-foreground");
- expect(nodeTreeSource).not.toMatch(/text-(?:blue|emerald|amber|green)-/);
- expect(nodeTreeSource).not.toMatch(/border-(?:blue|emerald|amber|green)-/);
- });
-
it("keeps foreground-based tree metadata readable in every application palette", () => {
expect(themeColors).toHaveLength(26);
diff --git a/apps/desktop/src/components/export/__tests__/DatabaseExportDialog.destinationIdentity.spec.ts b/apps/desktop/src/components/export/__tests__/DatabaseExportDialog.destinationIdentity.spec.ts
deleted file mode 100644
index 805c9d9194..0000000000
--- a/apps/desktop/src/components/export/__tests__/DatabaseExportDialog.destinationIdentity.spec.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../DatabaseExportDialog.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string) {
- const start = dialogSource.indexOf(`async function ${name}(`);
- const end = dialogSource.indexOf(`async function ${nextName}(`, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return dialogSource.slice(start, end);
-}
-
-describe("DatabaseExportDialog destination identity", () => {
- it("records a manually selected file destination before starting a single-database export", () => {
- const source = functionSource("startExport", "startAllDatabasesExport");
- const selectedPath = source.indexOf("const path = await save(");
- const recordedDestination = source.indexOf("recordDatabaseExportDestination(await dirname(path))");
- const exportStarted = source.indexOf("isExporting.value = true");
-
- expect(selectedPath).toBeGreaterThanOrEqual(0);
- expect(recordedDestination).toBeGreaterThan(selectedPath);
- expect(exportStarted).toBeGreaterThan(recordedDestination);
- });
-
- it("records a manually selected directory before starting an all-databases export", () => {
- const source = functionSource("startAllDatabasesExport", "cancelExport");
- const selectedPath = source.indexOf("const path = await openDialog(");
- const recordedDestination = source.indexOf("recordDatabaseExportDestination(path)");
- const exportStarted = source.indexOf("isExporting.value = true");
-
- expect(selectedPath).toBeGreaterThanOrEqual(0);
- expect(recordedDestination).toBeGreaterThan(selectedPath);
- expect(exportStarted).toBeGreaterThan(recordedDestination);
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts
index 8c4566198b..e182bfc477 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -493,16 +491,4 @@ describe("DataGrid multi-row paste from a blank cell", () => {
expect(updates).toEqual([{ $set: { status: "{plain text" } }, { $set: { status: "{plain text" } }]);
});
-
- it("routes DOM and canvas cell gestures through the same selection preparation", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
- const domGesture = source.slice(source.indexOf('@mousedown="\n prepareDataCellMouseDown'), source.indexOf('@mouseenter="onCellMouseenter'));
- const canvasGesture = source.slice(source.indexOf("function onCanvasMouseDown"), source.indexOf("function onCanvasContext"));
-
- expect(domGesture).toContain("prepareDataCellMouseDown(item, col.actualColIdx);");
- expect(domGesture).toContain("handleDataCellMousedown(item.displayIndex, col.visibleColIdx, item.id, $event);");
- expect(canvasGesture).toContain("prepareDataCellMouseDown(item, actualColIdx)");
- expect(canvasGesture).toContain("handleDataCellMousedown(item.displayIndex, hit.visibleColIdx, item.id, event)");
- expect(source).toContain("columnIndexes: visibleColumnIndexes.value.slice(range.startCol)");
- });
});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridCellDetailSelection.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridCellDetailSelection.spec.ts
deleted file mode 100644
index e33ef81d27..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridCellDetailSelection.spec.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-const largeValueSource = readFileSync(new URL("../../../composables/useDataGridLargeValues.ts", import.meta.url), "utf8");
-
-describe("DataGrid cell detail selection", () => {
- it("selects the first available cell when opening Mongo JSON preview without a selection", () => {
- const togglePreview = dataGridSource.match(/function toggleMongoJsonPreview[\s\S]*?\n\}/)?.[0];
- expect(togglePreview).toContain("if (showMongoJsonPreview.value)");
- expect(togglePreview).toContain("!currentSelectedCellPosition() && displayItems.value.length > 0 && visibleColumnIndexes.value.length > 0");
- expect(togglePreview).toContain("selectSingleCell(0, 0)");
- });
-
- it("keeps Canvas hover state while the renderer swaps drawing surfaces", () => {
- expect(dataGridSource).toContain("function isCanvasGridInteractionTarget(target: Node): boolean");
- expect(dataGridSource).toContain("canvasOverlayRef.value?.contains(target) === true");
- expect(dataGridSource).toContain("canvasRef.value?.contains(target) === true");
- expect(dataGridSource).toContain("canvasBackRef.value?.contains(target) === true");
-
- const canvasLeave = dataGridSource.match(/function onCanvasMouseLeave[\s\S]*?\n\}/)?.[0];
- const detailLeave = dataGridSource.match(/function clearCanvasDetailHover[\s\S]*?\n\}/)?.[0];
- expect(canvasLeave).toContain("isCanvasGridInteractionTarget(relatedTarget)");
- expect(detailLeave).toContain("isCanvasGridInteractionTarget(relatedTarget)");
- });
-
- it("gates only the three hover Info buttons with the visibility setting", () => {
- expect(dataGridSource).toContain("const cellDetailButtonEnabled = computed(() => settingsStore.editorSettings.dataGridCellDetailButtonVisible);");
- expect(dataGridSource.match(/v-if="cellDetailButtonEnabled"/g)).toHaveLength(3);
- expect(dataGridSource.match(/v-if="cellDetailButtonVisible\(/g)).toHaveLength(2);
-
- const hoverVisibility = dataGridSource.match(/function cellDetailButtonVisible[\s\S]*?\n\}/)?.[0];
- expect(hoverVisibility).toBeDefined();
- expect(hoverVisibility).not.toContain("dataGridCellDetailButtonVisible");
- });
-
- it("removes the Canvas action overlay and reservation only when no action remains", () => {
- expect(dataGridSource).toContain("if (!cellDetailButtonEnabled.value && !canQuickDownload && !foreignKey && !externalUrl) return null;");
- expect(dataGridSource).toContain("canvasDataGridActionOverlayWidth(canQuickDownload, !!foreignKey, cellDetailButtonEnabled.value, !!externalUrl)");
- expect(dataGridSource).toContain("canvasDataGridActionOverlayWidth(cell.canQuickDownload, !!cell.foreignKey, cellDetailButtonEnabled.value, !!cell.externalUrl)");
- expect(dataGridSource).toContain("canvasDataGridActionReservedWidth(cell.canQuickDownload, !!cell.foreignKey, cellDetailButtonEnabled.value, !!cell.externalUrl)");
- expect(dataGridSource).toMatch(/watch\([\s\S]*?cellDetailButtonEnabled,[\s\S]*?scheduleCanvasDraw/);
- });
-
- it("keeps context-menu details and refresh restoration independent of the hover setting", () => {
- expect(dataGridSource).toContain("cellDetails: openContextCellDetailDialog");
- expect(dataGridSource).toContain("if (cellDialog) openCellDetailDialog(cellDialog.rowIndex, cellDialog.col);");
- });
-
- it("resynchronizes the open detail after a mouse selection gesture finishes", () => {
- expect(dataGridSource).toContain("watch([selectedRange, showCellDetail, isEditingDetail, isSelectingCells]");
- expect(dataGridSource).toContain("if (isSelectingCells.value) return;");
- expect(dataGridSource).toMatch(/detailCell\.value = target;\s+hydrateCellDetailTarget\(target\);/);
- });
-
- it("hydrates bounded large-value previews for every cell detail target", () => {
- expect(largeValueSource).toContain("function isLargeValuePreview");
- expect(dataGridSource).toContain("function hydrateLargeValueCell");
- expect(dataGridSource).toMatch(/showCellDetails[\s\S]*?hydrateCellDetailTarget\(detailCell\.value\)/);
- expect(dataGridSource).toMatch(/openCellDetailDialog[\s\S]*?hydrateCellDetailTarget\(cellDetailDialogTarget\.value\)/);
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridColumnOrderSelection.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridColumnOrderSelection.spec.ts
deleted file mode 100644
index d73b8ead5e..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridColumnOrderSelection.spec.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-describe("DataGrid synchronized column order selection", () => {
- it("reconciles the active selection when another grid changes the table order", () => {
- expect(dataGridSource).toContain("applyColumnOrderChange(() => onTableDataGridColumnOrderChanged(event));");
- expect(dataGridSource).toContain("window.addEventListener(TABLE_DATA_GRID_COLUMN_ORDER_CHANGED_EVENT, onSynchronizedTableDataGridColumnOrderChanged);");
- expect(dataGridSource).toContain("window.removeEventListener(TABLE_DATA_GRID_COLUMN_ORDER_CHANGED_EVENT, onSynchronizedTableDataGridColumnOrderChanged);");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
index 52d83fca33..8e35053e31 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
@@ -1,8 +1,6 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import DataGridConditionEditor from "@/components/grid/DataGridConditionEditor.vue";
import type { DataGridConditionHistoryKind } from "@/lib/dataGrid/dataGridConditionHistory";
@@ -258,97 +256,6 @@ describe("DataGridConditionEditor quote completion", () => {
expect(document.querySelector('[role="listbox"]')).toBeNull();
});
- it("keeps the wrapped input caret aligned with its syntax highlight layer", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const expandedInputCss = source.match(/\.data-grid-topbar-condition-input--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
- const expandedHighlightCss = source.match(/\.data-grid-condition-highlight--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
- const prefixPadding = "calc(var(--data-grid-condition-prefix-indent) + 0.125rem)";
-
- expect(expandedInputCss).toContain("padding:");
- expect(expandedInputCss).toContain(prefixPadding);
- expect(expandedHighlightCss).toContain(prefixPadding);
- expect(expandedInputCss).not.toContain("text-indent:");
- expect(expandedHighlightCss).not.toContain("text-indent:");
- expect(expandedInputCss).toContain("overflow-wrap: anywhere");
- expect(source).toContain("white-space:pre-wrap;overflow-wrap:anywhere;");
- expect(source).not.toContain("textIndent: rect.prefix");
- expect(source).toContain("paddingLeft: rect.prefix + 2");
- expect(source).toContain("paddingRight: rect.suffix + 8");
- expect(source).toContain("width: Math.max(1, rect.width - 8)");
- expect(source).toContain("function fitExpandedHeightToOverlay()");
- expect(source).toContain("expandedHeight.value + overflow");
- });
-
- it("keeps the expanded condition label readable over wrapped content", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const floatingControls = source.match(/data-grid-topbar-condition-floating-controls[^"]*/)?.[0];
- const floatingLabelCss = source.match(/\.data-grid-topbar-condition-label--floating\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
- const compactFloatingLabelCss = source.match(/\.data-grid-topbar-condition-label--floating\.data-grid-topbar-condition-label--compact\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
-
- expect(floatingControls).toContain("z-[2]");
- expect(source).toContain("data-grid-topbar-condition-label--floating");
- expect(source).toContain("label.scrollWidth + 4");
- expect(floatingLabelCss).toContain("text-shadow:");
- expect(floatingLabelCss).not.toContain("padding-right:");
- expect(floatingLabelCss).not.toContain("box-shadow:");
- expect(compactFloatingLabelCss).toContain("max-width: 5rem");
- expect(compactFloatingLabelCss).toContain("opacity: 1");
- });
-
- it("keeps dark condition styles scoped to their target elements", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
-
- expect(source).not.toContain(":global(.dark) .data-grid");
- expect(source).toContain(":global(.dark .data-grid-topbar-condition-label--floating)");
- expect(source).toContain(":global(.dark .data-grid-topbar-condition-pane--expanded)");
- });
-
- it("scrolls the caret into view after accepting a long completion", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
-
- expect(source).toContain("function scrollCaretIntoView()");
- expect(source).toContain("const hasVerticalOverflow = target.scrollHeight > target.clientHeight + 4");
- expect(source).toContain("const hasHorizontalOverflow = target.scrollWidth > target.clientWidth + 1");
- expect(source).toContain("target.scrollTop = 0");
- expect(source).toContain("const caretLeft = caretMarker.offsetLeft");
- expect(source).toContain("target.scrollLeft");
- expect(source).toContain("function scheduleCaretIntoView()");
- expect(source).toContain("function focusAfterAccept()");
- expect(source).toContain("requestAnimationFrame(() => scrollCaretIntoView())");
- expect(source).toContain("scheduleCaretIntoView()");
- expect(source).toContain('if (action === "accept") focusAfterAccept()');
- });
-
- it("also keeps the caret visible after regular input wraps", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const onInputBody = source.match(/function onInput\(event: Event\) \{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
-
- expect(onInputBody).toContain("resizeEditor(true)");
- expect(onInputBody).toContain("updateSuggestionPosition()");
- expect(onInputBody).toContain("scheduleCaretIntoView()");
- });
-
- it("keeps the caret visible after switching focus into the expanded editor", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const focusTransferBody = source.match(/if \(nextExpanded && document\.activeElement === input && !composing\.value\) \{(?<body>[\s\S]*?)\n \}/)?.groups?.body;
-
- expect(focusTransferBody).toContain("const start = selectionStart.value");
- expect(focusTransferBody).toContain("overlay.setSelectionRange(start, end)");
- expect(focusTransferBody).toContain("overlay.focus({ preventScroll: true })");
- expect(focusTransferBody).toContain("scheduleCaretIntoView()");
- });
-
- it("keeps the caret visible after collapsing the expanded editor back to one line", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const collapseTransferBody = source.match(/if \(!nextExpanded && overlayFocused && !composing\.value\) \{(?<body>[\s\S]*?)\n \}/)?.groups?.body;
-
- expect(collapseTransferBody).toContain("const start = selectionStart.value");
- expect(collapseTransferBody).toContain("input.setSelectionRange(start, end)");
- expect(collapseTransferBody).toContain("input.focus({ preventScroll: true })");
- expect(collapseTransferBody!.indexOf("input.focus({ preventScroll: true })")).toBeLessThan(collapseTransferBody!.indexOf("input.setSelectionRange(start, end)"));
- expect(collapseTransferBody).toContain("scheduleCaretIntoView()");
- });
-
it("preserves continuous input when the expanded editor collapses", async () => {
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
const textWidth = (this.textContent?.length ?? 0) * 8;
@@ -472,15 +379,6 @@ describe("DataGridConditionEditor quote completion", () => {
expect(expandedHighlight?.style.transform).toBe("translate(0px, 0px)");
vi.unstubAllGlobals();
});
-
- it("positions suggestions below the measured expanded editor height", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
- const expandedPaneCss = source.match(/\.data-grid-topbar-condition-pane--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
-
- expect(source).toContain("bottom: expandedRect.value.top + expandedHeight.value");
- expect(expandedPaneCss).toContain("transition: box-shadow 150ms ease");
- expect(expandedPaneCss).not.toContain("height 150ms");
- });
});
describe("DataGridConditionEditor Chinese column matching", () => {
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridDdlSearch.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridDdlSearch.spec.ts
deleted file mode 100644
index 28600980f8..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridDdlSearch.spec.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-const metadataLoaderSource = readFileSync(new URL("../../../composables/useDataGridTableMetadataLoaders.ts", import.meta.url), "utf8");
-
-describe("DataGrid DDL search navigation", () => {
- it("resets navigation when the raw search query changes", () => {
- expect(dataGridSource).toMatch(/watch\(\s*searchQuery,\s*async \(\) => \{\s*ddlSearchMatchIndex\.value = 0;/);
- });
-
- it("highlights the DDL once and marks the rendered DOM for the search", () => {
- // #9212: re-highlighting (and re-parsing) the whole DDL on every keystroke
- // froze the window, so the highlighted HTML only depends on the DDL itself
- // and the search marks are applied to the already-rendered <pre>.
- expect(dataGridSource).toMatch(/const highlightedDdlContent = computed\(\(\) => \(ddlContent\.value \? highlight\(ddlContent\.value\) : ""\)\);/);
- expect(dataGridSource).toContain('v-html="highlightedDdlContent"');
- expect(dataGridSource).toContain('import { applyDdlSearchMarks } from "@/lib/sql/ddlSearchMarks"');
- expect(dataGridSource).not.toContain("filteredDdlContent");
- expect(dataGridSource.match(/applyDdlSearchMarks\(ddlPreRef\.value, searchQuery\.value\)/g) ?? []).toHaveLength(3);
- });
-
- it("uses the shared DDL cache policy and exposes refresh controls", () => {
- expect(metadataLoaderSource).toContain('from "@/lib/metadata/objectDdlCache"');
- expect(metadataLoaderSource).toContain("async function fetchDdl(force = options.settingsStore.editorSettings.refreshDdlOnOpen)");
- expect(metadataLoaderSource).toMatch(/objectType: tableObjectSourceKind\(props\.tableMeta\.tableType\)/);
- expect(metadataLoaderSource).toContain("loadObjectDdl(request, { force })");
- expect(dataGridSource).toMatch(/async function refreshActiveTableInfo\(\)[\s\S]*?fetchDdl\(true\)[\s\S]*?fetchTableInfoColumns\(true\)[\s\S]*?fetchIndexes\(\)[\s\S]*?fetchForeignKeys\(\)[\s\S]*?fetchConstraints\(\)[\s\S]*?fetchTriggers\(\)/);
- expect(dataGridSource).toContain('@click="refreshActiveTableInfo"');
- expect(metadataLoaderSource).toMatch(/loadObjectMetadataFacet\(request, "columns"/);
- expect(dataGridSource).toMatch(/activeTableInfoTab\.value === "constraints"\) return constraintsLoading\.value/);
- expect(dataGridSource).not.toContain("setTableInfoRefreshDdlOnOpen");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridDetailNavigation.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridDetailNavigation.spec.ts
index e1c184bd43..e7f16c280d 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridDetailNavigation.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridDetailNavigation.spec.ts
@@ -1,10 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { adjacentDataGridDetailIndex, detailNavigationDelta, shouldIgnoreDataGridDetailNavigation } from "../../../lib/dataGrid/dataGridDetailNavigation";
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-const detailDialogsSource = readFileSync(new URL("../DataGridDetailDialogs.vue", import.meta.url), "utf8");
-
function keyboardEvent(overrides: Partial<KeyboardEvent> = {}): KeyboardEvent {
return {
key: "ArrowDown",
@@ -25,12 +21,6 @@ function targetMatching(selectorPart: string): EventTarget {
return { closest: (selector: string) => (selector.includes(selectorPart) ? {} : null) } as unknown as EventTarget;
}
-function functionBody(source: string, name: string, nextName: string): string {
- const start = source.indexOf(`function ${name}`);
- const end = source.indexOf(`function ${nextName}`, start + 1);
- return start >= 0 && end > start ? source.slice(start, end) : "";
-}
-
describe("DataGrid detail navigation index", () => {
it("follows the supplied displayed order instead of deriving neighboring ids", () => {
const displayedRows = [42, 7, 99];
@@ -89,44 +79,4 @@ describe("DataGrid detail keyboard safety", () => {
expect(shouldIgnoreDataGridDetailNavigation(keyboardEvent({ ctrlKey: true }))).toBe(true);
expect(shouldIgnoreDataGridDetailNavigation(keyboardEvent({ defaultPrevented: true }))).toBe(true);
});
-
- it("wires row and column intents to the displayed DataGrid order", () => {
- expect(detailDialogsSource).toContain('@keydown="onRowDetailKeydown"');
- expect(detailDialogsSource).toContain('@keydown="onColumnDetailKeydown"');
- expect(detailDialogsSource).toContain("shouldIgnoreDataGridDetailNavigation(event)");
- expect(detailDialogsSource).toContain('detailNavigationDelta(event.key, "row")');
- expect(detailDialogsSource).toContain('detailNavigationDelta(event.key, "column")');
- expect(detailDialogsSource).toContain('emit("navigateRow", delta)');
- expect(detailDialogsSource).toContain('emit("navigateColumn", delta)');
- expect(dataGridSource).toContain('@navigate-row="navigateRowDetail"');
- expect(dataGridSource).toContain('@navigate-column="navigateColumnDetail"');
-
- const rowNavigation = functionBody(dataGridSource, "navigateRowDetail", "navigateColumnDetail");
- const columnNavigation = functionBody(dataGridSource, "navigateColumnDetail", "openContextRowDetailDialog");
-
- expect(rowNavigation).toContain("displayRowIndexById(rowDetailDialogRowId.value)");
- expect(rowNavigation).toContain("displayItemAt(nextRowIndex)");
- expect(rowNavigation).not.toMatch(/rowDetailDialogRowId\.value\s*[+-]/);
- expect(columnNavigation).toContain("visibleColumnIndexes.value.indexOf(columnDetailDialogColumnIndex.value)");
- expect(columnNavigation).toContain("visibleColumnIndexes.value[nextColumnPosition]");
- expect(columnNavigation).not.toMatch(/columnDetailDialogColumnIndex\.value\s*[+-]/);
- });
-
- it("keeps the dialog open while replacing the detail target and guards closed dialogs", () => {
- const rowNavigation = functionBody(dataGridSource, "navigateRowDetail", "navigateColumnDetail");
- const columnNavigation = functionBody(dataGridSource, "navigateColumnDetail", "openContextRowDetailDialog");
-
- expect(rowNavigation).toContain("if (!rowDetailDialogOpen.value || rowDetailDialogRowId.value === null) return;");
- expect(columnNavigation).toContain("if (!columnDetailDialogOpen.value || columnDetailDialogColumnIndex.value === null) return;");
- expect(rowNavigation).not.toContain("rowDetailDialogOpen.value = false");
- expect(columnNavigation).not.toContain("columnDetailDialogOpen.value = false");
- expect(detailDialogsSource).toContain('const rowSearch = ref("");');
- expect(detailDialogsSource).toContain('const columnSearch = ref("");');
- });
-
- it("focuses the dialog content on open so arrows work immediately", () => {
- expect(detailDialogsSource).toContain('@open-auto-focus="focusDetailDialogContentOnOpen"');
- expect(detailDialogsSource).toContain('tabindex="-1"');
- expect(detailDialogsSource).toContain("function focusDetailDialogContentOnOpen(event: Event) {");
- });
});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridExternalResultScroll.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridExternalResultScroll.spec.ts
deleted file mode 100644
index 379785049f..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridExternalResultScroll.spec.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function resultWatchSource(): string {
- const start = dataGridSource.indexOf("watch(\n () => props.result,\n (result, previousResult) => {");
- const end = dataGridSource.indexOf("// --- Context menu handlers ---");
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return dataGridSource.slice(start, end);
-}
-
-function captureViewportAnchorForRefreshSource(): string {
- const start = dataGridSource.indexOf("function captureViewportAnchorForRefresh()");
- const end = dataGridSource.indexOf("function restoreViewportAnchorAfterRefresh(");
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return dataGridSource.slice(start, end);
-}
-
-describe("DataGrid result-replacement vertical scroll", () => {
- it("resets to the first row when the result is replaced without an internal grid action", () => {
- const watchSource = resultWatchSource();
-
- expect(watchSource).toContain("} else if (!inPlaceRefreshPending) {");
- const externalBranch = watchSource.slice(watchSource.indexOf("} else if (!inPlaceRefreshPending) {"));
- expect(externalBranch.indexOf("resetGridVerticalScroll();")).toBeGreaterThanOrEqual(0);
- expect(externalBranch).toContain("#7341");
- });
-
- it("keeps the internal-action reset flag path unchanged", () => {
- const watchSource = resultWatchSource();
-
- expect(watchSource).toContain("if (getResetScrollAfterResult()) {\n clearResetScrollAfterResult();\n resetGridVerticalScroll();");
- });
-
- it("treats any pending prepareFullReload marker as an in-place refresh that keeps the viewport", () => {
- const watchSource = resultWatchSource();
-
- expect(watchSource).toContain("preservedSelectionOnNextResult !== null || preservedViewportAnchorOnNextResult !== null || preservedDetailsOnNextResult !== null || preserveTransposeOnNextResult.value");
- // The pending-marker check must run before the watch consumes the markers.
- const pendingCheck = watchSource.indexOf("const inPlaceRefreshPending =");
- const selectionConsume = watchSource.indexOf("preservedSelectionOnNextResult = null;");
- const anchorConsume = watchSource.indexOf("preservedViewportAnchorOnNextResult = null;");
- const detailsConsume = watchSource.indexOf("preservedDetailsOnNextResult = null;");
- const transposeConsume = watchSource.indexOf("preserveTransposeOnNextResult.value = false;");
- expect(pendingCheck).toBeGreaterThanOrEqual(0);
- for (const consume of [selectionConsume, anchorConsume, detailsConsume, transposeConsume]) {
- expect(consume).toBeGreaterThan(pendingCheck);
- }
- });
-
- it("returns before any scroll reset when the replacement completes an infinite-scroll append", () => {
- const watchSource = resultWatchSource();
-
- const appendReturn = watchSource.indexOf("if (appendCompletion) {");
- const appendEarlyReturn = watchSource.indexOf("return;\n }");
- const resetBranch = watchSource.indexOf("if (getResetScrollAfterResult()) {");
- expect(appendReturn).toBeGreaterThanOrEqual(0);
- expect(appendEarlyReturn).toBeGreaterThan(appendReturn);
- expect(resetBranch).toBeGreaterThan(appendEarlyReturn);
- });
-
- it("does not anchor a toolbar refresh to the current top row when already scrolled to the top (#8339)", () => {
- // Anchoring the row that happens to be at scrollTop 0 would re-pin it to the
- // same on-screen offset after refresh, which pushes newly inserted rows
- // (e.g. rows prepended by an external insert under a DESC sort) above the
- // visible viewport instead of showing them. Skipping the anchor when already
- // at the top lets the toolbar-refresh path land on the freshest first row.
- const anchorSource = captureViewportAnchorForRefreshSource();
-
- expect(anchorSource).toContain("#8339");
- const guard = anchorSource.indexOf("if (scroller.scrollTop <= 0) return null;");
- const rowHeightUse = anchorSource.indexOf("const rowHeight =");
- expect(guard).toBeGreaterThanOrEqual(0);
- expect(rowHeightUse).toBeGreaterThan(guard);
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridGoToColumnShortcut.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridGoToColumnShortcut.spec.ts
index d3c3c6ff82..47b0101077 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridGoToColumnShortcut.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridGoToColumnShortcut.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -29,8 +27,6 @@ vi.mock("@/composables/useDataGridColumnResize", async (importOriginal) => {
import DataGrid from "../DataGrid.vue";
import { useSettingsStore } from "@/stores/settingsStore";
-const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
-const appSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/App.vue"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
const RecycleScroller = defineComponent({
@@ -147,12 +143,6 @@ afterEach(() => {
}
});
-function functionBody(name: string, nextName: string): string {
- const start = dataGridSource.indexOf(`function ${name}`);
- const end = dataGridSource.indexOf(`function ${nextName}`, start + 1);
- return start >= 0 && end > start ? dataGridSource.slice(start, end) : "";
-}
-
describe("DataGrid go-to-column shortcut", () => {
it("switches between the split and original single-row toolbar layouts", async () => {
const { host, settingsStore } = mountGrid();
@@ -299,61 +289,4 @@ describe("DataGrid go-to-column shortcut", () => {
expect(bubbled).toHaveBeenCalledOnce();
expect(goToColumnButton(host).getAttribute("aria-expanded")).toBe("false");
});
-
- it("opens the existing popover through the shared grid action", () => {
- const keydown = functionBody("onGridKeydown", "copyDetailValue");
-
- expect(dataGridSource).toMatch(/<div\b(?=[^>]*\bdata-grid-root)(?=[^>]*\btabindex="0")(?=[^>]*@keydown="onGridKeydown")[^>]*>/);
- expect(keydown).toMatch(
- /const targetAllowsNativeClipboard = eventTargetAllowsNativeClipboard\(event\);[\s\S]*?if \(!targetAllowsNativeClipboard && isGoToColumnShortcut\(event, settingsStore\.editorSettings\.shortcuts\) && openGoToColumn\(\)\) \{[\s\S]*?event\.preventDefault\(\);[\s\S]*?event\.stopPropagation\(\);[\s\S]*?return;[\s\S]*?\}/,
- );
- expect(dataGridSource).toContain("function openGoToColumn(): boolean");
- expect(dataGridSource).toContain("if (!displayableColumnIndexes.value.length) return false;");
- });
-
- it("keeps editable targets available for the application-level fallback", () => {
- const keydown = functionBody("onGridKeydown", "copyDetailValue");
- const shortcutStart = keydown.indexOf("if (!targetAllowsNativeClipboard && isGoToColumnShortcut");
- const shortcutEnd = keydown.indexOf("if (isFocusSearchShortcut", shortcutStart);
- const shortcutBranch = keydown.slice(shortcutStart, shortcutEnd);
-
- expect(shortcutStart).toBeGreaterThan(-1);
- expect(shortcutBranch).not.toContain("else");
- expect(shortcutBranch.match(/preventDefault/g)).toHaveLength(1);
- expect(shortcutBranch.match(/stopPropagation/g)).toHaveLength(1);
- });
-
- it("gives the data-tab fallback priority over conflicting global shortcuts", () => {
- const keydown = functionBody("onGridKeydown", "copyDetailValue");
-
- expect(keydown).toMatch(/if \(isFocusSearchShortcut\(event\) && !isGoToColumnShortcut\(event, settingsStore\.editorSettings\.shortcuts\)\)/);
- expect(appSource).toMatch(
- /const shortcuts = settingsStore\.editorSettings\.shortcuts;[\s\S]*?if \(showTabSwitcher\.value\) return;[\s\S]*?if \(isGoToColumnShortcut\(e, shortcuts\) && contentAreaRef\.value\?\.openGoToColumn\(\)\) \{[\s\S]*?return;[\s\S]*?const tabSwitcherDirection = tabSwitcherDirectionFromShortcut\(e, shortcuts\);/,
- );
- });
-
- it("keeps toolbar navigation and adds keyboard selection to the lookup", () => {
- const selectColumn = functionBody("scrollToColumn", "onGoToColumnKeydown");
- const escape = functionBody("onGoToColumnKeydown", "matchesTableInfoColumn");
- const scroll = functionBody("scrollToColumnIndex", "measureColumnHeaderText");
-
- expect(dataGridSource.match(/<Popover v-model:open="goToColumnOpen">/g)).toHaveLength(1);
- expect(dataGridSource).toContain('>{{ t("grid.goToColumn") }}</span');
- expect(dataGridSource).toContain('v-model="goToColumnSearch"');
- expect(dataGridSource).toContain('ref="goToColumnSearchInput"');
- expect(dataGridSource).toContain('ref="goToColumnListRef"');
- expect(dataGridSource).toContain("filterDataGridColumnLookupItems(goToColumnItems.value, goToColumnSearch.value)");
- expect(dataGridSource).toContain("const goToColumnSelectedIndex = ref(0);");
- expect(selectColumn).toContain('goToColumnSearch.value = ""');
- expect(selectColumn).toContain("scrollToColumnIndex(columnIndex)");
- expect(escape).toMatch(/event\.key === "ArrowDown"[\s\S]*?moveGoToColumnSelection\(1\)/);
- expect(escape).toMatch(/event\.key === "ArrowUp"[\s\S]*?moveGoToColumnSelection\(-1\)/);
- expect(escape).toMatch(/event\.key === "Enter"[\s\S]*?scrollToColumn\(selected\.index\)/);
- expect(escape).toMatch(/event\.key === "Escape"[\s\S]*?goToColumnOpen\.value = false;[\s\S]*?goToColumnSearch\.value = ""/);
- expect(scroll).toContain("if (hiddenColumnIndexes.value.has(columnIndex))");
- expect(scroll).toContain("showColumn(columnIndex)");
- expect(scroll).toContain("highlightedColumnIndex.value = columnIndex");
- expect(scroll).toContain("scroller.scrollLeft = targetLeft");
- expect(scroll).toContain("updateGridHorizontalViewport(scroller)");
- });
});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridInfiniteScrollSort.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridInfiniteScrollSort.spec.ts
deleted file mode 100644
index 3efa0d252c..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridInfiniteScrollSort.spec.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string): string {
- const start = dataGridSource.indexOf(`function ${name}`);
- const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
- expect(start).toBeGreaterThanOrEqual(0);
- expect(relativeEnd).toBeGreaterThan(0);
- const end = start + relativeEnd;
- return dataGridSource.slice(start, end);
-}
-
-describe("DataGrid infinite-scroll sorting", () => {
- it("clears completed and pending infinite-scroll state before database sorting", () => {
- const sortSource = functionSource("applyColumnSort", "selectHeaderSort");
- const resetSource = functionSource("resetInfiniteScrollState", "onToolbarRefresh");
-
- expect(sortSource).toContain('if (mode === "database" && infiniteScrollEnabled.value) {\n resetInfiniteScrollState();');
- expect(resetSource).toContain("lastInfiniteScrollPage = 0;");
- expect(resetSource).toContain("infiniteScrollAllLoaded = false;");
- expect(resetSource).toContain("infiniteScrollRequestedOffset = undefined;");
- expect(resetSource).toContain("infiniteScrollRequestedLimit = undefined;");
- expect(resetSource).toContain("isInfiniteScrollPaginating.value = false;");
- expect(resetSource).toContain("infiniteScrollLoading.value = false;");
- });
-
- it("preserves the existing lightweight reset for local sorting", () => {
- const sortSource = functionSource("applyColumnSort", "selectHeaderSort");
-
- expect(sortSource).toContain("} else {\n currentPage.value = 1;\n resetGridVerticalScroll(true);\n }");
- expect(sortSource.match(/emit\("sort"/g)).toHaveLength(1);
- });
-
- it("does not expose an explicit local sort as a database order for refresh or pagination", () => {
- const orderSource = functionSource("currentOrderBy", "executeServerPageJump");
-
- expect(orderSource).toContain('sortMode.value === "database"');
- expect(orderSource).toContain("return orderByInput.value.trim() || structuredOrderBy;");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridInitializationOrder.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridInitializationOrder.spec.ts
deleted file mode 100644
index 4d92edde88..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridInitializationOrder.spec.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-describe("DataGrid setup initialization order", () => {
- it("initializes table column metadata before column width measurement", () => {
- const tableColumnMetadataDeclaration = dataGridSource.indexOf("const tableColumnsByResultIndex = computed");
- const columnResizeInitialization = dataGridSource.indexOf("useDataGridColumnResize({");
-
- expect(tableColumnMetadataDeclaration).toBeGreaterThanOrEqual(0);
- expect(columnResizeInitialization).toBeGreaterThan(tableColumnMetadataDeclaration);
- });
-
- it("initializes column formatters before measuring formatted column widths", () => {
- const columnFormatterDeclaration = dataGridSource.indexOf("} = useDataGridColumnFormatter({");
- const columnWidthInitialization = dataGridSource.lastIndexOf("initColumnWidths();");
-
- expect(columnFormatterDeclaration).toBeGreaterThanOrEqual(0);
- expect(columnWidthInitialization).toBeGreaterThan(columnFormatterDeclaration);
- expect(dataGridSource).toContain("columnFormatterForWidth?.(columnIndex)");
- });
-
- it("initializes where-search capability before the immediate filter preview watcher", () => {
- const canUseWhereSearchDeclaration = dataGridSource.indexOf("const canUseWhereSearch = computed");
- const filterPreviewDeclaration = dataGridSource.indexOf("const filterPreviewVisible = computed");
- const filterPreviewWatcher = dataGridSource.indexOf("[filterPreviewVisible, structuredFilterRules]");
-
- expect(canUseWhereSearchDeclaration).toBeGreaterThanOrEqual(0);
- expect(filterPreviewDeclaration).toBeGreaterThan(canUseWhereSearchDeclaration);
- expect(filterPreviewWatcher).toBeGreaterThan(filterPreviewDeclaration);
- });
-
- it("does not expose an uninitialized large-value runtime to startup callbacks", () => {
- expect(dataGridSource).toContain("let largeValueRuntime: ReturnType<typeof useDataGridLargeValues> | undefined;");
- expect(dataGridSource).toContain("largeValueRuntime?.scheduleVisibleLargeValuePreviewHydration(delay)");
- expect(dataGridSource).toContain("largeValueRuntime?.hydrateLargeValueCell(rowId, columnIndex) ?? false");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridInlineBulkEdit.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridInlineBulkEdit.spec.ts
index 19f53a388c..df166f2d17 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridInlineBulkEdit.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridInlineBulkEdit.spec.ts
@@ -1,15 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { bulkEditInputToSqlValue, dataGridInlineBulkEditValue } from "@/lib/dataGrid/dataGridInlineBulkEdit";
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function functionBody(name: string, nextName: string): string {
- const start = dataGridSource.indexOf(`function ${name}`);
- const end = dataGridSource.indexOf(`function ${nextName}`, start + 1);
- return start >= 0 && end > start ? dataGridSource.slice(start, end) : "";
-}
-
describe("DataGrid inline bulk editing", () => {
it.each([
["1", "1"],
@@ -27,18 +18,6 @@ describe("DataGrid inline bulk editing", () => {
it.each([{ key: "v", ctrlKey: true }, { key: "1", altKey: true }, { key: "删", isComposing: true }, { key: "删", keyCode: 229 }, { key: "Process" }])("ignores shortcut, composition, and control keys: %j", (event) => {
expect(dataGridInlineBulkEditValue(event, 2)).toBeUndefined();
});
-
- it("starts a cell editor instead of opening the bulk edit dialog", () => {
- const keydown = functionBody("onGridKeydown", "copyDetailValue");
- expect(keydown).toContain("beginInlineBulkEdit(inlineBulkEditValue)");
- expect(keydown).not.toContain("openBulkEditDialog");
- });
-
- it("commits the inline value to the full selection", () => {
- const commit = functionBody("commitInlineBulkEdit", "commitBooleanGridEdit");
- expect(commit).toContain("fillSelectionWithValue(nextValue, { emptyStringAsNull: true })");
- expect(commit).toContain("cancelEdit()");
- });
});
describe("bulkEditInputToSqlValue", () => {
@@ -49,10 +28,4 @@ describe("bulkEditInputToSqlValue", () => {
it.each(["0", "false", "NULLL", "NULLX", "'NULL'", "nulls", "NUL", " 1 "])("keeps non-sentinel input %j as typed", (input) => {
expect(bulkEditInputToSqlValue(input)).toBe(input);
});
-
- it("routes applyBulkEditValue through bulkEditInputToSqlValue for both scopes", () => {
- const applyBulkEdit = functionBody("applyBulkEditValue", "confirmConditionalBulkEdit");
- expect(applyBulkEdit).toContain("bulkEditInputToSqlValue(bulkEditValue.value)");
- expect(applyBulkEdit).not.toContain('bulkEditValue.value === "" ? null');
- });
});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReloadSql.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReloadSql.spec.ts
deleted file mode 100644
index ba3c803155..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReloadSql.spec.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-const largeValueSource = readFileSync(new URL("../../../composables/useDataGridLargeValues.ts", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string): string {
- const start = largeValueSource.indexOf(`function ${name}`);
- const relativeEnd = largeValueSource.slice(start).search(new RegExp(`\\n\\s*(?:async\\s+)?function\\s+${nextName}\\b`));
- expect(start).toBeGreaterThanOrEqual(0);
- expect(relativeEnd).toBeGreaterThan(0);
- return largeValueSource.slice(start, start + relativeEnd);
-}
-
-describe("DataGrid large-value reload SQL", () => {
- it("projects the synthetic rowid through the rowid-wrapped select on full-value reloads", () => {
- const fetchChunkSource = functionSource("fetchLargeValueRequestChunk", "resolveLargeValueCells");
-
- // Keyless Oracle tables address rows via the hidden __DBX_ROWID alias; the
- // reload must opt into the ROWIDTOCHAR inline view so the generated SQL
- // never references __DBX_ROWID as a base-table column (ORA-00904).
- expect(fetchChunkSource).toContain("includeRowId: shouldIncludeSyntheticRowId(options.databaseType.value, tableMeta.primaryKeys, tableMeta.tableType)");
- });
-
- it("keeps the visible-preview hydration consistent with the synthetic key", () => {
- const hydrateSource = functionSource("hydrateVisibleLargeValuePreviews", "runVisibleLargeValuePreviewHydration");
-
- expect(hydrateSource).toContain("includeRowId: shouldIncludeSyntheticRowId(options.databaseType.value, tableMeta.primaryKeys, tableMeta.tableType)");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReplace.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReplace.spec.ts
deleted file mode 100644
index f287040361..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridLargeValueReplace.spec.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string): string {
- const start = dataGridSource.indexOf(`function ${name}`);
- const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
- expect(start).toBeGreaterThanOrEqual(0);
- expect(relativeEnd).toBeGreaterThan(0);
- return dataGridSource.slice(start, start + relativeEnd);
-}
-
-describe("DataGrid large-value replacement", () => {
- it("counts preview matches and resolves full values before staging replacements", () => {
- const eligibilitySource = functionSource("canReplaceGridCell", "replacementCellInScope");
- const replaceSource = functionSource("replaceGridMatches", "fillSelectionWithValue");
-
- expect(eligibilitySource).not.toContain("!isLargeValuePreview");
- expect(replaceSource).toContain("await prepareDataGridCellReplacements");
- expect(replaceSource).toContain("resolveLargeValueCells");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts
index 801b0ac62f..e9a1438162 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -30,7 +28,6 @@ vi.mock("@/composables/useDataGridColumnResize", async (importOriginal) => {
import DataGrid from "../DataGrid.vue";
import { useSettingsStore } from "@/stores/settingsStore";
-const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
const shortcutCases = [
{ actionId: "goToFirstPage", key: "F1", offset: 0, functionName: "firstPage" },
@@ -300,16 +297,6 @@ describe("DataGrid pagination shortcuts", () => {
expect(paginate).not.toHaveBeenCalled();
});
- it("routes shortcuts to the existing pagination functions and preserves PageUp/PageDown navigation", () => {
- expect(dataGridSource).toMatch(/if \(!targetAllowsNativeClipboard && handleGridPaginationShortcut\(event\)\) return;/);
- for (const { actionId, functionName } of shortcutCases) {
- expect(dataGridSource).toContain(`is${actionId[0]!.toUpperCase()}${actionId.slice(1)}Shortcut(event, shortcuts)`);
- expect(dataGridSource).toContain(`navigate = ${functionName}`);
- }
- expect(dataGridSource).toContain('event.key === "PageUp" && navigateSelectedCell("pageUp", event.shiftKey)');
- expect(dataGridSource).toContain('event.key === "PageDown" && navigateSelectedCell("pageDown", event.shiftKey)');
- });
-
it("keeps legacy settings without pagination mappings keyboard-neutral", async () => {
const { host, paginate } = mountGrid({ configurePaginationShortcuts: false });
await settle();
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridPendingRowFilterVisibility.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridPendingRowFilterVisibility.spec.ts
deleted file mode 100644
index 46d9ab8194..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridPendingRowFilterVisibility.spec.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-describe("DataGrid pending row visibility under local column filters", () => {
- it("keeps pending new rows visible while a local column filter is active", () => {
- // The pending-row branch of displayRowRefs must not consult the local
- // column filter matchers; only the row status filter applies (#9201).
- expect(dataGridSource).toMatch(/const row = newRows\.value\[newIndex\];[\s\S]{0,200}?if \(!row\) continue;/);
- expect(dataGridSource).not.toContain("!rowMatchesLocalColumnFilters(row)");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridReadonlyTextSelection.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridReadonlyTextSelection.spec.ts
index f2d4dc2011..09b574a794 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridReadonlyTextSelection.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridReadonlyTextSelection.spec.ts
@@ -1,13 +1,10 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { createApp, nextTick } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import DataGridReadonlyTextSelection from "../DataGridReadonlyTextSelection.vue";
const mountedRoots: HTMLDivElement[] = [];
-const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
function mountSelection(options: { value?: string; expanded?: boolean } = {}) {
const root = document.createElement("div");
@@ -30,14 +27,6 @@ afterEach(() => {
});
describe("DataGridReadonlyTextSelection", () => {
- it("closes a stale read-only selection when a result is replaced", () => {
- const resultWatcher = dataGridSource.match(/watch\(\s*\(\) => props\.result,\s*\(result, previousResult\) => \{[\s\S]*?\n\);/)?.[0] ?? "";
-
- expect(resultWatcher).toContain("const appendCompletion = dataGridInfiniteScrollAppendCompletion(previousResult, result");
- expect(resultWatcher).toContain("if (appendCompletion) {");
- expect(resultWatcher).toContain("closeReadonlyCellTextSelection();");
- });
-
it("focuses and selects the complete read-only value on mount", async () => {
const { root } = mountSelection();
await nextTick();
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridSaveReload.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridSaveReload.spec.ts
deleted file mode 100644
index 0aed91e6dc..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridSaveReload.spec.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string): string {
- const start = dataGridSource.indexOf(`function ${name}`);
- const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
- expect(start).toBeGreaterThanOrEqual(0);
- expect(relativeEnd).toBeGreaterThan(0);
- return dataGridSource.slice(start, start + relativeEnd);
-}
-
-describe("DataGrid save reload integration", () => {
- it("shares the toolbar full-reload preparation with editor saves", () => {
- const prepareSource = functionSource("prepareFullReload", "onToolbarRefresh");
- const toolbarSource = functionSource("onToolbarRefresh", "setAutoRefreshInterval");
- const rollbackSource = functionSource("onToolbarRollback", "addRow");
-
- expect(dataGridSource).toContain("prepareFullReload,\n emit,");
- expect(dataGridSource).toContain("refreshSavedRows,\n onCellValueChanged");
- expect(toolbarSource).toContain("prepareFullReload();");
- expect(rollbackSource).toContain("prepareFullReload();");
- expect(toolbarSource).toContain("const resetToFirstPage = hasPendingConditionInputs();");
- expect(toolbarSource).toContain("resetToFirstPage ? 0 : (currentPage.value - 1) * pageSize.value");
- expect(prepareSource).toContain("resetInfiniteScrollState();");
- expect(prepareSource).toContain("captureViewportAnchorForRefresh();");
- expect(prepareSource).toContain("preservedViewportAnchorOnNextResult = viewportAnchor ? { anchor: viewportAnchor, sourceResult: props.result } : null;");
- expect(prepareSource).toContain("captureCurrentSelectionForRefresh();");
- expect(prepareSource).toContain("preservedSelectionOnNextResult = selection ? { selection, sourceResult: props.result } : null;");
- expect(prepareSource).toContain("preservedDetailsOnNextResult = captureDetailsForRefresh();");
- expect(prepareSource).toContain("preserveTransposeOnNextResult.value = showTranspose.value;");
- expect(dataGridSource).toContain("if (detailsSnapshot) restoreDetailsAfterRefresh(detailsSnapshot);");
- expect(dataGridSource).toContain("if (viewportAnchorSnapshot) restoreViewportAnchorAfterRefresh(viewportAnchorSnapshot);");
- });
-
- it("resets accumulated infinite-scroll pagination before reloading from offset zero", () => {
- const resetSource = functionSource("resetInfiniteScrollState", "prepareFullReload");
- const nextPageSource = functionSource("infiniteScrollNextPage", "checkInfiniteScroll");
-
- expect(resetSource).toContain("currentPage.value = 1;");
- expect(resetSource).toContain("lastInfiniteScrollPage = 0;");
- expect(resetSource).toContain("infiniteScrollRequestedOffset = undefined;");
- expect(resetSource).toContain("infiniteScrollRequestedLimit = undefined;");
- expect(nextPageSource).toContain("const nextOffset = props.result.rows.length;");
- expect(nextPageSource).toContain('emit("paginate", nextOffset, nextLimit, currentWhereInput(), currentOrderBy());');
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridSelectionGesture.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridSelectionGesture.spec.ts
deleted file mode 100644
index df350e0c1f..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridSelectionGesture.spec.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-describe("DataGrid selection gesture ownership", () => {
- it("stops released gestures before DOM hover or canvas movement extends them", () => {
- expect(source).toContain("function stopReleasedSelectionGesture(event: MouseEvent)");
- expect(source).toContain("if ((event.buttons & 1) !== 0) return false;");
- expect(source).toContain("function onCellMouseenter(rowIndex: number, visibleColIdx: number, actualColIdx: number, event: MouseEvent)");
- expect(source).toContain('@mouseenter="onCellMouseenter(item.displayIndex, col.visibleColIdx, col.actualColIdx, $event)"');
-
- const canvasMove = source.slice(source.indexOf("function onCanvasMouseMove"), source.indexOf("function onCanvasMouseLeave"));
- expect(canvasMove).toContain("stopReleasedSelectionGesture(event);");
- });
-
- it("only exposes cell snapshots for selections with a rectangular matrix", () => {
- expect(source).toMatch(/contextCell\.value && hasCellSelection\.value && selectedCellMatrix\.value\s*\n?\s*\?\s*"cells"/);
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridSurfaces.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridSurfaces.spec.ts
index d185cdab5c..35f309cbad 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridSurfaces.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridSurfaces.spec.ts
@@ -115,13 +115,9 @@ import DataGridPagination from "@/components/grid/DataGridPagination.vue";
import DataGridQueryControls from "@/components/grid/DataGridQueryControls.vue";
import DataGridSearchBar from "@/components/grid/DataGridSearchBar.vue";
-const dataGridSource = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
-const dataGridCellDetailEditSource = readFileSync("apps/desktop/src/composables/useDataGridCellDetailEdit.ts", "utf8");
const cellDetailPanelSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailPanel.vue", "utf8");
const cellDetailDialogSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailDialog.vue", "utf8");
const binaryTextPreviewSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailTextPreview.vue", "utf8");
-const cellDetailHeaderSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailHeader.vue", "utf8");
-const globalsCss = readFileSync("apps/desktop/src/styles/globals.css", "utf8");
function detail(patch: Partial<DataGridCellDetail> = {}): DataGridCellDetail {
return {
@@ -154,55 +150,6 @@ beforeEach(() => {
vi.clearAllMocks();
localStorage.removeItem("dbx-filter-builder-value-shortcut-hint-days");
});
-describe("DataGrid canvas surfaces", () => {
- it("keeps condition and text filter editors open when persistent expansion is enabled", () => {
- expect(dataGridSource).toContain('const isPersistentFilterView = computed(() => filterEditorView.value === "conditions" || filterEditorView.value === "text");');
- expect(dataGridSource).toContain("const isFilterEditorPinnedOpen = computed(() => isPersistentFilterView.value && settingsStore.editorSettings.dataGridKeepFilterEditorExpanded);");
- expect(dataGridSource).toContain("get: () => isFilterEditorPinnedOpen.value || filterBuilderOpen.value,");
- expect(dataGridSource).toContain("if (!isFilterEditorPinnedOpen.value) filterBuilderOpen.value = false;");
- expect(dataGridSource).toContain('v-model:filter-builder-open="effectiveFilterBuilderOpen"');
- expect(dataGridSource).toContain("filterEditorView === 'conditions' && effectiveFilterBuilderOpen");
- expect(dataGridSource).toContain("filterEditorView === 'text' && effectiveFilterBuilderOpen");
- });
-
- it("asks before an expensive Elasticsearch cursor jump", () => {
- expect(dataGridSource).toContain("requestCount >= ELASTICSEARCH_PAGE_JUMP_WARNING_REQUESTS");
- expect(dataGridSource).toContain('t("grid.esDeepPageJumpConfirmMessage"');
- expect(dataGridSource).toContain('@click="confirmEsDeepPageJump"');
- });
-
- it("shows stable request progress while an Elasticsearch page jump is running", () => {
- expect(dataGridSource).toContain('t("grid.pageJumpLoading", { page: pageJumpProgress.targetPage })');
- expect(dataGridSource).toContain('t("grid.pageJumpProgress", { current: pageJumpProgress.completedRequests, total: pageJumpProgress.totalRequests })');
- expect(dataGridSource).toContain('role="progressbar"');
- expect(dataGridSource).toContain(':style="{ width: `${pageJumpProgressPercent}%` }"');
- });
-
- it("uses the stable overlay for viewport and device-pixel measurement", () => {
- expect(dataGridSource).toContain("function canvasMeasurementSurface(): HTMLElement | null");
- expect(dataGridSource).toContain("return canvasOverlayRef.value ?? null;");
- expect(dataGridSource).toContain("const measurementSurface = canvasMeasurementSurface();");
- expect(dataGridSource).toContain("getSurface: canvasMeasurementSurface,");
- expect(dataGridSource).toContain("const canvas = inactiveCanvasSurface();");
- expect(dataGridSource).toContain("canvasUsingBackSurface.value = !canvasUsingBackSurface.value;");
- });
-
- it("uses the canvas that actually received the event during a surface flip", () => {
- expect(dataGridSource).toContain("function canvasEventSurface(event: MouseEvent): HTMLCanvasElement | null");
- expect(dataGridSource).toContain("const currentTarget = event.currentTarget;");
- expect(dataGridSource).toContain("return currentTarget instanceof HTMLCanvasElement ? currentTarget : activeCanvasSurface();");
- expect(dataGridSource).toContain("const canvas = canvasEventSurface(event);");
-
- const canvasMouseMove = dataGridSource.slice(dataGridSource.indexOf("function onCanvasMouseMove"), dataGridSource.indexOf("function onCanvasMouseLeave"));
- expect(canvasMouseMove).toContain("const cursorSurface = canvasEventSurface(event);");
- });
-
- it("handles double clicks on the stable canvas container", () => {
- expect(dataGridSource).toContain('@dblclick="onCanvasDblClick"');
- expect(dataGridSource.match(/@dblclick="onCanvasDblClick"/g)).toHaveLength(1);
- expect(dataGridSource).toContain("@dblclick.stop");
- });
-});
describe("DataGridSearchBar", () => {
it("focuses/selects the input and forwards keyboard, navigation, and suggestion interactions", async () => {
@@ -258,18 +205,6 @@ describe("DataGridSearchBar", () => {
});
describe("DataGridPagination", () => {
- it("keeps drag summaries count-only and wires the derived average without materializing selected cells", () => {
- const summaryStart = dataGridSource.indexOf("const selectionSummary = computed");
- const pendingSummary = dataGridSource.indexOf("createPendingSelectionSummary(selectedCellCount.value, multiRowCount.value)", summaryStart);
- const materializedSummary = dataGridSource.indexOf("summarizeSelection(selectedCells.value)", summaryStart);
-
- expect(summaryStart).toBeGreaterThan(-1);
- expect(pendingSummary).toBeGreaterThan(summaryStart);
- expect(materializedSummary).toBeGreaterThan(pendingSummary);
- expect(dataGridSource).toContain('const selectionSummaryAverageText = computed(() => {\n if (isSelectingCells.value) return "…";');
- expect(dataGridSource).toContain(':selection-summary-average-text="selectionSummaryAverageText"');
- });
-
it("shows average beside the existing selection summary values", () => {
const mounted = mountComponent(DataGridPagination, {
selectionSummary: { cellCount: 4, rowCount: 2 },
@@ -507,8 +442,6 @@ describe("DataGridColumnHeader", () => {
expect(String(tooltipType.props.class ?? "")).toContain("data-grid-type-string");
const headerTypeLine = findOne(mounted.root, (node) => hostText(node) === "varchar(255)" && node.props["data-grid-header-type-line"] === "");
expect(String(headerTypeLine.props.class)).toContain("data-grid-type-string");
- // Softer dark-mode palette override for the tooltip container.
- expect(globalsCss).toMatch(/\.dark \.dbx-column-info-tooltip \{[^}]*--data-grid-type-string-fg: #4ade80/);
});
it("cancels resize-handle clicks without leaking header click events", () => {
@@ -1423,38 +1356,6 @@ describe("DataGridTextFilterWorkbench", () => {
});
describe("cell detail surfaces", () => {
- it("keeps detail tabs and editor actions usable when the panel narrows", () => {
- const tabsHeader = cellDetailHeaderSource;
- const tabViewport = tabsHeader.match(/<div class="([^"]*overflow-x-auto[^"]*)">\s*<TabsList/);
- const tabList = tabsHeader.match(/<TabsList class="([^"]+)">/);
- const triggerClasses = Array.from(tabsHeader.matchAll(/<TabsTrigger\b[^>]*class="([^"]+)"/g), ([, classes]) => classes.split(/\s+/));
-
- expect(tabViewport?.[1]?.split(/\s+/)).toEqual(expect.arrayContaining(["min-w-0", "flex-1", "overflow-x-auto"]));
- expect(tabList?.[1]?.split(/\s+/)).toEqual(expect.arrayContaining(["flex", "w-max", "min-w-full"]));
- expect(triggerClasses).toHaveLength(3);
- for (const classes of triggerClasses) {
- expect(classes).toEqual(expect.arrayContaining(["min-w-max", "flex-1", "shrink-0"]));
- }
- expect(dataGridSource).not.toContain("activeCellDetailTabsGridClass");
-
- const valueEditorLifecycleStart = dataGridSource.indexOf("watch(valueEditorContainer");
- const valueEditorLifecycleEnd = dataGridSource.indexOf("const detailEdit = useDataGridCellDetailEdit", valueEditorLifecycleStart);
- const valueEditorLifecycle = dataGridSource.slice(valueEditorLifecycleStart, valueEditorLifecycleEnd);
- expect(valueEditorLifecycle).toContain("const editor = valueDetailEditor;");
- expect(valueEditorLifecycle).toContain("if (valueDetailEditor !== editor) return;");
- expect(valueEditorLifecycle).toContain("if (editor.getValue() !== detailEditValue.value)");
- expect(valueEditorLifecycle).toContain("editor.setValue(detailEditValue.value, activeCellDetail.value?.type);");
-
- const valueEditorStart = dataGridSource.indexOf("<TabsContent v-if=\"activeCellDetailTabs.includes('valueEditor')\"");
- const valueEditorEnd = dataGridSource.indexOf("</TabsContent>", valueEditorStart);
- const valueEditor = dataGridSource.slice(valueEditorStart, valueEditorEnd);
- expect(valueEditor).toMatch(/<TabsContent[^>]*class="[^"]*\bmin-w-0\b[^"]*">/);
- expect(valueEditor).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\bflex-wrap\b[^"]*">/);
-
- expect(cellDetailPanelSource).toMatch(/<TabsContent value="details" class="[^"]*\bmin-w-0\b[^"]*">/);
- expect(cellDetailPanelSource).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\bflex-wrap\b[^"]*">/);
- });
-
it("presents printable LONG BLOB bytes as text and copies the presented value", async () => {
const copyText = vi.fn();
const blobDetail = detail({
@@ -1857,14 +1758,6 @@ describe("cell detail surfaces", () => {
expect(compareJson).toHaveBeenCalledOnce();
});
- it("snapshots comparison values before opening and suppresses modal-induced blur commits", () => {
- expect(dataGridCellDetailEditSource).toContain("detailValueDiffSnapshot.value = snapshot;");
- expect(dataGridCellDetailEditSource).toContain("detailValueDiffOpen.value = true;");
- expect(dataGridSource).toContain("if (!detailValueDiffOpen.value && !detailTransformOpen.value) commitValueEditorEdit();");
- expect(dataGridSource).toContain(':disabled="!canCompareDetailJson" @mousedown.prevent @click="openDetailJsonCompare"');
- expect(dataGridSource).toContain('v-model:open="detailValueDiffOpen" :snapshot="detailValueDiffSnapshot"');
- });
-
// issue #9832:编辑中点「压缩 JSON」会把草稿压成单行,此时必须仍能点「格式化 JSON」
// 重新展开,否则 Mongo 这类对象字段的 JSON 一旦压缩就再也无法格式化。
it("keeps the JSON format action reachable while a compacted draft is being edited", async () => {
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridViewSnapshotRestore.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridViewSnapshotRestore.spec.ts
deleted file mode 100644
index e85f03ab58..0000000000
--- a/apps/desktop/src/components/grid/__tests__/DataGridViewSnapshotRestore.spec.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, endMarker: string): string {
- const start = dataGridSource.indexOf(`function ${name}(`);
- const end = dataGridSource.indexOf(endMarker, start + 1);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return dataGridSource.slice(start, end);
-}
-
-describe("DataGrid tab-switch view snapshots", () => {
- const captureSource = functionSource("captureViewSelection", "function captureTabSwitchViewSnapshot(");
- const captureFnSource = functionSource("captureTabSwitchViewSnapshot", "function restoreTabSwitchViewSnapshot(");
- const restoreSource = functionSource("restoreTabSwitchViewSnapshot", "const multiRowCount = computed(");
-
- it("captures only with an owner key and a generation, and skips transpose", () => {
- expect(captureFnSource).toContain("if (!ownerKey || !props.viewGeneration) return;");
- expect(captureFnSource).toContain("if (showTranspose.value) return;");
- expect(captureFnSource).toContain("ownerKey,");
- expect(captureFnSource).toContain("viewGeneration: props.viewGeneration");
- expect(captureFnSource).toContain("probe: currentViewProbe()");
- });
-
- it("takes the snapshot owner from viewStateKey, falling back to cacheKey", () => {
- // Document tabs need their own owner key: cacheKey also scopes structured
- // filters, column widths and pending edits, which they leave untouched.
- expect(dataGridSource).toContain("const viewSnapshotOwnerKey = computed(() => props.viewStateKey?.trim() || props.cacheKey?.trim() || undefined);");
- expect(captureFnSource).toContain("const ownerKey = viewSnapshotOwnerKey.value;");
- expect(restoreSource).toContain("const ownerKey = viewSnapshotOwnerKey.value;");
- });
-
- it("captures the selection in O(selection size), never through the refresh identity scan", () => {
- // Copies refs directly instead of captureCurrentSelectionForRefresh, which
- // builds an identity token for every row (O(row count) on a large result).
- expect(captureFnSource).not.toContain("captureCurrentSelectionForRefresh");
- // Contiguous/all row selections serialize as a compact range instead of one
- // id per row, and the range helpers iterate only the selected ids via the
- // O(1) display index lookup — never the full displayItems.
- expect(captureSource).toContain("selectedRowCount === displayCount");
- expect(captureSource).toContain("selectedRowsContiguous(selectedRowIds.value)");
- expect(captureSource).toContain('kind: "all"');
- expect(captureSource).toContain("clampDataGridViewSelection(");
- const contiguousHelper = dataGridSource.slice(dataGridSource.indexOf("function selectedRowsContiguous("), dataGridSource.indexOf("function minimalRowRange("));
- expect(contiguousHelper).toContain("displayRowIndexById(rowId)");
- expect(contiguousHelper).toContain("max - min + 1 === count");
- expect(contiguousHelper).not.toContain("displayItems");
- });
-
- it("gates every restore on identity, renderer, and probe", () => {
- expect(restoreSource).toContain("if (!structuredFilterHydrationReady.value) return;");
- expect(restoreSource).toContain("if (snapshot.viewGeneration !== props.viewGeneration) return;");
- expect(restoreSource).toContain('if (snapshot.renderer !== (useCanvasGridRows.value ? "canvas" : "dom")) return;');
- expect(restoreSource).toContain("if (snapshot.probe !== currentViewProbe()) return;");
- expect(restoreSource).toContain("if (showTranspose.value) return;");
- });
-
- it("applies the index-based selection directly without scrolling it into view", () => {
- expect(restoreSource).toContain("restoreCellSelectionState({ cellKeys: new Set(capturedSelection.cellKeys) })");
- expect(restoreSource).toContain('selectedRowIds.value = new Set(indexes.map((index) => displayItems.value[index]?.id).filter((id): id is number => typeof id === "number"));');
- expect(restoreSource).toContain("selectedColumnIndexes.value = new Set(capturedSelection.columnIndexes);");
- expect(restoreSource).toContain("selectedRowIds.value = new Set(displayItems.value.map((item) => item.id));");
- expect(restoreSource).toContain("selection.lastClickedRowIndex.value = capturedSelection.anchorRowIndex;");
- expect(restoreSource).not.toContain("restoreSelectionAfterRefresh(snapshot");
- });
-
- it("clamps the restored viewport and consumes the snapshot after success", () => {
- expect(restoreSource).toContain("Math.min(Math.max(0, snapshot.viewport.top), maxTop)");
- expect(restoreSource).toContain("Math.min(Math.max(0, snapshot.viewport.left), maxLeft)");
- // A replayed snapshot is consumed so a later remount cannot re-apply it.
- expect(restoreSource).toContain("consumeDataGridViewSnapshot(ownerKey);");
- });
-
- it("settles the viewport over a bounded retry envelope instead of a fixed two frames", () => {
- // Immediate attempt, then nextTick, then at most 8 rAFs — mirroring
- // restoreScrollAcrossFrames. A fixed two-frame assumption intermittently
- // clamps the saved position to the top before virtualization measures.
- expect(restoreSource).toContain("if (attempt()) return;");
- expect(restoreSource).toContain("nextTick(() => {");
- expect(restoreSource).toContain("frames >= MAX_VIEW_SNAPSHOT_RESTORE_FRAMES");
- expect(restoreSource).toContain("viewSnapshotRestoreFrame = requestAnimationFrame(onFrame);");
- // An unmeasured scroller clamps the target to 0; that must not count as a
- // finished restore, or the saved position is lost at the top.
- expect(restoreSource).toContain("const roomForSavedTop = maxTop >= snapshot.viewport.top;");
- expect(restoreSource).toContain("return accepted && (snapshot.viewport.top === 0 || (roomForSavedTop && stable));");
- expect(dataGridSource).toContain("const MAX_VIEW_SNAPSHOT_RESTORE_FRAMES = 8;");
- });
-
- it("honours the rollback switch in both directions", () => {
- expect(captureFnSource).toContain("if (!DATA_GRID_VIEW_SNAPSHOT_RESTORE) return;");
- expect(restoreSource).toContain("if (!DATA_GRID_VIEW_SNAPSHOT_RESTORE) return;");
- expect(dataGridSource).toContain("cancelViewSnapshotRestoreFrame();");
- });
-
- it("wires capture to unmount and to the pre-tab-switch event", () => {
- expect(dataGridSource).toContain('window.addEventListener("dbx:before-tab-switch", captureTabSwitchViewSnapshot)');
- expect(dataGridSource).toContain('window.removeEventListener("dbx:before-tab-switch", captureTabSwitchViewSnapshot)');
- expect(dataGridSource).toContain("onUnmounted(() => {\n // Capture before teardown");
- expect(dataGridSource).toContain("captureTabSwitchViewSnapshot();");
- });
-
- it("reports a dropped selection only after a successful restore", () => {
- // The capture must not toast while the user is leaving the tab.
- expect(captureFnSource).not.toContain("toast(");
- expect(restoreSource).toContain("snapshot.selectionDropped && shouldNotifyOverBudgetSelection(ownerKey");
- expect(restoreSource).toContain('toast(t("grid.viewSnapshotSelectionNotRestored")');
- // The notice stays one-shot per owner+generation.
- expect(dataGridSource).toContain("shouldNotifyOverBudgetSelection(ownerKey, props.viewGeneration!)");
- });
-
- it("retries after asynchronous structured-filter hydration", () => {
- expect(dataGridSource).toContain("structuredFilterHydrationReady.value = false;");
- expect(dataGridSource).toContain("structuredFilterHydrationReady.value = true;");
- expect(dataGridSource).toContain("nextTick(restoreTabSwitchViewSnapshot);");
- expect(dataGridSource).toContain("structuredFilterHydrationRequestId");
- });
-});
diff --git a/apps/desktop/src/components/grid/__tests__/dataGridColumnLayoutPopover.spec.ts b/apps/desktop/src/components/grid/__tests__/dataGridColumnLayoutPopover.spec.ts
index 00a4244de0..f37f962e02 100644
--- a/apps/desktop/src/components/grid/__tests__/dataGridColumnLayoutPopover.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/dataGridColumnLayoutPopover.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import path from "node:path";
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -41,8 +39,6 @@ vi.mock("@/components/ui/button", async () => {
import DataGridColumnLayoutPopover from "../DataGridColumnLayoutPopover.vue";
-const contentAreaSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/layout/ContentArea.vue"), "utf8");
-
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
function columnLayoutOptions(itemCount: number): DataGridColumnLayoutOption[] {
@@ -175,8 +171,6 @@ afterEach(() => {
describe("data grid column layout popover", () => {
it("is available from the query result toolbar and keeps a labelled compact trigger", async () => {
- expect(contentAreaSource).toContain('<DataGridColumnLayoutPopover :grid="dataGridRef" :compact="compact" />');
-
const gridState = createGrid(4);
const host = document.createElement("div");
document.body.append(host);
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts
deleted file mode 100644
index 8f8f547707..0000000000
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const browserSource = readFileSync(new URL("../KvKeyBrowser.vue", import.meta.url), "utf8");
-const etcdBrowserSource = readFileSync(new URL("../../etcd/EtcdKeyBrowser.vue", import.meta.url), "utf8");
-
-describe("KvKeyBrowser node export", () => {
- it("keeps directory toggles out of the detail-loading path", () => {
- expect(browserSource).toContain('if (node.kind === "lazy") return node.hasValue === true;');
- expect(browserSource).toContain("if (props.enableNodeActions && nodeHasValue(node)) void loadSelectedKey(routeFromNode(node));");
- expect(browserSource).not.toContain("function nodeMayHaveValue");
- });
-
- it("keeps an expanded virtual Consul directory open when its exact Key probe is absent", () => {
- expect(browserSource).toContain("const lazyNode = lazyTreeState.nodeByKey.get(key);");
- expect(browserSource).toContain("if (lazyNode?.hasChildren)");
- expect(browserSource).toContain("lazyNode.hasValue = false;");
- expect(browserSource).toContain("void refreshLazyParent(parentLazyKvPath(key, props.lazyPathStyle));");
- });
-
- it("shows export for both value keys and virtual directories", () => {
- expect(browserSource).toContain("if (props.api.exportScope || nodeHasValue(node))");
- expect(browserSource).toContain('kind: nodeIsExpandable(node) ? "prefix" : "key"');
- expect(browserSource).toContain("await props.api.exportScope(props.connectionId, request)");
- });
-
- it("delegates etcd directory export to a fixed-revision recursive scan", () => {
- expect(etcdBrowserSource).toContain("exportScope: exportEtcdNodeScope");
- expect(etcdBrowserSource).toContain("const scan = await scanConnection(connectionId, request.path)");
- expect(etcdBrowserSource).toContain("isKeyInKvExportScope(displayKey(keyValue(entry)), request)");
- expect(etcdBrowserSource).toContain("const missingValue = entries.find((entry) => !entry.value)");
- });
-
- it("compares canonical Key bytes without exposing mirror-delete operations", () => {
- expect(etcdBrowserSource).toContain("id: `source:${kvValueByteIdentity(source.key)}`");
- expect(etcdBrowserSource).not.toContain("id: source.key.data");
- expect(etcdBrowserSource).not.toContain("mirrorDeletes");
- expect(etcdBrowserSource).not.toContain('operation: "delete"');
- });
-
- it("snapshots the target and invalidates stale transfer previews", () => {
- expect(etcdBrowserSource).toContain("const targetId = targetConnectionId.value");
- expect(etcdBrowserSource).toContain("const generation = ++transferPreviewGeneration");
- expect(etcdBrowserSource).toContain("if (generation !== transferPreviewGeneration) return");
- expect(etcdBrowserSource).toContain(':disabled="transferLoading || transferApplying"');
- });
-
- it("refreshes a partial batch before allowing the remaining operations to retry", () => {
- expect(etcdBrowserSource).toContain('row.operation = "applied"');
- expect(etcdBrowserSource).toContain("await previewTransfer()");
- expect(etcdBrowserSource).toContain('t("etcd.transferPartiallyApplied"');
- });
-});
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts
deleted file mode 100644
index ebf119e2f7..0000000000
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const browserSource = readFileSync(new URL("../KvKeyBrowser.vue", import.meta.url), "utf8");
-
-describe("KvKeyBrowser search and split layout", () => {
- it("uses the requested prefix for a server-side, paginated search", () => {
- expect(browserSource).toContain("props.api.listPrefix(connectionId, searchQuery, pageSize, reset ? null : continuation.value");
- expect(browserSource).not.toContain("async function searchAllKeys");
- expect(browserSource).not.toContain("filterKvKeysBySearch(result.keys, query)");
- });
-
- it("focuses a matching Consul directory instead of nesting it beneath itself", () => {
- expect(browserSource).toContain('const focusedDirectory = props.lazyPathStyle === "relative" && rootPath && !rootPath.endsWith("/")');
- expect(browserSource).toContain("key.key === `${rootPath}/`");
- expect(browserSource).toContain("const childResult = await props.api.listPrefix(context.connectionId, focusedDirectory.key, pageSize, null, { recursive: false });");
- expect(browserSource).toContain("if (rootSummary?.hasValue !== true)");
- expect(browserSource).toContain("hasValue: true");
- });
-
- it("offers debounced, server-backed prefix completion for lazy Consul trees", () => {
- expect(browserSource).toContain("const remoteKeySuggestions = ref<KvKeySummary[]>([]);");
- expect(browserSource).toContain("const keySuggestionDebounceMs = 300;");
- expect(browserSource).toContain("function scheduleRemoteKeySuggestions(value: string)");
- expect(browserSource).toContain("listPrefix(connectionId, query, 8, null, { recursive: false })");
- expect(browserSource).toContain("const candidates = props.lazyHierarchy ? [...lazyTreeState.nodeByKey.values(), ...remoteKeySuggestions.value] : keys.value;");
- expect(browserSource).toContain('autocomplete="off"');
- expect(browserSource).toContain('<Popover :open="showKeySuggestions">');
- expect(browserSource).toContain('<PopoverContent v-if="showKeySuggestions" id="kv-key-prefix-suggestions"');
- expect(browserSource).toContain('if (props.lazyHierarchy && suggestion.key.endsWith("/"))');
- expect(browserSource).toContain("scheduleRemoteKeySuggestions(suggestion.key);");
- expect(browserSource).toContain('event.key !== "Enter" && event.key !== "Tab"');
- });
-
- it("drops stale lazy tree responses after a connection or root generation changes", () => {
- expect(browserSource).toContain("generation: ++keyLoadGeneration");
- expect(browserSource).toContain("function lazyLoadContextValid(context: LazyLoadContext)");
- expect(browserSource).toContain("context.connectionId === props.connectionId");
- expect(browserSource).toContain("lazyTreeState.nodeByKey.get(parentKey) !== node");
- expect(browserSource).toContain("keyLoadGeneration++;");
- });
-
- it("shows list request errors instead of the empty-state message", () => {
- expect(browserSource).toContain('const listError = ref("");');
- expect(browserSource.match(/listError\.value = formatError\(error\);/g)).toHaveLength(2);
- expect(browserSource.indexOf('v-else-if="listError"')).toBeLessThan(browserSource.indexOf('v-else-if="visibleRows.length === 0"'));
- });
-
- it("highlights the matching search query only for the selected search result", () => {
- expect(browserSource).toContain("interface KvSearchHighlight");
- expect(browserSource).toMatch(/const activeSearchHighlight = computed\(\(\) => \(?props\.searchHighlight\?\.key === selectedKey\.value/);
- expect(browserSource).toContain("function highlightText(value: string, enabled: boolean)");
- expect(browserSource).toContain("selectedValueHighlightSegments");
- });
-
- it("does not select Key text while opening its context menu", () => {
- expect(browserSource).toContain("select-none items-center");
- expect(browserSource).toContain("@mousedown.right.prevent");
- });
-
- it("uses a persisted draggable split between the Key tree and details", () => {
- expect(browserSource).toContain('<Splitpanes class="kv-browser-splitpanes min-h-0 flex-1" @resized="handleKvBrowserSplitResized">');
- expect(browserSource).toContain('<Pane :size="kvBrowserSplitSize" min-size="20" max-size="70">');
- expect(browserSource).toContain('<Pane :size="100 - kvBrowserSplitSize" min-size="30">');
- expect(browserSource).toContain("safeLocalStorageSet(kvBrowserSplitSizeStorageKey, String(size))");
- expect(browserSource).toContain("cursor: col-resize");
- });
-});
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserTtl.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserTtl.spec.ts
deleted file mode 100644
index b7b71a0210..0000000000
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserTtl.spec.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const browserSource = readFileSync(new URL("../KvKeyBrowser.vue", import.meta.url), "utf8");
-
-describe("KvKeyBrowser TTL details", () => {
- it("renders the selected key TTL and refreshes it every second", () => {
- expect(browserSource).toContain("const selectedTtlLabel = computed");
- expect(browserSource).toContain('<Badge v-if="selectedTtlLabel" variant="outline">TTL {{ selectedTtlLabel }}</Badge>');
- expect(browserSource).toContain("metadataRefreshTimer = setInterval");
- expect(browserSource).toContain("void refreshSelectedMetadata(key, generation)");
- });
-
- it("stops TTL polling when the browser unmounts", () => {
- expect(browserSource).toContain("onBeforeUnmount(() =>");
- expect(browserSource).toContain("stopKeyListRefresh()");
- expect(browserSource).toContain("stopMetadataRefresh()");
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts b/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts
deleted file mode 100644
index fa6aa1d692..0000000000
--- a/apps/desktop/src/components/layout/__tests__/AppTabBar.spec.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const tabBarSource = readFileSync(new URL("../AppTabBar.vue", import.meta.url), "utf8");
-const groupTabBarSource = readFileSync(new URL("../EditorGroupTabBar.vue", import.meta.url), "utf8");
-const groupSource = readFileSync(new URL("../EditorGroup.vue", import.meta.url), "utf8");
-
-describe("AppTabBar shared group navigation", () => {
- it("hosts existing group bars without rendering a second tab strip", () => {
- expect(tabBarSource).toContain("GROUP_TAB_BAR_PORTAL");
- expect(tabBarSource).toContain('v-for="group in queryStore.groups"');
- expect(tabBarSource).toContain(':data-special-page-tab-target="group.id"');
- expect(tabBarSource).not.toContain("overlayReturnTabs");
- expect(tabBarSource).not.toContain("data-return-tab");
- expect(tabBarSource).not.toContain("createRenameDuplicateTabItems");
- expect(groupSource).toContain("<Teleport defer");
- expect(groupSource).toContain("if (!tabBarPortal?.active.value) return undefined;");
- expect(groupSource).toContain(':disabled="!tabBarPortal?.active.value || !tabBarTarget"');
- });
-
- it("retains targets while hiding inactive special content and follows all placements", () => {
- expect(tabBarSource).toContain('v-show="driverStoreActive || pluginCenterActive || settingsPageActive"');
- expect(tabBarSource).toContain("data-special-page-navigation");
- expect(tabBarSource).toContain("data-special-page-content");
- expect(tabBarSource).toContain("<slot />");
- for (const layout of ["flex-col", "flex-col-reverse", "flex-row", "flex-row-reverse"]) {
- expect(tabBarSource).toContain(layout);
- }
- expect(tabBarSource).toContain("props.tabBarCollapsed");
- expect(tabBarSource).toContain("props.tabBarWidth");
- });
-
- it("scopes the close-other shortcut to the active tab's owner group", () => {
- expect(tabBarSource).toContain("closeOtherTabsInGroup(ownerGroup.id, activeTabId)");
- });
-});
-
-describe("AppTabBar close confirmation layout", () => {
- it("allows long unbroken tab titles to shrink and wrap inside the dialog", () => {
- expect(tabBarSource).toMatch(/<DialogContent class="[^"]*\bmin-w-0\b[^"]*\bsm:max-w-md\b/);
- expect(tabBarSource).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\bspace-y-2\b">\s*<p class="[^"]*\bwrap-anywhere\b/);
- });
-
- it("keeps all single and bulk close actions while allowing the footer to wrap", () => {
- expect(tabBarSource).toMatch(/<DialogFooter class="[^"]*\bmin-w-0\b[^"]*\bsm:flex-wrap\b">/);
- expect(tabBarSource).toContain('v-if="showCloseConfirmBulkActions" variant="secondary" class="border-border" @click="handleDiscardAllAndClose"');
- expect(tabBarSource).toContain('v-if="showCloseConfirmBulkActions" @click="handleSaveAllAndClose"');
- expect(tabBarSource).toContain('variant="secondary" class="border-border" @click="handleDiscardAndClose"');
- expect(tabBarSource).toContain('@click="handleSaveAndClose"');
- expect(tabBarSource).toContain('@click="handleCancelClose"');
- });
-
- it("shows the dirty tab list using the shared tab title presentation", () => {
- const start = tabBarSource.indexOf('v-for="tab in closeConfirmDirtyTabs"');
- const end = tabBarSource.indexOf("</PopoverContent>", start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- expect(tabBarSource.slice(start, end)).toContain("closeConfirmTabTitle(tab)");
- });
-});
-
-describe("Group strip special page tabs", () => {
- it("keeps special page tabs and their update badge in the focused group", () => {
- expect(groupTabBarSource).toContain("queryStore.focusedGroupId === props.groupId");
- expect(groupTabBarSource).toContain("data-settings-page-tab");
- expect(groupTabBarSource).toContain("data-plugin-center-tab");
- expect(groupTabBarSource).toContain("data-driver-store-tab");
- expect(groupTabBarSource).toContain("@click=\"emit('activate-settings')\"");
- expect(groupTabBarSource).toContain("@click=\"emit('activate-plugin-center')\"");
- expect(groupTabBarSource).toContain("@click=\"emit('activate-driver-store')\"");
- expect(groupTabBarSource).toContain('t("toolbar.driverManager")');
- expect(groupTabBarSource).toContain("aria-label=\"t('toolbar.updatableDriverCount')\"");
- expect(groupTabBarSource).toContain("specialPageTabs?.driverUpdateCount");
- });
-
- it("routes special-page actions and preserves ordinary-tab dirty closing", () => {
- expect(groupSource).toContain(':special-page-tabs="toolbar.specialPageTabs.value"');
- expect(groupSource).toContain('@activate-settings="toolbar.activateSettingsPage()"');
- expect(groupSource).toContain('@activate-plugin-center="toolbar.activatePluginCenter()"');
- expect(groupSource).toContain('@close-plugin-center="toolbar.closePluginCenter()"');
- expect(groupSource).toContain('@close-driver-store="toolbar.closeDriverStore()"');
- expect(groupTabBarSource).toContain('@mousedown.middle.prevent="closeTab(entry.tab)"');
- expect(groupTabBarSource).toContain('@click.stop="closeTab(entry.tab)"');
- expect(groupTabBarSource).toContain("queryStore.closeTab(tab.id)");
- });
-
- it("uses one presentation path for active special pages and inactive ordinary tabs", () => {
- expect(groupTabBarSource).toContain("return !specialPageActive.value && tab.id === props.activeTabId;");
- expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.settingsActive)");
- expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.pluginCenterActive)");
- expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.driverStoreActive)");
- expect(groupTabBarSource).toContain("if (!active) return undefined;");
- expect(groupTabBarSource).toContain('return { "--app-tab-background": activeBackground, boxShadow: "inset 0 -2px 0 color-mix(in srgb, var(--foreground) 72%, transparent)" };');
- expect(groupTabBarSource).toContain('import "./appTabBar.css"');
- expect(groupTabBarSource).toContain("dirty-tab-marker");
- expect(groupTabBarSource).toContain("dirtyTabTitleStyle");
- expect(groupTabBarSource).toContain("createRenameDuplicateTabItems");
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.dataToolbar.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.dataToolbar.spec.ts
deleted file mode 100644
index ba54da4d4f..0000000000
--- a/apps/desktop/src/components/layout/__tests__/ContentArea.dataToolbar.spec.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const contentAreaSource = readFileSync(new URL("../ContentArea.vue", import.meta.url), "utf8");
-
-describe("ContentArea data toolbar", () => {
- it("keeps table properties in the primary toolbar at every overflow tier", () => {
- expect(contentAreaSource).toContain('v-if="activeTab.result && activeDataTabTableMeta && activeTab.connectionId"');
- expect(contentAreaSource).not.toContain("showDataTableInfoButton");
- expect(contentAreaSource).not.toContain("ToolbarOverflowMenu");
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.outputView.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.outputView.spec.ts
deleted file mode 100644
index 007dbadf12..0000000000
--- a/apps/desktop/src/components/layout/__tests__/ContentArea.outputView.spec.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const contentAreaSource = readFileSync(new URL("../ContentArea.vue", import.meta.url), "utf8");
-
-describe("ContentArea completed query output", () => {
- it("re-evaluates the no-table fallback when tab activation resets the shared view", () => {
- expect(contentAreaSource).toContain("props.activeTab.isExecuting, props.activeOutputView] as const");
- expect(contentAreaSource).toContain('emit("update:activeOutputView", props.activeTab.id, result ? defaultViewForResult(result) : "summary")');
- });
-
- it("scopes the output-view watcher to the shared result surface", () => {
- expect(contentAreaSource).toContain("if (props.editorOnly) return;");
- });
-});
-
-describe("ContentArea editor-only split sizing", () => {
- it("keeps the editor pane at 100% in editor-only mode so no blank dead zone is left behind", () => {
- // The shared result surface renders results in its own workspace pane, so
- // this splitpanes has a single (editor) pane in editor-only mode. A purely
- // reactive size prop does not re-normalize a lone pane, so any value below
- // 100 would shrink the editor and leave the remainder as empty background.
- expect(contentAreaSource).toContain("const editorPaneSize = computed(() => (props.editorOnly || !resultsPaneOpen.value ? 100 : 100 - resultsPaneSize.value));");
- });
-});
-
-describe("ContentArea Mongo tab reuse", () => {
- it("remounts the document browser when the active tab changes collections", () => {
- expect(contentAreaSource).toContain(':key="`${activeTab.id}:${activeTab.sql}`"');
- });
-});
-
-describe("ContentArea query result grid", () => {
- it("passes connection and per-run count SQL to the query-tab grid so the total can be re-counted", () => {
- const countSqlProp = ':count-sql="activeTab.resultCountSql"';
- const countSqlIndex = contentAreaSource.indexOf(countSqlProp);
- expect(countSqlIndex).toBeGreaterThan(-1);
- // Robust string-matching: anchor on the per-run count SQL and walk back to
- // the enclosing DataGrid so the test does not depend on DataGrid ordering
- // while staying in readFileSync format.
- const dataGridIndex = contentAreaSource.lastIndexOf("<DataGrid", countSqlIndex);
- expect(dataGridIndex).toBeGreaterThan(-1);
- const queryGridBlock = contentAreaSource.slice(dataGridIndex, countSqlIndex + 900);
- expect(queryGridBlock).toContain("<DataGrid");
- expect(queryGridBlock).toContain(':connection-id="activeResultConnectionId"');
- expect(queryGridBlock).toContain(':count-sql="activeTab.resultCountSql"');
- expect(queryGridBlock).toContain(':count-total-rows="activeTab.resultCountSql ? () => queryStore.countTabResultRows(activeTab.id) : undefined"');
- expect(queryGridBlock).toContain(':total-row-count="activeTab.resultTotalRowCount"');
- expect(queryGridBlock).toContain(':total-row-count-loading="activeTab.resultTotalRowCountLoading"');
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.tableImportEntry.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.tableImportEntry.spec.ts
deleted file mode 100644
index f476e24e0b..0000000000
--- a/apps/desktop/src/components/layout/__tests__/ContentArea.tableImportEntry.spec.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-function read(relativePath: string) {
- return readFileSync(new URL(relativePath, import.meta.url), "utf8");
-}
-
-// 能打开「导入表数据」向导的三个入口。侧边栏的守卫在菜单宿主(SidebarTreeRuntimeHost.vue)里,
-// 写入函数 composables/useSidebarTreeToolRuntime.ts 本身不带守卫,所以这里列的是入口界面而不是写入点。
-const TABLE_IMPORT_ENTRY_SURFACES = ["../ContentArea.vue", "../../objects/ObjectBrowser.vue", "../../sidebar/SidebarTreeRuntimeHost.vue"];
-
-describe("ContentArea table import entry", () => {
- it("gates the data-tab toolbox import item on the shared capability check", () => {
- const source = read("../ContentArea.vue");
- // HANA 的能力清单是 tableImport:false。入口不跟能力走时,向导仍能打开并停在「选项」步:
- // 目标表字段元数据取不回来,下一步恒为禁用(QA #hana-import 的复现路径)。
- expect(source).toContain("const canOpenTableImport = computed(");
- expect(source).toContain("supportsTableImport(activeEffectiveDatabaseType.value)");
-
- const item = source.indexOf('t("tableToolbox.importData")');
- expect(item).toBeGreaterThan(-1);
- const openTag = source.lastIndexOf("<DropdownMenuItem", item);
- expect(openTag).toBeGreaterThan(-1);
- expect(source.slice(openTag, item)).toContain('v-if="canOpenTableImport"');
- });
-
- it("keeps every entry surface consulting the same capability", () => {
- for (const surface of TABLE_IMPORT_ENTRY_SURFACES) {
- expect(read(surface), surface).toContain("supportsTableImport");
- }
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.unavailableDataReload.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.unavailableDataReload.spec.ts
deleted file mode 100644
index 24133330b5..0000000000
--- a/apps/desktop/src/components/layout/__tests__/ContentArea.unavailableDataReload.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const contentAreaSource = readFileSync(new URL("../ContentArea.vue", import.meta.url), "utf8");
-
-describe("ContentArea restored data-tab refresh", () => {
- it("routes both no-data refresh entries through the filter-preserving helper (#7963)", () => {
- // 裸 emit("reload") 会让 onReloadData 把缺省的 whereInput/orderBy 当成
- // “用户已清空”,刷新后退回整张表的数据。
- expect(contentAreaSource).not.toContain(`@click="emit('reload')"`);
- expect(contentAreaSource).not.toMatch(/\bemit\("reload"\)\s*;/);
- expect(contentAreaSource).toContain(`@click="reloadUnavailableDataTab()"`);
- expect(contentAreaSource).toContain("reloadUnavailableDataTab();");
- });
-
- it("passes the restored tab's own WHERE/ORDER BY into the reload event", () => {
- expect(contentAreaSource).toContain("const { whereInput, orderBy } = restoredDataTabReloadFilters(props.activeTab);");
- // The tabId-first contract still reserves the sql and searchText slots before
- // the restored filters. Omitting either placeholder shifts ORDER BY into WHERE.
- expect(contentAreaSource).toContain(`emit("reload", props.activeTab.id, undefined, undefined, whereInput, orderBy);`);
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.groups.spec.ts b/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.groups.spec.ts
index 102fc9aa68..6903857fc4 100644
--- a/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.groups.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.groups.spec.ts
@@ -35,245 +35,8 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({
}));
const specDir = dirname(fileURLToPath(import.meta.url));
-const source = readFileSync(resolve(specDir, "../EditorGroupTabBar.vue"), "utf8");
const sharedStyles = readFileSync(resolve(specDir, "../appTabBar.css"), "utf8");
-describe("EditorGroupTabBar semantic tab groups", () => {
- it("keeps separate collapsed state for pinned and regular clusters under the same key", () => {
- expect(source).toContain("const collapsedTabGroups = ref<Set<string>>(new Set());");
- expect(source).toContain('return `${tab.pinned ? "fixed" : "regular"}:${settingsStore.editorSettings.tabGroupMode}:${tabGroupKey(tab)}`;');
- expect(source).toContain("function toggleTabGroup(tab: QueryTab)");
- expect(source).toContain(':aria-expanded="!isTabGroupCollapsed(entry.tab)"');
- });
-
- it("counts group entries in linear time instead of rescanning the section", () => {
- const builder = sourceBetween("function buildStripEntries", "const pinnedStripEntries");
- expect(builder).toContain("const groupKeys = grouping ? section.map(tabGroupKey) : [];");
- expect(builder).toContain("const groupCounts = new Map<string, number>();");
- expect(builder).toContain("groupCounts.get(groupKey!) ?? 0");
- expect(builder).not.toContain("section.filter(");
- });
-
- it("computes the active group once instead of scanning every group", () => {
- const activeGroup = sourceBetween("const activeTabGroupId", "function isTabGroupActive");
- expect(activeGroup).toContain("const activeTab = props.tabs.find((item) => isTabActive(item));");
- expect(source).toContain("return activeTabGroupId.value === tabGroupId(tab);");
- });
-
- it("expands a collapsed group when one of its tabs becomes active", () => {
- expect(source).toContain("expandTabGroupForTab(tabId);");
- });
-
- it("supports persistent names and colors from the group header context menu", () => {
- expect(source).toContain('["#2563eb", "#d97706", "#7c3aed", "#059669", "#dc2626", "#0891b2", "#db2777", "#475569"]');
- expect(source).toContain("tabGroupCustomizations: customizations");
- expect(source).toContain("data-tab-group-name-input");
- expect(source).toContain('type="color"');
- });
-
- it("keeps placement, grouping, and sorting out of the group context menu", () => {
- const groupMenu = sourceBetween("function getTabGroupMenuItems", "function openTabGroupContextMenu");
- expect(groupMenu).not.toContain("getTabPreferenceMenuItems");
- });
-
- it("exposes preferences and the group close from each tab context menu", () => {
- const menuStart = source.indexOf("function getTabMenuItems");
- const menuEnd = source.indexOf("function handleTabDoubleClick");
- expect(menuStart).toBeGreaterThanOrEqual(0);
- expect(menuEnd).toBeGreaterThan(menuStart);
- const menu = source.slice(menuStart, menuEnd);
- expect(menu).not.toContain("getTabPreferenceMenuItems");
- expect(menu).toContain("action: () => closeTabGroup(tab)");
- expect(menu).toContain('visible: settingsStore.editorSettings.tabGroupMode !== "none"');
- });
-
- it("closes the global semantic group by key, not just this pane's cluster", () => {
- // D1 (amended): closing a cluster is destructive and stays bar-local —
- // scoped to this pane's tabs (props.tabs), still within the trigger's
- // pinned section. Profile edits (rename/color/reset) keep global reach.
- const closeGroup = sourceBetween("function tabsInSemanticGroup", "function getTabGroupMenuItems");
- expect(closeGroup).toContain("props.tabs.filter((item) => item.pinned === tab.pinned && tabGroupKey(item) === groupKey)");
- expect(closeGroup).toContain("queryStore.closeTabsByIds(tabsToClose, finalActiveTabId)");
- });
-
- it("waits for tab preference persistence and treats the whole group title as the context target", () => {
- expect(source).toContain("await settingsStore.updateEditorSettingsAndPersist(partial)");
- expect(source).toContain("openTabGroupContextMenu($event, onContextMenu)");
- expect(source).toContain("document.getSelection()?.removeAllRanges()");
- });
-
- it("applies the group rail classes to clustered pills", () => {
- // Grouped pills carry tab-group-tab for the entry underline and the
- // vertical rail, with first/last markers available for side layouts.
- expect(source).toContain("'tab-group-tab': entry.grouping,");
- expect(source).toContain("'tab-group-tab--first': entry.grouping && entry.groupFirst,");
- expect(source).toContain("'tab-group-tab--last': entry.grouping && entry.groupLast,");
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\) \.tab-group-tab::after\s*\{[^}]*bottom:\s*-0\.5px;/s);
- expect(sharedStyles).toContain(".app-tab-bar:not(.vertical-tab-layout) .tab-group-tab--last::after");
- expect(sharedStyles).toMatch(/\.tab-group-tab\[data-active-tab="true"\]::after,[\s\S]*?\.tab-group-entry:has\(\.tab-group-tab\[data-active-tab="true"\]\)::after\s*\{[^}]*z-index:\s*2;[^}]*var\(--foreground\) 72%/s);
- });
-
- it("hides collapsed cluster pills but reveals them while searching", () => {
- expect(source).toContain("grouping && !tabSearchQuery.trim() && isTabGroupCollapsed(entry.tab)");
- expect(sharedStyles).toContain(".tab-group-entry--collapsed");
- });
-
- it("remeasures overflow after a single-row group expansion finishes", () => {
- expect(source).toContain('@transitionend.self="handleTabGroupTransitionEnd"');
- expect(source).toContain(':data-tab-group-id="entry.grouping ? tabGroupId(entry.tab) : undefined"');
- expect(source).toContain("captureExpandedTabGroupWidths(new Set(pending))");
- expect(source).toContain("'tab-group-entry--collapsing'");
- expect(source).toContain("window.setTimeout(() =>");
- expect(sharedStyles).toContain("@keyframes tab-group-collapse");
- expect(sharedStyles).toMatch(/\.tab-group-entry--collapsing\s*\{[^}]*animation:\s*tab-group-collapse 140ms ease forwards;/s);
- expect(source).toContain('entry.style.removeProperty("--tab-group-entry-expanded-width")');
- expect(sharedStyles).toContain("max-width: var(--tab-group-entry-expanded-width, 100%)");
- expect(sharedStyles).toMatch(/\.tab-group-entry\[data-tab-group-id\] > \.tab-group-tab\s*\{[^}]*width:\s*var\(--tab-group-entry-expanded-width, auto\);[^}]*min-width:\s*var\(--tab-group-entry-expanded-width, max-content\) !important;[^}]*flex:\s*none;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\) \.tab-group-entry\s*\{[^}]*min-width:\s*0;/s);
- const handler = sourceBetween("function handleTabGroupTransitionEnd", "function toggleTabGroup");
- expect(handler).toContain('event.propertyName !== "max-width"');
- expect(handler).toContain("refreshHorizontalTabOverflow();");
- expect(source).toContain('return "tab-tail-overflow-spacer flex-none self-stretch";');
- expect(sharedStyles).toContain(".tab-tail-overflow-spacer[data-tauri-drag-region]");
- });
-
- it("keeps the overflow search scoped to the popover list without filtering the strip", () => {
- // Regression: the popover's "search opened tabs" box shared the strip's
- // query, so typing a term with no match emptied the top tab bar while the
- // active tab's content stayed on screen.
- const overflowFilter = sourceBetween("const filteredGroupTabs", "watch(tabOverflowOpen");
- expect(overflowFilter).toContain("tabOverflowSearchQuery.value.trim()");
- expect(overflowFilter).not.toContain("tabSearchQuery");
- const overflowOpenWatch = sourceBetween("watch(tabOverflowOpen", "const showOverflowControl");
- expect(overflowOpenWatch).toContain('tabOverflowSearchQuery.value = "";');
- const stripFilter = sourceBetween("const filteredPinnedTabs", "function buildStripEntries");
- expect(stripFilter).toContain("tabSearchQuery.value.trim()");
- expect(stripFilter).not.toContain("tabOverflowSearchQuery");
- expect(source).toContain('<Input v-model="tabOverflowSearchQuery" data-group-tab-search-input');
- });
-
- it("keeps wrap layout out of the vertical placement", () => {
- expect(source).toContain('const isWrapLayout = computed(() => !isVerticalLayout.value && settingsStore.editorSettings.tabLayout === "wrap");');
- });
-
- it("uses compact group pills and places the accent next to content for horizontal bars", () => {
- expect(source).toContain('isClassicLayout.value ? "classic-tab-layout" : "separated-tab-layout"');
- expect(source).toContain(':data-placement="settingsStore.editorSettings.tabPlacement"');
- expect(source).toContain(':data-group-mode="settingsStore.editorSettings.tabGroupMode"');
- expect(sharedStyles).toContain(".app-tab-bar:not(.vertical-tab-layout) .tab-group-header");
- expect(sharedStyles).toMatch(/\.app-tab-bar\.classic-tab-layout:not\(\.vertical-tab-layout\) \.tab-group-header-content\s*\{[^}]*height:\s*100%;[^}]*border-radius:\s*0;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar\.classic-tab-layout:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\)\[data-group-mode="none"\] \.app-tab-pill\s*\{[^}]*border-right-width:\s*0\.5px;/s);
- expect(sharedStyles).toMatch(
- /\.app-tab-bar\.classic-tab-layout:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\)\[data-placement="top"\]\[data-group-mode="none"\] \.app-tab-pill\[data-active-tab="true"\]\s*\{[^}]*border-top-color:\s*transparent;[^}]*border-right-color:\s*transparent;[^}]*border-left-color:\s*transparent;/s,
- );
- expect(sharedStyles).toMatch(/\.tab-overflow-control\s*\{[^}]*width:\s*34px;[^}]*flex:\s*0 0 34px;/s);
- expect(sharedStyles).toContain("padding-inline-end: 2.125rem;");
- expect(sharedStyles).toContain("inset-inline-end: 2.125rem;");
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\)\[data-placement="top"\] \.tab-overflow-control::before\s*\{[^}]*inset-inline:\s*-0\.25rem 0;[^}]*background:\s*transparent;/s);
- expect(sharedStyles).toMatch(/\.app-tab-scroll\.wrap-mode\.classic-wrap \.tab-group-header,[\s\S]*?\.tab-group-header-content\s*\{[^}]*height:\s*2rem !important;/s);
- expect(sharedStyles).toMatch(/\.app-tab-scroll\.wrap-mode\.classic-wrap \.tab-group-header:not\(\.tab-group-header--collapsed\)::after\s*\{[^}]*right:\s*-1px;/s);
- expect(sharedStyles).toContain(".app-tab-bar:not(.vertical-tab-layout) .tab-group-header::after");
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\) \.tab-group-header::after\s*\{[^}]*bottom:\s*0;/s);
- expect(sharedStyles).toContain(".app-tab-bar:not(.vertical-tab-layout) .tab-group-header--collapsed::after");
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):has\(\.wrap-mode\) \.tab-group-tab::after\s*\{[^}]*bottom:\s*-0\.5px;[^}]*background:\s*var\(--tab-group-color\);/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):has\(\.wrap-mode\)\[data-placement="bottom"\] \.tab-group-tab::after\s*\{[^}]*top:\s*-0\.5px;[^}]*bottom:\s*auto;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\)\[data-placement="bottom"\] \.tab-group-tab::after\s*\{[^}]*top:\s*-0\.5px;/s);
- expect(sharedStyles).toContain(".app-tab-scroll.wrap-mode.classic-wrap .tab-section--horizontal > .app-tab-pill");
- expect(sharedStyles).toContain(".app-tab-scroll.wrap-mode:not(.classic-wrap) .tab-section--horizontal > .app-tab-pill");
- expect(sharedStyles).toContain("row-gap: 0.375rem;");
- expect(sharedStyles).toContain(".app-tab-bar.separated-tab-layout:not(.vertical-tab-layout):not(:has(.wrap-mode)) .tab-group-entry:has(.tab-group-tab)");
- expect(sharedStyles).toContain('[data-group-mode="none"] .tab-section--horizontal');
- expect(sharedStyles).toContain("column-gap: 4px;");
- expect(sharedStyles).toContain(".app-tab-bar.separated-tab-layout.horizontal-fixed-tabs .app-tab-scroll:not(.wrap-mode)");
- expect(sharedStyles).toContain(".horizontal-fixed-tabs-scroll.wrap-mode");
- expect(sharedStyles).toContain("row-gap: 0.375rem !important;");
- expect(sharedStyles).toMatch(/\.horizontal-fixed-tabs-scroll\.wrap-mode\.classic-wrap\s*\{[^}]*row-gap:\s*0\.25rem !important;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar\.classic-tab-layout:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\) \.tab-group-entry\s*\{[^}]*height:\s*100%;[^}]*max-height:\s*none;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar:not\(\.vertical-tab-layout\):has\(\.wrap-mode\) \.tab-group-entry:has\(\.tab-group-tab\)::after\s*\{[^}]*bottom:\s*0;/s);
- expect(sharedStyles).toMatch(/\.app-tab-bar\.classic-tab-layout:not\(\.vertical-tab-layout\):not\(:has\(\.wrap-mode\)\)\[data-placement="top"\] \.app-tab-pill\s*\{[^}]*border-top-width:\s*0;/s);
- expect(sharedStyles).toContain("scroll-margin-inline-end: 1px;");
- });
-
- function sourceBetween(start: string, end: string): string {
- const startIndex = source.indexOf(start);
- const endIndex = source.indexOf(end, startIndex + start.length);
- expect(startIndex).toBeGreaterThanOrEqual(0);
- expect(endIndex).toBeGreaterThan(startIndex);
- return source.slice(startIndex, endIndex);
- }
-});
-
-describe("EditorGroupTabBar vertical placement", () => {
- const groupSource = readFileSync(resolve(specDir, "../EditorGroup.vue"), "utf8");
- const workspaceSource = readFileSync(resolve(specDir, "../SqlEditorWorkspace.vue"), "utf8");
- const appSource = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../../../App.vue"), "utf8");
-
- it("renders each pane's own bar as a vertical strip when placement is left/right", () => {
- expect(source).toContain('const isVerticalLayout = computed(() => settingsStore.editorSettings.tabPlacement === "left" || settingsStore.editorSettings.tabPlacement === "right");');
- expect(source).toContain('isVerticalLayout.value && props.tabBarCollapsed ? "vertical-tab-layout--collapsed" : ""');
- // The strip flips to a column with vertical scrolling; no horizontal strip remains.
- expect(source).toContain("isVerticalLayout ? 'flex-col items-stretch overflow-y-auto overflow-x-hidden py-1'");
- });
-
- it("keeps vertical rows fixed and aligns the sidebar toolbar with content headers", () => {
- expect(sharedStyles).toMatch(/\.vertical-tab-layout\s*\{[^}]*--tab-group-root-rail-x:\s*1\.16rem;[^}]*--tab-group-tab-inset:\s*1\.8rem;[^}]*--tab-group-branch-width:\s*0\.5rem;/s);
- expect(sharedStyles).toContain("width: calc(100% - var(--tab-group-tab-inset) - 0.25rem);");
- expect(sharedStyles).toContain("margin-inline: var(--tab-group-tab-inset) 0.25rem;");
- expect(sharedStyles).toContain("padding-inline: 0.2rem 0.25rem !important;");
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.tab-group-entry\s*\{[^}]*flex:\s*none;/s);
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.app-tab-scroll\s*\{[^}]*overflow-x:\s*hidden;/s);
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.app-tab-pill\s*\{[^}]*border-radius:\s*var\(--dbx-radius-md\);/s);
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.tab-group-entry\s*\{[^}]*max-height:\s*2rem;/s);
- expect(sharedStyles).toContain("max-height 140ms ease,");
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.tab-group-entry--collapsed\s*\{[^}]*max-height:\s*0;[^}]*opacity:\s*0;/s);
- expect(sharedStyles).toMatch(/\.vertical-tab-layout--collapsed \.tab-group-entry\s*\{[^}]*max-height:\s*2\.5rem;[^}]*overflow:\s*visible;/s);
- expect(sharedStyles).toMatch(/\.vertical-tab-layout--collapsed \.tab-group-entry--collapsed\s*\{[^}]*max-height:\s*0;[^}]*overflow:\s*hidden;/s);
- expect(source).toContain("if (isWrapLayout.value || isVerticalLayout.value) return;");
- expect(source).toContain("if (isWrapLayout.value) {");
- expect(source).toContain('inline: isVerticalLayout.value ? "nearest" : "center"');
- expect(source).toContain('class="flex h-9 shrink-0 items-center gap-0.5 border-b p-1"');
- expect(source).toContain('class="h-7 w-full pl-7 text-sm"');
- });
-
- it("positions each pane's bar by the global placement without mixing directions", () => {
- expect(groupSource).toContain('case "bottom":');
- expect(groupSource).toContain('return "flex-col-reverse";');
- expect(groupSource).toContain('case "left":');
- expect(groupSource).toContain('return "flex-row";');
- expect(groupSource).toContain('case "right":');
- expect(groupSource).toContain('return "flex-row-reverse";');
- // The editor toolbar stays atop the pane's content column in every placement.
- expect(groupSource).toContain('class="flex min-h-0 min-w-0 flex-1 flex-col"');
- });
-
- it("shares the vertical width/collapse state from App through the pane chain", () => {
- expect(appSource).toContain(':tab-bar-width="tabBarWidth"');
- expect(appSource).toContain(':tab-bar-collapsed="tabBarCollapsed"');
- expect(appSource).toContain('@start-resize="startTabBarResize"');
- expect(appSource).toContain('@toggle-collapse="toggleTabBarCollapsed"');
- expect(workspaceSource).toContain(':tab-bar-width="tabBarWidth"');
- expect(workspaceSource).toContain("@start-resize=\"emit('start-resize', $event)\"");
- expect(groupSource).toContain(':tab-bar-width="tabBarWidth"');
- // Dragging any pane's handle drives the shared resize handler.
- expect(source).toContain("@pointerdown=\"emit('start-resize', $event)\"");
- expect(source).toContain("@click=\"emit('toggle-collapse')\"");
- });
-
- it("keeps horizontal placements immune to the persisted collapse state", () => {
- expect(source).toContain("const isTabBarCollapsed = computed(() => isVerticalLayout.value && !!props.tabBarCollapsed);");
- expect(source).toContain("if (!isVerticalLayout.value) return undefined;");
- });
-
- it("uses the sidebar rail and soft active shadow for vertical pills", () => {
- expect(sharedStyles).toContain(".vertical-tab-layout .tab-group-tab::before");
- expect(sharedStyles).toMatch(/\.vertical-tab-layout \.tab-group-tab::before\s*\{[^}]*top:\s*-0\.25rem;[^}]*bottom:\s*-0\.25rem;/s);
- expect(sharedStyles).toContain('.vertical-tab-layout .app-tab-pill[data-active-tab="true"]');
- expect(sharedStyles).toContain("inset 0 0 0 1px color-mix");
- expect(sharedStyles).toContain(".vertical-tab-layout .tab-group-header:not(.tab-group-header--collapsed)::after");
- expect(sharedStyles).toContain("margin-inline: var(--tab-group-tab-inset) 0.25rem;");
- });
-});
-
function createHost(): HTMLDivElement {
const host = document.createElement("div");
document.body.appendChild(host);
@@ -738,12 +501,6 @@ describe("EditorGroupTabBar group behavior", () => {
const pill = host.querySelector<HTMLElement>(`[data-tab-id="${pluginTabId}"]`);
expect(pill).toBeTruthy();
expect(pill!.querySelector("img")).toBeTruthy();
- // The pill and the overflow popup list both render via TabModeIcon, whose
- // per-mode chain must keep the plugin-workbench plugin icon branch.
- const tabModeIconSource = readFileSync(resolve(specDir, "../TabModeIcon.vue"), "utf8");
- expect(tabModeIconSource).toContain("tab.mode === 'plugin-workbench' && tab.pluginWorkbench");
- expect(tabModeIconSource).toContain(':contribution-id="tab.pluginWorkbench.contributionId"');
- expect(source).toContain('<TabModeIcon :tab="entry.tab"');
app.unmount();
host.remove();
diff --git a/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.spec.ts b/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.spec.ts
deleted file mode 100644
index 368243cf41..0000000000
--- a/apps/desktop/src/components/layout/__tests__/EditorGroupTabBar.spec.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../EditorGroupTabBar.vue", import.meta.url), "utf8");
-const tabMenuSource = readFileSync(new URL("../../../lib/tabs/tabMenu.ts", import.meta.url), "utf8");
-
-describe("EditorGroupTabBar compatibility with AppTabBar", () => {
- it("keeps data-tab double-click Zen mode behavior", () => {
- expect(source).toContain('"toggle-zen-mode": []');
- expect(source).toContain('tab.mode === "data"');
- expect(source).toContain('emit("toggle-zen-mode")');
- expect(source).toContain("if (tab.id !== props.activeTabId) {");
- expect(source).toContain("startRenameTab(tab);");
- });
-
- it("only offers Duplicate for query tabs", () => {
- expect(tabMenuSource).toContain("visible: options.canRename");
- expect(source).toContain("createRenameDuplicateTabItems");
- });
-
- it("does not double-activate from the tab item click", () => {
- expect(source).toContain("function activateTab(tabId: string) {");
- expect(source).toContain('emit("activate-tab", tabId);');
- expect(source).not.toContain("queryStore.activateTabInGroup(props.groupId, tabId);");
- });
-
- it("cleans up drag listeners on cancel, blur, and unmount", () => {
- expect(source).toContain("function cleanupTabDrag(event?: Event)");
- expect(source).toContain('window.addEventListener("pointercancel", cleanupTabDrag)');
- expect(source).toContain('window.addEventListener("blur", cleanupTabDrag)');
- expect(source).toContain("onUnmounted(() => {");
- expect(source).toContain("cleanupTabDrag();");
- });
-
- it("validates drag source and target groups before moving", () => {
- expect(source).toContain("serializeTabDragPayload");
- expect(source).toContain("parseTabDragPayload");
- expect(source).toContain("const sourceGroupExists = queryStore.groups.some((group) => group.id === payload.sourceGroupId)");
- expect(source).toContain("const targetGroupExists = queryStore.groups.some((group) => group.id === targetGroupId)");
- expect(source).toContain("if (!sourceGroupExists || !targetGroupExists) {");
- });
-
- it("keeps pinned tabs in a separate row for horizontal placements", () => {
- expect(source).toContain('hasHorizontalFixedRows.value ? "horizontal-fixed-tabs" : ""');
- expect(source).toContain("horizontal-fixed-tabs-scroll");
- expect(source).toContain("const stripSections = computed(() =>");
- expect(source).toContain('{ key: "regular", pinned: false, entries: regularStripEntries.value }');
- expect(source).toContain('{ key: "fixed", pinned: true, entries: pinnedStripEntries.value }');
- expect(source).toContain("!isVerticalLayout.value && props.tabs.some((tab) => tab.pinned)");
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts
deleted file mode 100644
index 8a038e7b5c..0000000000
--- a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const panelSource = readFileSync(new URL("../SqlFilePanel.vue", import.meta.url), "utf8");
-
-describe("SqlFilePanel selection", () => {
- it("uses the shared ordered-list selection behavior", () => {
- expect(panelSource).toContain("orderedListSelectionIntent(event)");
- expect(panelSource).toContain("orderedListRangeAnchorIndex(visibleItems.value");
- expect(panelSource).not.toContain("anchorIndex ?? 0");
- });
-
- it("does not open or expand rows during modifier selection", () => {
- expect(panelSource).toMatch(/if \(selectionIntent === "range"\)[\s\S]*selectRangeTo\(currentIndex\);[\s\S]*return;/);
- expect(panelSource).toMatch(/if \(selectionIntent === "toggle"\)[\s\S]*selectionAnchorIndex\.value = currentIndex;[\s\S]*return;/);
- expect(panelSource).toMatch(/selectionAnchorIndex\.value = currentIndex;[\s\S]*activate\(\);/);
- });
-
- it("clears selection when a non-row area is clicked", () => {
- expect(panelSource).toContain('@click="handlePanelClick"');
- expect(panelSource).toContain("[data-sql-file-row='true']");
- expect(panelSource).toContain('data-sql-file-row="true"');
- });
-});
-
-describe("SqlFilePanel folder headers", () => {
- it("keeps sticky folder headers opaque while the file list scrolls", () => {
- expect(panelSource).toContain("bg-[color-mix(in_oklab,var(--muted)_10%,var(--background))] sticky top-0");
- expect(panelSource).toContain("hover:bg-[color-mix(in_oklab,var(--accent)_40%,var(--background))]");
- expect(panelSource).not.toContain("bg-muted/10 sticky top-0");
- });
-});
-
-describe("SqlFilePanel file renaming", () => {
- it("does not re-read a successfully renamed file before refreshing the tree", () => {
- const renameFunction = panelSource.match(/async function renameSqlFile\(\) \{[\s\S]*?\n\}/)?.[0];
-
- expect(renameFunction).toBeDefined();
- expect(renameFunction).toContain("queryStore.relocateExternalSqlFilePath(target.entry.path, nextPath)");
- expect(renameFunction).not.toContain("readExternalSqlFileSnapshot(nextPath)");
- });
-
- it("preserves non-SQL extensions while keeping SQL rename convenience", () => {
- expect(panelSource).toContain("normalizedRenamedFileName(fileNameInput.value, target.entry.name)");
- expect(panelSource).toContain("isSqlFilePath(currentName) ? normalizedSqlFileName(trimmed) : trimmed");
- });
-});
-
-describe("SqlFilePanel directory actions", () => {
- it("shows a new SQL file icon for nested directories", () => {
- expect(panelSource).toContain('@click.stop="openCreateDialog(folder.path, entry.path)"');
- });
-});
-
-describe("SqlFilePanel file filter", () => {
- it("restores the previous filter when the backend rejects the saved pattern", () => {
- expect(panelSource).toContain('message?.startsWith("Invalid file filter")');
- expect(panelSource).toContain("saveSqlFileFilter(previousFilter)");
- expect(panelSource).toContain('t("sqlFileTree.filterInvalid"');
- });
-
- it("renders the translated filter placeholder", () => {
- expect(panelSource).toContain("t('sqlFileTree.fileFilterPlaceholder')");
- expect(panelSource).not.toContain("const fileFilterPlaceholder =");
- });
-
- it("offers SQL execution only for SQL files", () => {
- expect(panelSource).toContain("if (isSqlFilePath(target.entry.name))");
- expect(panelSource).toContain("isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)");
- });
-});
diff --git a/apps/desktop/src/components/layout/__tests__/ToolbarUpdateIcon.spec.ts b/apps/desktop/src/components/layout/__tests__/ToolbarUpdateIcon.spec.ts
index f9ccc080f3..e877db39f2 100644
--- a/apps/desktop/src/components/layout/__tests__/ToolbarUpdateIcon.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/ToolbarUpdateIcon.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { createApp, h } from "vue";
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import ToolbarUpdateIcon from "../ToolbarUpdateIcon.vue";
describe("silent toolbar update icon", () => {
@@ -13,29 +11,4 @@ describe("silent toolbar update icon", () => {
expect(container.querySelector("[data-toolbar-update-progress], [data-toolbar-update-scan]")).toBeNull();
app.unmount();
});
-
- it("renders a text Update action whenever any aggregate update is available", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/layout/AppToolbar.vue"), "utf8");
-
- expect(source).toContain('v-if="hasUpdateAvailable"');
- expect(source).toContain("data-toolbar-update-action");
- expect(source).toContain('t("updates.updateAction")');
- });
-
- it("keeps the update entry visible when the appearance setting is off but an update is available", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/layout/AppToolbar.vue"), "utf8");
-
- expect(source).toContain("const showToolbarUpdateEntry = computed(() => toolbarItems.value.checkUpdates || props.hasUpdateAvailable);");
- expect(source).toContain("if (showToolbarUpdateEntry.value) {");
- expect(source).toContain('<template v-if="showToolbarUpdateEntry">');
- expect(source).not.toContain('<template v-if="toolbarItems.checkUpdates">');
- });
-
- it("passes only opt-out component badges to their separate toolbar entries", () => {
- const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/App.vue"), "utf8");
-
- expect(source).toContain(':agent-driver-update-count="showDriverStoreUpdateBadge"');
- expect(source).toContain(':has-mcp-update-available="showMcpSettingsUpdateBadge"');
- expect(source).not.toContain(':agent-driver-update-count="toolbarDriverUpdateCount"');
- });
});
diff --git a/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts b/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts
deleted file mode 100644
index 6b102c24d0..0000000000
--- a/apps/desktop/src/components/layout/__tests__/appContentSurfaces.contract.spec.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-
-// The editor-content wrapper carries a v-show guard that hides it while the
-// settings page or driver store is the active surface. A past merge resolved
-// this region by nesting the special surfaces INSIDE that guarded wrapper,
-// which display:none-d the settings page exactly when it was active. These
-// assertions pin the sibling order so a future merge cannot re-introduce it.
-describe("App main content surface structure", () => {
- it("hides only the editor workspace via the surface guard, never the special pages", () => {
- const guard = 'v-show="!driverStoreActive && !pluginCenterActive && !settingsStore.settingsPageActive"';
- // The empty-state slot shares the query surface's visibility guard.
- expect(appSource.split(guard).length - 1).toBe(1);
-
- // Source order: special surfaces first, then the guarded editor wrapper.
- const markers = ["<DriverStorePage", "<EditorSettingsPage", guard, "<SqlEditorWorkspace", "<WelcomeScreen"];
- const indices = markers.map((marker) => appSource.indexOf(marker));
- expect(indices.every((index) => index >= 0)).toBe(true);
- expect([...indices].sort((a, b) => a - b)).toEqual(indices);
- });
-
- it("keeps navigation independent from the workspace welcome content", () => {
- expect(appSource).toContain(':show-tab-navigation="queryStore.tabs.length > 0 || settingsPageTabOpen || driverStoreTabOpen || pluginCenterTabOpen"');
- expect(appSource).toContain(':active-tab="activeTab ?? undefined"');
- expect(appSource).toMatch(/<template #empty>\s*<WelcomeScreen/);
- expect(appSource).not.toContain('v-if="queryStore.tabs.length > 0 || settingsPageTabOpen || driverStoreTabOpen || pluginCenterTabOpen"');
- });
-
- it("returns to an open special page after the final query tab closes", () => {
- expect(appSource).toContain("else if (previousId) activateOpenSpecialPageFallback();");
- expect(appSource).toMatch(
- /function activateOpenSpecialPageFallback\(\)[\s\S]*?settingsPageTabOpen\.value[\s\S]*?activateMainContentSurface\("settings"\)[\s\S]*?driverStoreTabOpen\.value[\s\S]*?activateMainContentSurface\("driverStore"\)[\s\S]*?pluginCenterTabOpen\.value[\s\S]*?activateMainContentSurface\("pluginCenter"\)/,
- );
- });
-
- it("anchors the drag-back hit test on every pane strip and the special-surfaces bar", () => {
- const groupBarSource = readFileSync(new URL("../EditorGroupTabBar.vue", import.meta.url), "utf8");
- const slimBarSource = readFileSync(new URL("../AppTabBar.vue", import.meta.url), "utf8");
- expect(groupBarSource).toContain("data-main-tab-bar");
- expect(groupBarSource).toContain("'ring-2 ring-primary ring-inset': detachedDropTarget");
- expect(slimBarSource).toContain("data-special-page-tab-target");
- expect(slimBarSource).not.toContain("data-return-tab");
- // The split workspace renders several bars; the hit test must union their rects.
- expect(appSource).toContain('querySelectorAll<HTMLElement>("[data-main-tab-bar]")');
- });
-});
diff --git a/apps/desktop/src/components/nacos/__tests__/NacosAccessControlConsole.spec.ts b/apps/desktop/src/components/nacos/__tests__/NacosAccessControlConsole.spec.ts
index 6336ce0674..ac4d6ce932 100644
--- a/apps/desktop/src/components/nacos/__tests__/NacosAccessControlConsole.spec.ts
+++ b/apps/desktop/src/components/nacos/__tests__/NacosAccessControlConsole.spec.ts
@@ -61,11 +61,7 @@ vi.mock("@/components/nacos/NacosRoleAccessControl.vue", async () => {
import NacosAccessControlConsole from "../NacosAccessControlConsole.vue";
-const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/nacos/NacosAccessControlConsole.vue"), "utf8");
const legacySource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/nacos/NacosAccessControl.vue"), "utf8");
-const treeItemSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/sidebar/TreeItem.vue"), "utf8");
-const connectionTreeSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/sidebar/ConnectionTree.vue"), "utf8");
-const connectionStoreSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/stores/connectionStore.ts"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
async function settle() {
@@ -85,43 +81,6 @@ afterEach(() => {
});
describe("NacosAccessControlConsole", () => {
- it("uses the access-control header pattern for its navigation", () => {
- expect(source).toContain('class="flex h-14 shrink-0 flex-wrap items-center gap-3 border-b px-4"');
- expect(source).toContain('class="flex rounded-md border p-0.5 shadow-sm"');
- expect(source).toContain("<UsersRound");
- expect(source).toContain("<KeyRound");
- expect(source).toContain('t("nacos.accessControlTitle")');
- expect(source).toContain('t("nacos.accessControlDescription")');
- });
-
- it("only submits r-nacos namespace privilege fields supported by its API", () => {
- expect(legacySource).not.toContain("privilegeEnabled");
- expect(legacySource).toContain("whitelistIsAll: userForm.value.whitelistIsAll");
- expect(legacySource).toContain("blacklistIsAll: userForm.value.blacklistIsAll");
- expect(legacySource).toContain('import NacosNamespaceMultiSelect from "@/components/nacos/NacosNamespaceMultiSelect.vue"');
- expect(legacySource).toContain('v-model="userForm.whitelist"');
- expect(legacySource).toContain('v-model="userForm.blacklist"');
- expect(legacySource).toContain("whitelist: [...userForm.value.whitelist]");
- expect(legacySource).toContain("blacklist: [...userForm.value.blacklist]");
- expect(legacySource).not.toContain('<textarea v-model="userForm.whitelist"');
- expect(legacySource).not.toContain('<textarea v-model="userForm.blacklist"');
- });
-
- it("invalidates the r-nacos namespace picker when namespaces change", () => {
- expect(legacySource).toContain('import { subscribeNacosNamespacesChanged, type NacosNamespacesChangedDetail } from "@/lib/nacos/nacosNamespaceCache"');
- expect(legacySource).toContain("stopNacosNamespacesChangedListener = subscribeNacosNamespacesChanged(handleNacosNamespacesChanged)");
- expect(legacySource).toContain("if (detail.connectionId !== props.connectionId) return");
- expect(legacySource).toContain("if (userDialogOpen.value && isRNacos.value) void loadUserFormNamespaces(true)");
- expect(legacySource).toContain("stopNacosNamespacesChangedListener?.()");
- });
-
- it("notifies users when an official Nacos password reset succeeds or fails", () => {
- expect(legacySource).toContain('const userOperationNotice = ref<{ kind: "success" | "error"; message: string } | null>(null)');
- expect(legacySource).toContain("await syncCurrentConnectionPassword(username, userForm.value.password)");
- expect(legacySource).toContain('userOperationNotice.value = { kind: "error", message: t("nacos.passwordResetFailed", { message }) }');
- expect(legacySource).toContain('v-if="userOperationNotice"');
- });
-
it("requires exact username confirmation before deleting a user in the legacy workspace", () => {
expect(legacySource).toContain("const userDeleteConfirmed = computed(() => userDeleteConfirmation.value === pendingUserDelete.value?.username)");
expect(legacySource).toContain('@click="openDeleteUser(user)"');
@@ -129,29 +88,6 @@ describe("NacosAccessControlConsole", () => {
expect(legacySource).toContain(':disabled="deletingUser || !userDeleteConfirmed"');
});
- it("does not hide user deletion solely because the user has ROLE_ADMIN", () => {
- expect(legacySource).not.toContain('if (user.roles.includes("ROLE_ADMIN")) return');
- expect(legacySource).not.toContain("v-if=\"!user.roles.includes('ROLE_ADMIN')\"");
- });
-
- it("uses the same role creation icon in the legacy and enhanced workspaces", () => {
- expect(legacySource).toContain('import { KeyRound, Loader2, Pencil, Plus, RefreshCw, Search, ShieldCheck, ShieldPlus, Trash2, UserRound } from "@lucide/vue"');
- expect(legacySource).toContain('@click="openAssignRole"><ShieldPlus class="h-3.5 w-3.5" />{{ t("nacos.assignRole") }}');
- expect(readFileSync(resolve(process.cwd(), "apps/desktop/src/components/nacos/NacosRoleAccessControl.vue"), "utf8")).toContain('<ShieldPlus v-else class="h-3.5 w-3.5" />');
- });
-
- it("switches tabs when navigating between associated users and roles", () => {
- expect(source).toContain("@select-user=\"activeTab = 'users'\"");
- expect(source).toContain("@select-role=\"activeTab = 'roles'\"");
- });
-
- it("keeps the roles-only workspace reachable without an unavailable banner", () => {
- expect(source).toContain('if (!supportsUsers.value && supportsRoles.value) activeTab.value = "roles"');
- expect(source).toContain('v-if="!supportsUsers && !supportsRoles"');
- expect(connectionStoreSource).toContain("sidebarSnapshot.accessControl.listUsers.supported === true ||");
- expect(connectionStoreSource).toContain("sidebarSnapshot.accessControl.listRoleBindings.supported === true");
- });
-
it("keeps the roles-only workspace visible alongside the permission warning", async () => {
const unsupported = { supported: false, reason: "permissionDenied" as const };
mocks.connectionInfo = {
@@ -195,12 +131,6 @@ describe("NacosAccessControlConsole", () => {
expect(workspace?.getAttribute("data-tab")).toBe("roles");
});
- it("shares the directory-detail workspace across supported Nacos versions", () => {
- expect(source).toContain('import NacosRoleAccessControl from "@/components/nacos/NacosRoleAccessControl.vue"');
- expect(source).toContain('<NacosRoleAccessControl v-if="enhancedWorkspace && accessControl"');
- expect(source).toContain(':capabilities="accessControl"');
- });
-
it("keeps the enhanced read workspace visible when writes are permission denied", async () => {
const unsupported = { supported: false, reason: "permissionDenied" as const };
const supported = { supported: true };
@@ -290,10 +220,4 @@ describe("NacosAccessControlConsole", () => {
expect(mocks.nacosTestConnection).toHaveBeenLastCalledWith("nacos-refresh", true);
expect(mocks.refreshEnhancedWorkspace).toHaveBeenCalledTimes(1);
});
-
- it("internationalizes the sidebar entry, including trees persisted with the old label", () => {
- expect(connectionStoreSource).toContain('label: "nacos.accessControlSidebarLabel"');
- expect(treeItemSource).toContain('if (node.type === "nacos-access-control") return t("nacos.accessControlSidebarLabel")');
- expect(connectionTreeSource).toContain('node.type === "nacos-access-control" ? t("nacos.accessControlSidebarLabel") : node.label');
- });
});
diff --git a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts b/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts
deleted file mode 100644
index faca234288..0000000000
--- a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../NacosAdminConsole.vue", import.meta.url), "utf8");
-
-describe("NacosAdminConsole config workbench layout", () => {
- it("keeps access control outside the namespace-scoped workbench", () => {
- expect(source).not.toContain("NacosAccessControl");
- expect(source).toContain('type AdminTab = "configs" | "services";');
- });
-
- it("offers browser-console and Zen-mode actions in the workspace toolbar", () => {
- expect(source).toContain("resolveNacosConsoleUrl");
- expect(source).toContain("function openNacosConsole()");
- expect(source).toContain('t("nacos.openConsole")');
- expect(source).toContain("emit('toggleZenMode')");
- expect(source).toContain('props.zenMode ? t("nacos.exitZenMode") : t("nacos.enterZenMode")');
- });
-
- it("keeps JSON metadata available while offering an on-demand table dialog", () => {
- expect(source).toContain("function openInstanceMetadataTable(instance: NacosInstanceInfo)");
- expect(source).toContain('t("nacos.viewMetadataTable")');
- expect(source).toContain('class="nacos-instance-metadata-actions flex min-w-0 flex-wrap items-center gap-1"');
- expect(source).toContain('<details class="min-w-0 text-muted-foreground">');
- expect(source).not.toContain('<details class="min-w-0 flex-1 text-muted-foreground">');
- expect(source).toContain('v-model:open="instanceMetadataTableOpen"');
- expect(source).toContain('t("nacos.metadataKey")');
- expect(source).toContain('t("nacos.metadataValue")');
- expect(source).toContain("JSON.stringify(instance.metadata, null, 2)");
- });
-
- it("keeps the editor as the final and primary workbench surface", () => {
- const contextBar = source.indexOf('class="nacos-config-context-bar');
- const inspector = source.indexOf('class="nacos-config-inspector');
- const toolbar = source.indexOf('class="nacos-editor-toolbar');
- const editor = source.indexOf('ref="configEditorHost"');
-
- expect(contextBar).toBeGreaterThan(0);
- expect(inspector).toBeGreaterThan(contextBar);
- expect(toolbar).toBeGreaterThan(inspector);
- expect(editor).toBeGreaterThan(toolbar);
- });
-
- it("uses split-pane container queries instead of viewport breakpoints", () => {
- expect(source).toContain(".nacos-config-workbench {\n container-type: inline-size;");
- expect(source).toContain("@container (min-width: 960px)");
- expect(source).toContain("@container (max-width: 480px)");
- expect(source.indexOf('class="nacos-editor-actions-secondary')).toBeLessThan(source.indexOf('class="nacos-editor-actions-primary'));
- expect(source).toContain("grid-template-columns: minmax(0, 1fr) auto;");
- });
-
- it("tracks format and metadata changes as unsaved configuration state", () => {
- expect(source).toContain("configType.value !== originalConfigType.value");
- expect(source).toContain('(selectedConfig.value.appName || "") !== originalConfigMetadata.value.appName');
- expect(source).toContain('(selectedConfig.value.desc || "") !== originalConfigMetadata.value.desc');
- expect(source).toContain('(selectedConfig.value.tags || "") !== originalConfigMetadata.value.tags');
- });
-
- it("returns a stale batch apply to preview instead of retrying an expired plan", () => {
- const staleBranch = source.indexOf('isNacosErrorCode(error, "stalePreview")');
-
- expect(staleBranch).toBeGreaterThan(0);
- expect(source.indexOf("batchPreview.value = null;", staleBranch)).toBeGreaterThan(staleBranch);
- expect(source.indexOf("batchTransferRequest.value = null;", staleBranch)).toBeGreaterThan(staleBranch);
- expect(source.indexOf('batchError.value = t("nacos.previewExpired");', staleBranch)).toBeGreaterThan(staleBranch);
- });
-
- it("keeps service detail and instance loading as independent guarded requests", () => {
- expect(source).toContain("const serviceDetailRequestGuard = createNacosLatestRequestGuard();");
- expect(source).toContain("const instancesRequestGuard = createNacosLatestRequestGuard();");
- expect(source).toContain("await Promise.all([loadServiceDetail(), loadInstances()]);");
- });
-
- it("keeps configuration list responses scoped to the latest filters", () => {
- expect(source).toContain("const configListRequestGuard = createNacosLatestRequestGuard();");
- expect(source).toContain("const requestId = configListRequestGuard.begin();");
- expect(source).toContain("if (!isCurrentRequest()) return false;");
- expect(source).toContain("if (configListRequestGuard.isCurrent(requestId)) configLoading.value = false;");
- expect(source).toContain("const current = await loadConfigs(page);");
- expect(source).toContain("if (!current || !isConnectionNotFoundError(configError.value)");
- expect(source.match(/configListRequestGuard\.invalidate\(\);/g)?.length).toBeGreaterThanOrEqual(2);
- });
-
- it("keeps instance weight edits as drafts until the explicit save action", () => {
- expect(source).toContain("instanceWeightDrafts.value[instanceIdentity(instance)] = String(value);");
- expect(source).toContain('@click="requestInstanceWeightUpdate(instance)"');
- expect(source).not.toContain('@change="requestInstanceWeightUpdate(instance)"');
- });
-
- it("tracks instance operations by token so stale requests cannot lock a row forever", () => {
- expect(source).toContain("const updatingInstanceKeys = ref<Record<string, number>>({});");
- expect(source).toContain("const operationToken = beginInstanceOperation(key);");
- expect(source).toContain("clearInstanceOperation(key, operationToken);");
- expect(source).not.toContain('if (updateId === instanceUpdateSequence) updatingInstanceKey.value = "";');
- });
-
- it("prevents service-management dialogs from closing through outside clicks or Escape", () => {
- expect(source.match(/@pointer-down-outside\.prevent/g)?.length).toBeGreaterThanOrEqual(3);
- expect(source.match(/@interact-outside\.prevent/g)?.length).toBeGreaterThanOrEqual(3);
- expect(source.match(/@escape-key-down\.prevent/g)?.length).toBeGreaterThanOrEqual(3);
- });
-
- it("renders service details before the independently scrollable instance cards", () => {
- const detail = source.indexOf("nacos.serviceDetails");
- const instanceCards = source.indexOf('v-for="instance in instances"');
- expect(detail).toBeGreaterThan(0);
- expect(instanceCards).toBeGreaterThan(detail);
- });
-
- it("keeps verbose service details collapsed until the user expands them", () => {
- expect(source).toContain("const serviceDetailExpanded = ref(restoredUiState.serviceDetailExpanded ?? false);");
- });
-
- it("reserves the cluster-clear action space so entering a filter cannot reflow the toolbar", () => {
- expect(source).toContain('class="min-w-0 flex-1"');
- expect(source).toContain('class="nacos-service-filter-group flex min-w-0 items-center gap-1"');
- expect(source).toContain(':class="{ invisible: !serviceCluster }"');
- expect(source).toContain(':disabled="instancesLoading || !serviceCluster"');
- expect(source).not.toContain('v-if="serviceCluster"\n size="sm"');
- });
-
- it("uses the service split pane width for responsive service and instance layouts", () => {
- expect(source).toContain(".nacos-service-workbench {\n container: nacos-service-workbench / inline-size;");
- expect(source).toContain("@container nacos-service-workbench (max-width: 480px)");
- expect(source).toContain("@container nacos-service-workbench (min-width: 620px)");
- expect(source).toContain("@container nacos-service-workbench (min-width: 720px)");
- expect(source).toContain('class="nacos-instance-layout flex gap-3"');
- expect(source).toContain('class="nacos-instance-actions flex flex-wrap items-center gap-2"');
- expect(source).toContain("overflow-wrap: anywhere;");
- expect(source).not.toContain("xl:flex-row xl:items-start xl:justify-between");
- expect(source).not.toContain("sm:grid-cols-[auto_minmax(0,1fr)]");
- });
-
- it("adds icon-only clear controls to populated configuration and service filters", () => {
- for (const [filter, clear] of [
- ["configDataId", "clearConfigFilter('dataId')"],
- ["configGroup", "clearConfigFilter('group')"],
- ["configAppName", "clearConfigFilter('appName')"],
- ["serviceName", "clearServiceFilter('name')"],
- ["serviceGroup", "clearServiceFilter('group')"],
- ]) {
- expect(source).toContain(`v-if="${filter}"`);
- expect(source).toContain(`@click="${clear}"`);
- }
- expect(source).toContain("void loadConfigsWithRetry(1);");
- expect(source).toContain("void loadServicesWithRetry(1);");
- expect(source.match(/groupContains: true/g)?.length).toBeGreaterThanOrEqual(2);
- expect(source.match(/:aria-label="t\('nacos\.clear'\)"/g)?.length).toBeGreaterThanOrEqual(5);
- });
-
- it("uses green outlined styling for healthy instances and red styling for unhealthy instances", () => {
- expect(source).toContain("instance.healthy === false ? 'border-destructive/50 text-destructive' : 'border-emerald-500/50 text-emerald-700 dark:text-emerald-300'");
- });
-
- it("keeps the configuration editor zoom behavior aligned with the SQL editor", () => {
- expect(source).toContain("createEditorZoomCommitScheduler");
- expect(source).toContain("createEditorWheelZoomGestureGuard");
- expect(source).toContain("EditorView.domEventHandlers");
- expect(source).toContain("fontSizeFromWheelDelta(configEditorFontSize.value, event.deltaY)");
- expect(source).toContain("if (!configEditorWheelZoomGestureGuard.accepts(event)) return false;");
- expect(source).toContain("configEditorZoomCommitScheduler.dispose()");
- });
-
- it("keeps the configuration editor word wrapping aligned with the global editor setting", () => {
- expect(source).toContain("const configEditorWordWrap = new Compartment()");
- expect(source).toContain("configEditorWordWrap.of(editorSettings.wordWrap ? EditorView.lineWrapping : [])");
- expect(source).toContain("configEditorWordWrap.reconfigure(settings.wordWrap ? EditorView.lineWrapping : [])");
- expect(source).not.toContain("\n EditorView.lineWrapping,\n");
- });
-
- it("allows optional configuration columns to be hidden without hiding the data ID", () => {
- const configListHeader = source.indexOf('class="sticky top-0 z-20 grid border-b bg-muted');
- const columnVisibility = source.indexOf("nacos.visibleColumns");
-
- expect(configListHeader).toBeGreaterThan(0);
- expect(columnVisibility).toBeGreaterThan(configListHeader);
- expect(source).toContain("configListToggleableColumns");
- expect(source).toContain("DropdownMenuCheckboxItem");
- expect(source).toContain("nacos.visibleColumns");
- expect(source).toContain('v-for="(column, columnIndex) in configListColumns"');
- expect(source).toContain("column === 'dataId'");
- });
-
- it("marks the selected configuration without giving its row the header background", () => {
- expect(source).toContain("function isSelectedConfigListItem");
- expect(source).toContain(":class=\"{ 'border-l-2 border-l-primary': isSelectedConfigListItem(item) }\"");
- });
-
- it("adds a guarded batch delete action for selected configurations", () => {
- const toolbar = source.indexOf('class="flex min-w-0 flex-wrap items-center justify-end gap-2"');
- const batchDeleteButton = source.indexOf("v-if=\"activeTab === 'configs' && selectedConfigCount > 0\"");
-
- expect(toolbar).toBeGreaterThan(0);
- expect(batchDeleteButton).toBeGreaterThan(toolbar);
- expect(source).toContain('class="border-l border-current/30 pl-1.5 text-xs font-semibold tabular-nums"');
- expect(source).not.toContain('<Badge variant="outline" class="h-5 min-w-5 border-current px-1.5 text-current">{{ selectedConfigCount }}</Badge>');
- expect(source).toContain("const pendingBatchDelete = ref<NacosBatchDeleteSnapshot | null>(null);");
- expect(source).toContain("const canRequestBatchDeleteConfigs = computed(");
- expect(source).toContain("function requestBatchDeleteConfigs()");
- expect(source).toContain("async function deleteSelectedConfigs()");
- expect(source).toContain('await confirmNacosMutation(t("nacos.batchDelete"), snapshot.connectionId, snapshot.namespace)');
- expect(source).toContain("for (const key of snapshot.keys)");
- expect(source).toContain("await api.nacosDeleteConfig(snapshot.connectionId, key);");
- expect(source).toContain("function reconcileDeletedConfigSelection(deletedKeys: ReadonlySet<string>)");
- expect(source).toContain("reconcileDeletedConfigSelection(deletedKeys);");
- expect(source).toContain("nacos.batchDeletePartial");
- expect(source).toContain("nacos.batchDeleteInterrupted");
- });
-
- it("allows the Nacos configuration page size to be changed within the supported range", () => {
- expect(source).toContain("const NACOS_CONFIG_PAGE_SIZE_OPTIONS = [20, 50, 100, 200, 500] as const;");
- expect(source).toContain('const NACOS_CONFIG_PAGE_SIZE_STORAGE_KEY = "dbx-nacos-config-page-size";');
- expect(source).toContain("function setConfigPageSize(value: string)");
- expect(source).toContain("safeLocalStorageSet(NACOS_CONFIG_PAGE_SIZE_STORAGE_KEY, String(nextPageSize));");
- expect(source).toContain('t("nacos.configPageSize")');
- expect(source).toContain('v-for="size in NACOS_CONFIG_PAGE_SIZE_OPTIONS"');
- expect(source).toContain('@update:model-value="setConfigPageSize(String($event))"');
- expect(source).toContain(":aria-label=\"t('nacos.configPageSize')\"");
- expect(source).toContain('class="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 border-t px-3 py-2 text-xs text-muted-foreground"');
- expect(source).not.toContain('class="flex shrink-0 flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t px-3 py-2 text-xs text-muted-foreground"');
- const footerStart = source.indexOf('class="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 border-t px-3 py-2 text-xs text-muted-foreground"');
- const footerEnd = source.indexOf("</div>\n </div>\n </Pane>", footerStart);
- expect(source.slice(footerStart, footerEnd)).not.toContain('t("nacos.selectedCount", { count: selectedConfigCount })');
- expect(source).toContain('<ChevronLeft class="h-3.5 w-3.5" />');
- expect(source).toContain('<ChevronRight class="h-3.5 w-3.5" />');
- });
-
- it("uses semantic coloring for instance enable and disable actions", () => {
- expect(source).toContain("border-emerald-500/50 text-emerald-700");
- expect(source).toContain("border-destructive/50 text-destructive hover:bg-destructive/10");
- });
-
- it("hides instance operations that the selected API plane does not support", () => {
- expect(source).toContain('v-if="registerInstanceCapability.supported"');
- expect(source).toContain('v-if="updateInstanceHealthCapability.supported"');
- expect(source).toContain('v-if="deregisterInstanceCapability.supported"');
- });
-
- it("separates the service header, filtering controls, and management actions", () => {
- expect(source).toContain('<header class="shrink-0 border-b bg-background">');
- expect(source).toContain('class="nacos-service-toolbar flex flex-wrap items-center gap-x-4 gap-y-2 border-t bg-muted/30 px-4 py-2"');
- expect(source).toContain('t("nacos.serviceSettings")');
- expect(source).toContain('t("nacos.registerInstance")');
- });
-
- it("gates every Nacos mutation behind the shared production confirmation", () => {
- expect(source).toContain('import { executeWithProductionContextGuard } from "@/lib/database/productionExecutionGuard";');
- expect(source).toContain("async function confirmNacosMutation");
- expect(source).toContain('<ProductionContextBadge v-if="nacosProductionContext.active" compact />');
- expect(source.match(/await confirmNacosMutation\(/g)?.length).toBeGreaterThanOrEqual(9);
- for (const apiCall of ["nacosApplyConfigImport", "nacosApplyConfigTransfer", "nacosRollbackConfig", "nacosPublishConfig", "nacosDeleteConfig", "nacosUpdateInstance", "nacosCreateService", "nacosDeleteService", "nacosRegisterInstance", "nacosDeregisterInstance"]) {
- expect(source).toContain(apiCall);
- }
- });
-});
diff --git a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleYamlDiagnostics.spec.ts b/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleYamlDiagnostics.spec.ts
index 503462fd6e..5e610cc21f 100644
--- a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleYamlDiagnostics.spec.ts
+++ b/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleYamlDiagnostics.spec.ts
@@ -11,24 +11,6 @@ const source = readFileSync(new URL("../NacosAdminConsole.vue", import.meta.url)
* wiring that only exists inside this component, which is too large to mount.
*/
describe("NacosAdminConsole YAML diagnostics wiring", () => {
- it("installs and seeds the linter only for YAML configs", () => {
- expect(source).toContain('...(format === "yaml" ? [nacosConfigYamlLintExtension(configDiagnosticTranslate)] : []),');
- expect(source).toContain('if (format === "yaml") view.dispatch(setDiagnostics(view.state, nacosConfigYamlLintDiagnostics(view.state.doc.toString(), configDiagnosticTranslate)));');
- // A YAML-only extension: each helper has exactly one call site, inside the gated branch.
- expect(source.match(/nacosConfigYamlLintExtension\(/g)).toHaveLength(1);
- expect(source.match(/nacosConfigYamlLintDiagnostics\(/g)).toHaveLength(1);
- });
-
- it("keeps the lint logic out of the component", () => {
- // The component only formats and displays diagnostics; it never parses YAML itself.
- expect(source).not.toContain("analyzeNacosYaml(");
- expect(source).not.toContain("parseAllDocuments(");
- expect(source).not.toContain("parseDocument(");
- expect(source).toContain('import { setDiagnostics } from "@codemirror/lint";');
- expect(source).toContain('import { nacosConfigYamlLintDiagnostics, nacosConfigYamlLintExtension } from "@/lib/nacos/nacosConfigYamlLint";');
- expect(source).toContain('import { translateNacosYamlDiagnostic } from "@/lib/nacos/nacosYamlDiagnostics";');
- });
-
it("blocks publishing on error severity only", () => {
expect(source).toContain("if (nacosConfigValidationBlocksPublish(diagnostics)) {");
expect(source).not.toContain('diagnostics.some((diagnostic) => nacosConfigDiagnosticSeverity(diagnostic) === "error")');
@@ -37,22 +19,6 @@ describe("NacosAdminConsole YAML diagnostics wiring", () => {
expect(source).toContain("if (!showSuccess) return true;");
});
- it("does not double-mark YAML diagnostics with the legacy decoration", () => {
- expect(source).toContain('const configUsesYamlLint = computed(() => resolveNacosConfigFormat(configType.value, configDataId.value) === "yaml");');
- expect(source).toContain("configValidationHighlightActive = !configUsesYamlLint.value;");
- expect(source).toContain("effects: setConfigValidationHighlight.of(configUsesYamlLint.value ? [] : configValidationDiagnostics.value),");
- });
-
- it("reports severity and localized messages in the validation dialog", () => {
- expect(source).toContain('{{ configValidationHasError ? t("nacos.validationErrorTitle") : t("nacos.validationWarningTitle") }}');
- expect(source).toContain('{{ configValidationHasError ? t("nacos.validationErrorDescription") : t("nacos.validationWarningDescription") }}');
- // Asserted separately because the formatter may wrap the spans.
- expect(source).toContain("{{ configValidationSeverityLabel(diagnostic) }}");
- expect(source).toContain("{{ configValidationMessage(diagnostic) }}");
- // The localized text is resolved through the shared helper, never a raw parser string.
- expect(source).toContain("return diagnostic.code ? translateNacosYamlDiagnostic({ code: diagnostic.code, message: diagnostic.message, params: diagnostic.params ?? {} }, configDiagnosticTranslate) : diagnostic.message;");
- });
-
it("localizes every key it references, including the new severity labels", () => {
const referenced = [
"validationErrorTitle",
@@ -72,20 +38,4 @@ describe("NacosAdminConsole YAML diagnostics wiring", () => {
expect((nacos[key] as string).length, key).toBeGreaterThan(0);
}
});
-
- it("adds no watcher, listener, or observer for live diagnostics", () => {
- // CodeMirror owns the debounce; a component-level watcher would re-parse on
- // every keystroke and leak across config switches.
- expect(source.match(/watch\(/g)).toHaveLength(6);
- expect(source.match(/addEventListener\(/g)).toHaveLength(1);
- expect(source.match(/removeEventListener\(/g)).toHaveLength(1);
- expect(source.match(/onMounted\(/g)).toHaveLength(1);
- expect(source.match(/new ResizeObserver/g)).toHaveLength(1);
- });
-
- it("still tears the editor view down when the config changes", () => {
- expect(source).toContain("configEditorView.value?.destroy();");
- expect(source).toContain("configEditorView.value = null;");
- expect(source).toContain("await refreshConfigEditor();");
- });
});
diff --git a/apps/desktop/src/components/nacos/__tests__/NacosRoleAccessControl.spec.ts b/apps/desktop/src/components/nacos/__tests__/NacosRoleAccessControl.spec.ts
index 6aefafb261..a033754978 100644
--- a/apps/desktop/src/components/nacos/__tests__/NacosRoleAccessControl.spec.ts
+++ b/apps/desktop/src/components/nacos/__tests__/NacosRoleAccessControl.spec.ts
@@ -4,31 +4,6 @@ import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../NacosRoleAccessControl.vue", import.meta.url), "utf8");
describe("NacosRoleAccessControl", () => {
- it("uses a directory-detail layout for both users and roles", () => {
- expect(source).toContain('class="flex w-64 shrink-0 flex-col border-r');
- expect(source).toContain("v-if=\"tab === 'users'\"");
- expect(source).toContain("v-else-if=\"tab === 'roles' && selectedRole\"");
- });
-
- it("places the contextual create action beside search instead of duplicating refresh", () => {
- expect(source).toContain(":aria-label=\"tab === 'users' ? t('nacos.createUser') : t('nacos.accessCreateRole')\"");
- expect(source).toContain("@click=\"tab === 'users' ? openCreateUser() : openCreateRole()\"");
- expect(source).toContain("<UserPlus v-if=\"tab === 'users'\"");
- expect(source).toContain("<ShieldPlus v-else");
- expect(source).not.toContain(":aria-label=\"t('nacos.refresh')\"");
- expect(source).not.toContain('class="h-8 w-full"');
- });
-
- it("keeps role creation complete with per-namespace permissions", () => {
- expect(source).toContain("roleForm.newUsers");
- expect(source).toContain("moveNamespacesToGranted");
- expect(source).toContain('action: "rw"');
- expect(source).toContain("setPermissionAction");
- expect(source).toContain("accessUnassignedNamespaces");
- expect(source).toContain("accessGrantedNamespaces");
- expect(source).toContain('kind: "createRole"');
- });
-
it("keeps the selected role identity when opening the delete dialog", () => {
expect(source).toContain("resetRoleForm(selectedRole.value.role)");
});
@@ -46,67 +21,4 @@ describe("NacosRoleAccessControl", () => {
expect(source).toContain('t("nacos.accessDeleteUserConfirmationHint")');
expect(source).toContain("userDialog === 'delete' && !userDeleteConfirmed");
});
-
- it("lets the backend workflow protect only the final ROLE_ADMIN member", () => {
- expect(source).toContain("if (!selectedUser.value) return");
- expect(source).not.toContain('selectedUser.value.roles.includes("ROLE_ADMIN")');
- expect(source).not.toContain("v-if=\"!selectedUser.roles.includes('ROLE_ADMIN')\"");
- });
-
- it("shows complete IDs only in the unassigned namespace list", () => {
- expect(source).toContain('class="block truncate font-medium" :title="namespace.name"');
- expect(source).toContain('class="block break-all text-[10px] leading-4 text-muted-foreground" :title="namespace.id"');
- expect(source).not.toContain('<code v-if="namespace.name !== namespace.namespaceId"');
- });
-
- it("uses a wider, internally scrollable namespace picker and filters by name or ID", () => {
- expect(source).toContain('class="max-h-[90vh] overflow-auto sm:max-w-3xl"');
- expect(source).toContain("h-[min(28rem,45vh)]");
- expect(source).toContain('const id = item.id ?? item.namespaceId ?? ""');
- expect(source).toContain("item.name.toLocaleLowerCase().includes(normalized) || id.toLocaleLowerCase().includes(normalized)");
- expect(source).toContain(":aria-label=\"t('nacos.accessSearchNamespaces')\"");
- });
-
- it("refreshes the role namespace options after a namespace change for this connection", () => {
- expect(source).toContain('import { subscribeNacosNamespacesChanged, type NacosNamespacesChangedDetail } from "@/lib/nacos/nacosNamespaceCache"');
- expect(source).toContain("function handleNacosNamespacesChanged(detail: NacosNamespacesChangedDetail)");
- expect(source).toContain("if (detail.connectionId === props.connectionId) void loadSnapshot()");
- expect(source).toContain("stopNacosNamespacesChangedListener = subscribeNacosNamespacesChanged(handleNacosNamespacesChanged)");
- expect(source).toContain("stopNacosNamespacesChangedListener?.()");
- });
-
- it("merges split permission rows before editing an existing role", () => {
- expect(source).toContain("mergeNacosNamespacePermissionAssignments(managedRolePermissions.value)");
- });
-
- it("gates every mutation by its probed operation capability", () => {
- expect(source).toContain("capabilities: NacosAccessControlCapabilities");
- expect(source).toContain("const canCreateUser = computed");
- expect(source).toContain("const canGrantPermission = computed");
- expect(source).toContain("const userOperationWritable = computed");
- expect(source).toContain("const roleOperationWritable = computed");
- expect(source).toContain(':disabled="saving || !userOperationWritable ||');
- expect(source).toContain(':disabled="saving || !roleOperationWritable ||');
- });
-
- it("surfaces partial operations instead of hiding them in a toast", () => {
- expect(source).toContain("operationNeedsPasswords");
- expect(source).toContain("nacosRetryAccessOperation");
- expect(source).toContain("nacosUndoAccessOperation");
- expect(source).toContain("accessOperationResult");
- });
-
- it("uses the global notification for password reset results", () => {
- expect(source).toContain('import { useToast } from "@/composables/useToast"');
- expect(source).toContain("const { toast } = useToast()");
- expect(source).toContain('toast(t("nacos.passwordResetSucceeded", { username }), 2500)');
- expect(source).toContain('toast(t("nacos.passwordResetFailed", { message }), 5000)');
- });
-
- it("renders associated roles with the same navigable card pattern as role members", () => {
- expect(source).toContain('v-if="selectedUser.roles.length" class="flex flex-wrap gap-1.5 rounded border bg-muted/20 p-1.5"');
- expect(source).toContain(":title=\"t('nacos.accessOpenRole', { role })\"");
- expect(source).toContain('@click="openAssociatedRole(role)"');
- expect(source).toContain('emit("select-role")');
- });
});
diff --git a/apps/desktop/src/components/objects/ObjectBrowserClipboard.spec.ts b/apps/desktop/src/components/objects/ObjectBrowserClipboard.spec.ts
deleted file mode 100644
index b1c028e614..0000000000
--- a/apps/desktop/src/components/objects/ObjectBrowserClipboard.spec.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, expect, it } from "vitest";
-import objectBrowserSource from "./ObjectBrowser.vue?raw";
-
-describe("ObjectBrowser table clipboard context menu", () => {
- it("resolves recycled row menus when they are opened", () => {
- const lazyMenuBindings = objectBrowserSource.match(/:items="\(\) => getObjectBrowserMenuItems\(item\)"/g);
-
- expect(lazyMenuBindings).toHaveLength(2);
- });
-
- it("keeps paste on the copied row and allows replacing it from another row", () => {
- expect(objectBrowserSource).toMatch(/function tableClipboardMenuItems\(item: ObjectBrowserRow\)[\s\S]*?objectBrowserTableClipboardMenuState\(item\)[\s\S]*?state === "copy"[\s\S]*?state === "paste" \? \[pasteItem\] : \[copyItem, pasteItem\]/);
- expect(objectBrowserSource).toContain("...tableClipboardMenuItems(item)");
- });
-
- it("normalizes copied and target schemas before paste validation", () => {
- expect(objectBrowserSource).toMatch(/function normalizedObjectBrowserTableClipboardEntries\(\)[\s\S]*?normalizeObjectBrowserTableClipboardSchema\(entry\.schema, entry\.database, entry\.connectionId\)/);
- expect(objectBrowserSource).toMatch(/function canPasteTableClipboard\(\)[\s\S]*?tableClipboardMatchesTarget\(normalizedObjectBrowserTableClipboardEntries\(\), pasteTableTargetContext\(\)\)/);
- expect(objectBrowserSource).toMatch(/function pasteTableTargetContext\(\)[\s\S]*?normalizeObjectBrowserTableClipboardSchema\(selectedSchema\.value\)/);
- expect(objectBrowserSource).toMatch(/pasteTableEntries\.value = clipboard\.tables\.map[\s\S]*?normalizeObjectBrowserTableClipboardSchema\(entry\.schema, entry\.database, entry\.connectionId\)/);
- expect(objectBrowserSource).toMatch(/function normalizeObjectBrowserTableClipboardSchema[\s\S]*?connectionStore\.getConfig\(connectionId\) \?\? props\.connection[\s\S]*?!isSchemaAware\(connection\.db_type\)[\s\S]*?connection\.db_type !== "sqlite"[\s\S]*?return undefined/);
- });
-
- it("consumes only the clipboard used by a fully successful paste", () => {
- expect(objectBrowserSource).toMatch(
- /async function confirmPasteTable\(\)[\s\S]*?const clipboardAtPasteStart = connectionStore\.treeClipboard[\s\S]*?const pasteFeedback = tablePasteFeedback\(successCount, pasteFailCount, firstPasteError\)[\s\S]*?if \(pasteFailCount === 0\)[\s\S]*?connectionStore\.treeClipboard === clipboardAtPasteStart[\s\S]*?connectionStore\.treeClipboard = null/,
- );
- });
-
- it("shows the first paste failure reason without concatenating every error", () => {
- expect(objectBrowserSource).toMatch(/pasteFailCount\+\+/);
- expect(objectBrowserSource).toMatch(/firstPasteError \?\?= e/);
- expect(objectBrowserSource).toMatch(/batchPastePartialFail[\s\S]*?tableOperationFailed[\s\S]*?translateBackendError\(t, pasteFeedback\.firstError\)/);
- });
-
- it("refreshes created tables and retains the clipboard when a later paste step is cancelled", () => {
- expect(objectBrowserSource).toMatch(/let pasteCancelled = false[\s\S]*?let hasMutatedTable = false/);
- expect(objectBrowserSource).toMatch(/if \(!executed\) \{[\s\S]*?pasteCancelled = true;[\s\S]*?break;/);
- expect(objectBrowserSource).toMatch(/if \(pasteCancelled\) \{[\s\S]*?if \(hasMutatedTable\)[\s\S]*?await reload\(\)[\s\S]*?refreshObjectListTreeNode[\s\S]*?pasteTableCancelledAfterPartial[\s\S]*?return;/);
- });
-
- it("carries table comments through local copy and paste", () => {
- expect(objectBrowserSource).toMatch(/tableName: row\.name,\s*tableComment: row\.comment/);
- expect(objectBrowserSource).toMatch(/targetName: `\$\{entry\.tableName\}_copy`,[\s\S]*?tableComment: entry\.tableComment/);
- expect(objectBrowserSource).toMatch(/buildDuplicateStructurePlan\(entry\.sourceName, targetName, schema, entry\.tableComment/);
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/DatabaseBrowserFallback.spec.ts b/apps/desktop/src/components/objects/__tests__/DatabaseBrowserFallback.spec.ts
deleted file mode 100644
index 9a9972d198..0000000000
--- a/apps/desktop/src/components/objects/__tests__/DatabaseBrowserFallback.spec.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../DatabaseBrowser.vue", import.meta.url), "utf8");
-
-describe("DatabaseBrowser metadata fallback", () => {
- it("falls back to basic database names when extended metadata fails", () => {
- expect(source).toMatch(/await api\.listDatabaseMetadata\(props\.connection\.id\)[\s\S]*?catch \(metadataError\)[\s\S]*?await api\.listDatabases\(props\.connection\.id\)/);
- expect(source).toMatch(/catch \{\s*throw metadataError;\s*\}/);
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/DdlDialog.legacyScope.spec.ts b/apps/desktop/src/components/objects/__tests__/DdlDialog.legacyScope.spec.ts
index 063c318208..1254ba6013 100644
--- a/apps/desktop/src/components/objects/__tests__/DdlDialog.legacyScope.spec.ts
+++ b/apps/desktop/src/components/objects/__tests__/DdlDialog.legacyScope.spec.ts
@@ -1,14 +1,10 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { createApp, defineComponent, h, nextTick, type App } from "vue";
import { createI18n } from "vue-i18n";
import { afterEach, describe, expect, it } from "vitest";
import DdlScopeFixture from "./DdlDialog.legacyScope.fixture.vue";
-const ddlViewDialogSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/objects/DdlViewDialog.vue"), "utf8");
-
const mountedApps: App[] = [];
afterEach(() => {
@@ -61,14 +57,4 @@ describe("DdlViewDialog legacy fallback selectors", () => {
expect(content!.hasAttribute(scopeId!)).toBe(false);
expect(footer!.hasAttribute(scopeId!)).toBe(true);
});
-
- it("keeps the DDL dialog free of per-dialog legacy fallback rules", () => {
- // The dialog content element is rendered through reka-ui's portal Teleport and
- // never carries this component's scoped data-v attribute, so per-dialog rules
- // are avoided entirely: width comes from the global sm:max-w-190 legacy entry
- // and the footer layout from the global dialog-footer rule.
- expect(ddlViewDialogSource).not.toContain("dbx-legacy-webview");
- expect(ddlViewDialogSource).not.toContain("@media");
- expect(ddlViewDialogSource).toContain('class="dbx-ddl-view-dialog sm:max-w-190"');
- });
});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.crossDatabasePaste.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.crossDatabasePaste.spec.ts
deleted file mode 100644
index ef2a6d7cef..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.crossDatabasePaste.spec.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-describe("ObjectBrowser cross-database table paste", () => {
- it("routes a foreign table clipboard to the shared data-transfer dialog", () => {
- expect(objectBrowserSource).toContain("function canTransferTableClipboard()");
- expect(objectBrowserSource).toContain("function openTransferFromTableClipboard()");
- expect(objectBrowserSource).toContain("targetConnectionId: target.connectionId");
- expect(objectBrowserSource).toContain("targetDatabase: target.database");
- expect(objectBrowserSource).toMatch(/function objectBrowserTableClipboardMenuState[\s\S]*?tableClipboardMenuState\([\s\S]*?canTransferTableClipboard\(\),\s*\)/);
- });
-
- it("keeps the local duplicate-table paste path available", () => {
- expect(objectBrowserSource).toContain("if (canTransferTableClipboard()) {");
- expect(objectBrowserSource).toContain("if (!canPasteTableClipboard() && !canTransferTableClipboard()) return;");
- expect(objectBrowserSource).toContain("pasteTableMode.value = defaultPasteTableMode(effectiveDatabaseType.value);");
- expect(objectBrowserSource).toContain('normalizeNewTargetName: mode === "structure-and-data"');
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.spec.ts
deleted file mode 100644
index da78461743..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.eventCreate.spec.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-const contentAreaSource = readFileSync(new URL("../../layout/ContentArea.vue", import.meta.url), "utf8");
-
-function functionBody(name: string, source: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser MySQL Event CREATE navigation", () => {
- it("accepts an explicit create request prop next to the edit props", () => {
- expect(objectBrowserSource).toContain("initialEventCreateRequestId?: number;");
- expect(objectBrowserSource).toMatch(/initialEventName\?: string;[\s\S]*?initialEventCreateRequestId\?: number;[\s\S]*?initialObjectFilter\?: "tables" \| "events";/);
- });
-
- it("routes the initial event request through the shared resolver", () => {
- const openInitialEventIfNeeded = functionBody("openInitialEventIfNeeded", objectBrowserSource);
- expect(openInitialEventIfNeeded).toContain("resolveInitialEventEditorRequest({");
- expect(openInitialEventIfNeeded).toContain("eventCreateRequestId: props.initialEventCreateRequestId");
- expect(openInitialEventIfNeeded).toContain("openedRequestKey: openedInitialEvent.value");
- expect(openInitialEventIfNeeded).toContain("hasEventRow: rows.value.some");
- expect(openInitialEventIfNeeded).toContain("loadingObjects: loadingObjects.value");
- });
-
- it("opens the CREATE editor without any existing EVENT row", () => {
- const openInitialEventIfNeeded = functionBody("openInitialEventIfNeeded", objectBrowserSource);
- expect(openInitialEventIfNeeded).toContain('if (decision.type === "create") {');
- expect(openInitialEventIfNeeded).toContain("sidePanelRow.value = null;");
- expect(openInitialEventIfNeeded).toContain('sidePanelMode.value = "event-editor";');
- expect(openInitialEventIfNeeded).toContain("openedInitialEvent.value = decision.requestKey;");
- // The editor must see an empty name so MySqlEventEditor renders CREATE mode
- expect(openInitialEventIfNeeded).not.toContain("sidePanelRow.value = row;");
- });
-
- it("keeps the CREATE editor mounted when there is no EVENT row", () => {
- expect(objectBrowserSource).toContain('v-if="sidePanelRow || isEventEditor"');
- expect(objectBrowserSource).toContain('<MySqlEventEditor :key="eventEditorKey"');
- });
-
- it("renders the editor with an empty CREATE name and request-scoped instance", () => {
- expect(objectBrowserSource).toContain('<MySqlEventEditor :key="eventEditorKey" :connection="props.connection" :database="props.database" :schema="sidePanelRow?.schema || selectedSchema || props.database" :name="sidePanelRow?.name"');
- expect(objectBrowserSource).toMatch(/const eventEditorKey = computed\(\(\) =>[\s\S]*?createRequestId: props\.initialEventCreateRequestId[\s\S]*?openRequestId: props\.initialEventOpenRequestId[\s\S]*?rowId: sidePanelRow\.value\?\.id/);
- });
-
- it("re-triggers a create request when the request id changes on a reused tab", () => {
- expect(objectBrowserSource).toContain("() => props.initialEventCreateRequestId");
- expect(objectBrowserSource).toMatch(/watch\(\[\(\) => props\.initialEventName, \(\) => props\.initialEventOpenRequestId, \(\) => props\.initialEventCreateRequestId\][\s\S]*?openedInitialEvent\.value = "";[\s\S]*?openInitialEventIfNeeded\(\);/);
- expect(objectBrowserSource).toContain('if (name || createRequestId !== undefined) objectFilter.value = "events";');
- });
-
- it("lists the events filter as the preferred view for a create request", () => {
- expect(objectBrowserSource).toMatch(/const preferredFilter = props\.initialEventName \|\| props\.initialEventCreateRequestId !== undefined \? "events" : \(props\.selectedObjectFilter \?\? props\.initialObjectFilter \?\? "tables"\);/);
- });
-
- it("ContentArea passes the create request id into ObjectBrowser", () => {
- expect(contentAreaSource).toContain(':initial-event-name="activeTab.objectBrowser?.eventName"');
- expect(contentAreaSource).toContain(':initial-event-create-request-id="activeTab.objectBrowser?.eventCreateRequestId"');
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.mongoCollectionStats.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.mongoCollectionStats.spec.ts
deleted file mode 100644
index 29c14dcdab..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.mongoCollectionStats.spec.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-describe("ObjectBrowser MongoDB collection statistics (#9705)", () => {
- it("requests table statistics for every engine, MongoDB included", () => {
- // The loader used to skip MongoDB wholesale, so the columns below stayed
- // empty even though the backend can now answer `collStats` per collection.
- expect(objectBrowserSource).not.toContain('if (props.connection.db_type !== "mongodb") void loadObjectStatistics');
- expect(objectBrowserSource).toContain("void loadObjectStatistics(request, cacheWriteToken, cachedAt);");
- });
-
- it("renders the row/size columns and their sort keys for MongoDB", () => {
- expect(objectBrowserSource).toContain("const showObjectRowStats = computed(() => showTableStatistics.value);");
- expect(objectBrowserSource).toContain("const supportsObjectSizeStats = computed(() => !isVictoriaMetrics.value);");
- });
-
- it("keeps the batch table toolbar SQL-only", () => {
- expect(objectBrowserSource).toContain("const supportsBatchTableActions = computed(() => !isVictoriaMetrics.value && !isMongodb.value);");
- for (const handler of ["openBatchDatabaseExport", "copySelectedTablesToClipboard", "requestBatchTruncateTables", "requestBatchEmptyTables", "requestBatchDropTables"]) {
- const button = new RegExp(`v-if="supportsBatchTableActions[^"]*"[^>]*@click="${handler}"`);
- expect(objectBrowserSource).toMatch(button);
- }
- // No toolbar action may key off the stats-column flag any more.
- expect(objectBrowserSource).not.toContain('v-if="supportsObjectSizeStats');
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaFallback.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaFallback.spec.ts
deleted file mode 100644
index 019f3c99eb..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaFallback.spec.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-function functionBody(name: string, source: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser object-list schema fallback (#8301)", () => {
- it("resolves the listObjects schema through the shared Dameng-aware helper", () => {
- const loadObjects = functionBody("loadObjects", objectBrowserSource);
- expect(loadObjects).toContain("needsSchema.value ? objectListSchemaForConnection(props.connection, selectedSchema.value) : props.database");
- expect(objectBrowserSource).toContain('objectListSchemaForConnection, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect"');
- });
-
- it("routes the schema through the request scope used by listObjects", () => {
- const loadSqlObjectBrowserRows = functionBody("loadSqlObjectBrowserRows", objectBrowserSource);
- expect(loadSqlObjectBrowserRows).toContain("api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema");
- const loadObjects = functionBody("loadObjects", objectBrowserSource);
- expect(loadObjects).toContain("objectBrowserRowsCacheScope(schema)");
- });
-
- it("keeps the reload chain alive when loadSchemas rejects", () => {
- const reload = functionBody("reload", objectBrowserSource);
- expect(reload).toMatch(/try \{\s*if \(!\(await loadSchemas\(epoch\)\)\) return;\s*\} catch/);
- const catchClause = reload.slice(reload.indexOf("} catch"));
- // The failure path must not clear the selection (props.schema / current value)
- // and must still load objects — Dameng then falls back to the username.
- expect(catchClause).not.toContain("selectedSchema.value =");
- expect(catchClause).toContain("console.warn");
- expect(reload.lastIndexOf("await loadObjects")).toBeGreaterThan(reload.indexOf("} catch"));
- });
-
- it("leaves the selected schema untouched when listSchemas itself rejects", () => {
- const loadSchemas = functionBody("loadSchemas", objectBrowserSource);
- // Every selectedSchema assignment in the try block sits behind the awaited
- // listSchemas call, so a rejection keeps the current selection intact.
- const tryStart = loadSchemas.indexOf("try {");
- const apiCall = loadSchemas.indexOf("await api.listSchemas", tryStart);
- const firstAssignment = loadSchemas.indexOf("selectedSchema.value =", apiCall);
- expect(apiCall).toBeGreaterThan(tryStart);
- expect(firstAssignment).toBeGreaterThan(apiCall);
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.toolbarOverflowFloor.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.toolbarOverflowFloor.spec.ts
deleted file mode 100644
index 297de5a31f..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.toolbarOverflowFloor.spec.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Issue #9200: when the "Browse Objects" pane is narrow, the keyword search box
-// collapsed to a sliver and the "全部/表/视图" chips were painted on top of it,
-// instead of the toolbar condensing its controls into the overflow menu.
-//
-// useToolbarOverflow only condenses while the row reports real overflow, and its
-// contract requires "non-shrinking (shrink-0) or floored (min-w-*) children":
-// 1. the collapsed search wrapper was `min-w-0`, so the wrapper dropped to 0
-// width while the input inside still painted at its padding width (58px),
-// drawing on top of the neighbouring filter chips;
-// 2. the search + filter group carried `min-w-24`, which overrode the
-// content-based minimum and let the group shrink below its own content, so
-// its children spilled into the sort control instead of overflowing the row;
-// 3. the filter chips allowed their labels to wrap, so the group's min-content
-// (longest word) was far below the width the chips actually occupy.
-// Each of the three is load-bearing; removing any one of them brings the overlap
-// back at some pane width.
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-describe("ObjectBrowser toolbar condenses instead of overlapping when narrow", () => {
- it("floors the search box and lets the search + filter group keep its content minimum", () => {
- // The floored wrapper keeps the input from painting over its neighbours, and
- // dropping `min-w-24` lets the group's content-based minimum stop the spill
- // into the sort control, so the row reports overflow instead.
- expect(objectBrowserSource).toMatch(/<div class="flex flex-1 items-center gap-2">\s*<div class="relative min-w-\[6rem\] flex-1">/);
- });
-
- it("pins the filter chips to their single-line width so the row reports overflow", () => {
- expect(objectBrowserSource).toMatch(/<button\s+v-for="filter in objectFilters"[\s\S]*?class="h-6 shrink-0 whitespace-nowrap rounded-sm/);
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.verticalScrollbarViewport.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.verticalScrollbarViewport.spec.ts
deleted file mode 100644
index d7bf24fe66..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.verticalScrollbarViewport.spec.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-// Regression test for #8885: when the object-browser columns are wider than the
-// panel, the vertical scrollbar must stay pinned to the visible right edge
-// instead of travelling with the content. The list scroller therefore owns the
-// horizontal scrolling (with the content width applied to its inner item
-// wrapper), while the header is clipped and aligned programmatically.
-describe("ObjectBrowser vertical scrollbar viewport lock", () => {
- it("keeps the outer table container from scrolling horizontally", () => {
- const tableMatch = /class="object-browser-table[^"]*"/.exec(source);
- expect(tableMatch).not.toBeNull();
- expect(tableMatch![0]).toContain("overflow-hidden");
- expect(tableMatch![0]).not.toContain("overflow-x-auto");
- });
-
- it("moves the content min-width onto the scroller's inner wrapper", () => {
- const scrollerMatch = /<RecycleScroller[^>]*listScrollerRef[^>]*>/.exec(source);
- expect(scrollerMatch).not.toBeNull();
- expect(scrollerMatch![0]).toContain("--dbx-object-grid-min-width");
- expect(scrollerMatch![0]).not.toContain("minWidth:");
- expect(source).toContain(".object-browser-scroller {");
- expect(source).toContain("overflow-x: auto;");
- expect(source).toContain("min-width: var(--dbx-object-grid-min-width, 0px);");
- });
-
- it("clips the header and syncs its scroll position with the scroller", () => {
- const headerMatch = /ref="objectListHeaderRef"[^>]*/.exec(source);
- expect(headerMatch).not.toBeNull();
- expect(headerMatch![0]).toContain("overflow-hidden");
- expect(source).toContain("function syncObjectListHeaderScroll(");
- expect(source).toContain("header.scrollLeft = el.scrollLeft");
- // The sync runs on every scroller scroll event, when the scroller (re)attaches,
- // and whenever the column widths change the content width.
- const scrollHandler = source.indexOf("function onObjectsScroll(");
- expect(source.slice(scrollHandler, scrollHandler + 300)).toContain("syncObjectListHeaderScroll()");
- expect(source).toContain("nextTick(() => syncObjectListHeaderScroll())");
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserExport.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserExport.spec.ts
deleted file mode 100644
index e578c96286..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserExport.spec.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-function functionBody(name: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser XLSX export", () => {
- it("asks for export options before opening the save dialog", () => {
- const dialog = functionBody("showObjectBrowserXlsxHeaderDialog");
- const exportDataXlsx = functionBody("exportDataXlsx");
-
- expect(dialog).toContain("showHeaderOptions: hasComments");
- expect(exportDataXlsx).toContain("hasXlsxHeaderComments(columnInfos?.map((column) => column.comment))");
- expect(exportDataXlsx.indexOf("await showObjectBrowserXlsxHeaderDialog(")).toBeLessThan(exportDataXlsx.indexOf('await exportTableData(row, "xlsx", columnInfos, exportOptions.headerMode, exportOptions.autoFilter)'));
- });
-
- it("asks for the SQL INSERT mode before opening the save dialog", () => {
- const exportData = functionBody("exportData");
- const exportTableData = functionBody("exportTableData");
-
- expect(exportData).toContain("await showSqlInsertModeDialog({ allowSplit: true })");
- expect(exportData.indexOf("await showSqlInsertModeDialog({ allowSplit: true })")).toBeLessThan(exportData.indexOf("await exportTableData("));
- expect(exportTableData).toContain('...(format === "sql" ? { insertMode, splitMaxMb } : {})');
- });
-
- it("falls back to field-name headers when column metadata is unavailable", () => {
- const exportDataXlsx = functionBody("exportDataXlsx");
-
- expect(exportDataXlsx).toContain("catch {\n // Export still works with field-name headers when column metadata is unavailable.\n }");
- expect(exportDataXlsx).toContain('await exportTableData(row, "xlsx", columnInfos, exportOptions.headerMode, exportOptions.autoFilter)');
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts
deleted file mode 100644
index ba81818fc2..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserMetadataRefresh.spec.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-function functionBody(name: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser table metadata refresh", () => {
- it("refreshes the object list and the open table-info tab from the toolbar", () => {
- const refresh = functionBody("refresh");
-
- expect(refresh).toContain("void reload({ preserveExistingRows: true });");
- expect(refresh).toContain("void refreshActiveTableInfo();");
- expect(source).toContain('@click="refresh"');
- });
-
- it("invalidates stale requests and reloads only the active metadata surface", () => {
- const refreshTableInfo = functionBody("refreshActiveTableInfo");
-
- expect(refreshTableInfo).toContain('sidePanelMode.value !== "table-info" || !sidePanelRow.value');
- expect(refreshTableInfo).toContain("sidePanelGuard.bump();");
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "ddl"[\s\S]*?rawTableDdlContent\.value = "";[\s\S]*?await fetchTableDdl\(true\);/);
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "columns"[\s\S]*?tableColumns\.value = \[\];[\s\S]*?await fetchTableColumns\(true\);/);
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "indexes"[\s\S]*?tableIndexes\.value = \[\];[\s\S]*?await fetchTableIndexes\(true\);/);
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "foreignKeys"[\s\S]*?tableForeignKeys\.value = \[\];[\s\S]*?await fetchTableForeignKeys\(true\);/);
- expect(refreshTableInfo).toMatch(/tableInfoTab\.value === "triggers"[\s\S]*?tableTriggers\.value = \[\];[\s\S]*?await fetchTableTriggers\(true\);/);
- });
-
- it("routes table-info metadata through the object caches", () => {
- expect(source).toContain('from "@/lib/metadata/objectDdlCache"');
- expect(source).toContain('from "@/lib/metadata/objectMetadataCache"');
- expect(functionBody("fetchTableDdl")).toContain("loadObjectDdl(");
- for (const name of ["fetchTableColumns", "fetchTableIndexes", "fetchTableForeignKeys", "fetchTableTriggers"]) {
- expect(functionBody(name)).toContain("loadObjectMetadataFacet(");
- expect(functionBody(name)).not.toContain(".value.length > 0");
- }
- });
-
- it("shares the DDL refresh preference and exposes an explicit refresh action", () => {
- expect(source).toContain("async function fetchTableDdl(force = settingsStore.editorSettings.refreshDdlOnOpen)");
- expect(source).toContain('@click="refreshActiveTableInfo"');
- expect(source).not.toContain("setTableInfoRefreshDdlOnOpen");
- });
-
- it("keeps automatic object reloads free of extra metadata requests", () => {
- expect(functionBody("reload")).not.toContain("refreshActiveTableInfo");
- });
-
- it("leaves a failed facet eligible for retry", () => {
- for (const name of ["fetchTableDdl", "fetchTableColumns", "fetchTableIndexes", "fetchTableForeignKeys", "fetchTableTriggers"]) {
- const body = functionBody(name);
- expect(body).toContain("let loadedSuccessfully = false;");
- expect(body).toMatch(/loadedSuccessfully = true;/);
- expect(body).toMatch(/Loaded\.value = loadedSuccessfully;/);
- }
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserScaffoldRefresh.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserScaffoldRefresh.spec.ts
deleted file mode 100644
index cccbf4e58e..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserScaffoldRefresh.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-function functionBody(name: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser scaffold refresh race", () => {
- it("restores cached rows without revalidating on a tab remount", () => {
- const body = functionBody("loadObjects");
-
- const cachedBranch = body.indexOf("const cached =");
- const cachedReturn = body.indexOf("finishOnce();\n return;", cachedBranch);
-
- expect(cachedBranch).toBeGreaterThanOrEqual(0);
- expect(cachedReturn).toBeGreaterThan(cachedBranch);
- expect(body.slice(cachedBranch, cachedReturn)).not.toContain("cached.stale");
- expect(body.slice(cachedBranch, cachedReturn)).not.toContain("refreshingObjects.value = true;");
- });
-
- it("exposes a non-blocking refresh flag distinct from the blocking full-area load", () => {
- expect(source).toContain("const refreshingObjects = ref(false);");
- expect(functionBody("loadObjects")).toContain("refreshingObjects.value = true;");
- expect(functionBody("loadObjects")).toContain("loadingObjects.value = true;");
- });
-
- it("keeps visible rows on a background revalidate failure (scaffold-preserving error)", () => {
- expect(source).toContain('const scaffoldRefreshError = ref("");');
- const body = functionBody("loadObjects");
- // A scaffold/refresh revalidate failure must route to the non-blocking banner
- // (scaffoldRefreshError) and keep the visible rows, not replace them with the
- // blocking full-area error.
- expect(body).toContain("scaffoldRefresh = true;");
- expect(body).toContain("if (scaffoldRefresh) {");
- expect(body).toContain("scaffoldRefreshError.value = translateBackendError(t, e)");
- expect(source).toContain('v-if="scaffoldRefreshError"');
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserSearchPersistence.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserSearchPersistence.spec.ts
deleted file mode 100644
index 77ff41f750..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserSearchPersistence.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// Issues #8236 and #8285: switching away from the "Browse Objects" tab and
-// back reset the keyword search, including after opening and closing a table,
-// because ObjectBrowser has no <KeepAlive> around
-// it (ContentArea renders it inside a plain v-else-if chain) and its `search`
-// ref was always seeded to "". The fix threads the value through
-// activeTab.objectBrowser.searchQuery, mirroring the existing viewport
-// persistence path.
-
-const objectBrowserSource = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-const contentAreaSource = readFileSync(new URL("../../layout/ContentArea.vue", import.meta.url), "utf8");
-const querySurfacesSource = readFileSync(new URL("../../layout/querySurfaces.ts", import.meta.url), "utf8");
-const contentSurfaceEventsSource = readFileSync(new URL("../../../lib/tabs/contentSurfaceEvents.ts", import.meta.url), "utf8");
-const queryStoreSource = readFileSync(new URL("../../../stores/queryStore.ts", import.meta.url), "utf8");
-const databaseTypesSource = readFileSync(new URL("../../../types/database.ts", import.meta.url), "utf8");
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-
-describe("ObjectBrowser keyword search survives tab switches", () => {
- it("seeds the local search ref from a persisted initial value instead of always starting empty", () => {
- expect(objectBrowserSource).toContain("initialSearchQuery?: string;");
- expect(objectBrowserSource).toContain('const search = ref(props.initialSearchQuery ?? "");');
- });
-
- it("emits searchChange whenever the keyword changes, so the parent can persist it", () => {
- expect(objectBrowserSource).toContain("searchChange: [query: string];");
- expect(objectBrowserSource).toMatch(/watch\(search, \(value\) => \{\s*scrollObjectsToTop\(\);\s*emit\("searchChange", value\);\s*\}\);/);
- });
-
- it("ContentArea binds the persisted search query as a prop and forwards the change event", () => {
- expect(contentAreaSource).toContain(':initial-search-query="activeTab.objectBrowser?.searchQuery"');
- expect(contentAreaSource).toContain("@search-change=\"emit('objectBrowserSearchChange', activeTab.id, $event)\"");
- });
-
- it("keeps the original object tab as the owner when a table is opened", () => {
- expect(appSource).toMatch(/@open-object-table="\s*\n?\s*\(tabId: string, target: \{[\s\S]*?\) => \{[\s\S]*?const tab = queryStore\.tabs\.find\(\(candidate\) => candidate\.id === tabId\) \?\? activeTab;[\s\S]*?openObjectBrowserTableTarget\(/);
- expect(appSource).toContain('@object-browser-search-change="(tabId: string, query: string) => queryStore.updateObjectBrowserSearch(tabId, query)"');
- });
-
- it("the surface event contract and forwarding list both know about objectBrowserSearchChange", () => {
- expect(querySurfacesSource).toContain("objectBrowserSearchChange: [tabId: string, query: string];");
- expect(contentSurfaceEventsSource).toContain('"objectBrowserSearchChange",');
- });
-
- it("queryStore persists the search query onto the tab's objectBrowser state", () => {
- expect(queryStoreSource).toContain("function updateObjectBrowserSearch(id: string, query: string)");
- expect(queryStoreSource).toContain("tab.objectBrowser = { ...tab.objectBrowser, searchQuery: query };");
- expect(queryStoreSource).toContain("updateObjectBrowserSearch,");
- });
-
- it("the tab type declares searchQuery on objectBrowser state", () => {
- expect(databaseTypesSource).toMatch(/objectBrowser\?:\s*\{[^}]*searchQuery\?:\s*string;/s);
- });
-});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowserViewportPersistence.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowserViewportPersistence.spec.ts
deleted file mode 100644
index a41514bb42..0000000000
--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowserViewportPersistence.spec.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../ObjectBrowser.vue", import.meta.url), "utf8");
-
-function functionBody(name: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
-describe("ObjectBrowser viewport persistence", () => {
- it("flushes the latest scroll position before generating SQL", () => {
- const body = functionBody("openNewQuery");
- const flushIndex = body.indexOf("flushObjectBrowserViewport();");
- const createTabIndex = body.indexOf("queryStore.createTab");
-
- expect(flushIndex).toBeGreaterThanOrEqual(0);
- expect(createTabIndex).toBeGreaterThan(flushIndex);
- });
-});
diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts b/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts
index 0403cec228..4637c4584c 100644
--- a/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts
+++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.spec.ts
@@ -3,7 +3,6 @@
import { createApp, nextTick, ref, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
-import pluginHostSource from "./PluginWorkbenchHost.vue?raw";
const mocks = vi.hoisted(() => ({
readPluginUiEntry: vi.fn(),
@@ -198,17 +197,3 @@ describe("PluginWorkbenchHost initialization", () => {
elementFromPoint.mockRestore();
});
});
-
-describe("PluginWorkbenchHost file-save handle tracking", () => {
- const hostSource = pluginHostSource;
- const beginSaveSource = hostSource.slice(hostSource.indexOf("async function beginPluginFileSave"), hostSource.indexOf("async function writePluginFileChunkById"));
-
- it("opens the save target through openTauriPluginFile so the write handle joins openTauriHandles", () => {
- // A beginSave the plugin abandons (no finish/cancel) must still be
- // reclaimed by unmount's disposeLocalFileHandles; a direct
- // openPluginLocalFile call would leak the handle in the shared
- // 64-slot registry for the lifetime of the workbench host.
- expect(beginSaveSource).toContain("await openTauriPluginFile(pluginId, path, true)");
- expect(beginSaveSource).not.toContain("openPluginLocalFile");
- });
-});
diff --git a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
index 8cce58250c..3d4ec7aea1 100644
--- a/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
+++ b/apps/desktop/src/components/plugins/__tests__/PluginContributionsPanelBatch.spec.ts
@@ -1,7 +1,6 @@
// @vitest-environment happy-dom
import { createApp, nextTick, type App, type ComponentPublicInstance } from "vue";
-import { readFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { InstalledPlugin, PluginRepositoryCatalogResult } from "@/types/database";
import type { MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";
@@ -494,11 +493,6 @@ function singleApi(single: Single) {
const replacements = ["marketplace", "rollback", "package", "url"] as const;
describe("PluginContributionsPanel workbench refresh", () => {
- it("connects the panel event to the App workbench refresh entry", () => {
- const source = readFileSync("apps/desktop/src/App.vue", "utf8");
- expect(source).toMatch(/<PluginCenterPage\b[^>]*@plugin-runtime-replaced="refreshPluginWorkbenches"/);
- });
-
it.each(replacements)("refreshes once with the returned plugin ID after Web %s succeeds", async (single) => {
singleApi(single).mockResolvedValueOnce({ plugin: installed("replaced", "2.0.0") });
await startSingle(single);
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.groupingToggle.spec.ts b/apps/desktop/src/components/redis/RedisKeyBrowser.groupingToggle.spec.ts
deleted file mode 100644
index 6bb637aec0..0000000000
--- a/apps/desktop/src/components/redis/RedisKeyBrowser.groupingToggle.spec.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import source from "./RedisKeyBrowser.vue?raw";
-import { expect, it } from "vitest";
-
-it("uses the fuzzy toggle visual states while preserving grouping persistence and busy guards", () => {
- const button = source.match(/<Button\b[^>]*data-redis-grouping-toggle[^>]*>/s)?.[0];
- expect(button).toBeDefined();
- expect(button).toContain("customGrouping.enabled ? 'bg-accent text-accent-foreground' : 'border border-dashed border-border/70 text-muted-foreground hover:text-foreground'");
- expect(button).toContain(':aria-pressed="customGrouping.enabled"');
- expect(button).toContain(':disabled="groupingSaving || isFetchingAll"');
- expect(button).toContain("saveGrouping({ ...customGrouping, enabled: !customGrouping.enabled })");
-});
diff --git a/apps/desktop/src/components/redis/__tests__/RedisKeyBrowser.toolbarLayout.spec.ts b/apps/desktop/src/components/redis/__tests__/RedisKeyBrowser.toolbarLayout.spec.ts
deleted file mode 100644
index eb3bae66a8..0000000000
--- a/apps/desktop/src/components/redis/__tests__/RedisKeyBrowser.toolbarLayout.spec.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-// jsdom cannot lay out flex/grid or evaluate container queries, so the #9356
-// overlap fix is guarded at the source level: the toolbar actions group must
-// wrap (a nowrap + justify-end row spills LEFT onto the search-mode segmented
-// control when the key pane is ~320px..730px wide), and the batch-expiry label
-// must collapse to an icon before the row reaches that overflow band.
-const source = readFileSync(new URL("../RedisKeyBrowser.vue", import.meta.url), "utf8");
-
-function styleRule(selector: string): string {
- // Anchor on a line-start selector so template `class="..."` occurrences never match.
- const start = source.indexOf(`\n${selector} {`);
- expect(start).toBeGreaterThan(-1);
- const open = source.indexOf("{", start);
- const close = source.indexOf("}", open);
- return source.slice(open + 1, close);
-}
-
-describe("redis key browser toolbar layout (#9356)", () => {
- it("lets the toolbar actions wrap instead of overflowing onto the search-mode group", () => {
- expect(styleRule(".redis-key-toolbar-actions")).toContain("flex-wrap: wrap");
- });
-
- it("collapses the batch-expiry label to an icon in a 740px container tier", () => {
- const tierStart = source.indexOf("@container (max-width: 740px)");
- const tierEnd = source.indexOf("@container (max-width: 340px)");
- expect(tierStart).toBeGreaterThan(-1);
- expect(tierEnd).toBeGreaterThan(tierStart);
- const tierBody = source.slice(tierStart, tierEnd);
- expect(tierBody).toContain(".redis-expiry-label");
- expect(tierBody).toContain(".redis-expiry-icon");
- });
-
- it("switches to two toolbar rows in the 340px container tier", () => {
- const tierStart = source.indexOf("@container (max-width: 340px)");
- const tierEnd = source.indexOf("@container (max-width: 240px)");
- expect(tierStart).toBeGreaterThan(-1);
- expect(tierEnd).toBeGreaterThan(tierStart);
- const tierBody = source.slice(tierStart, tierEnd);
- expect(tierBody).toContain("grid-template-columns: auto minmax(0, 1fr)");
- const actionsRule = tierBody.slice(tierBody.indexOf(".redis-key-toolbar-actions"));
- expect(actionsRule).toContain("grid-row: 2");
- expect(actionsRule).toContain("justify-content: flex-start");
- });
-
- it("marks the batch-expiry icon and label in the template", () => {
- expect(source).toMatch(/class="[^"]*redis-expiry-icon[^"]*"/);
- expect(source).toMatch(/<span class="redis-expiry-label">/);
- expect(source).toContain(`:aria-label="t('redis.batchExpiry')"`);
- });
-
- it("keeps the key pane at a 360px minimum width", () => {
- expect(source).toContain("min-width: min(360px, 64%)");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.arrowFocus.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.arrowFocus.spec.ts
deleted file mode 100644
index d21e3ffadd..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.arrowFocus.spec.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const connectionTreeSource = readFileSync(new URL("../ConnectionTree.vue", import.meta.url), "utf8");
-
-function focusSidebarTreeNodeBody(): string {
- const match = connectionTreeSource.match(/^async function focusSidebarTreeNode[\s\S]*?^}/m);
- expect(match).not.toBeNull();
- return match![0]!;
-}
-
-describe("ConnectionTree arrow focus", () => {
- it("scrolls before querying the row so out-of-window virtual rows materialize first", () => {
- const body = focusSidebarTreeNodeBody();
- const scroll = body.indexOf("await scrollToSidebarNode(nodeId);");
- const renderWait = body.indexOf("await waitForSidebarRenderFrame();");
- const query = body.indexOf('root.querySelector<HTMLElement>(`[data-node-id="${CSS.escape(nodeId)}"]`)');
- const missingRowGuard = body.indexOf("if (!row) return;");
- const focus = body.indexOf("row.focus({ preventScroll: true });");
-
- // RecycleScroller only keeps the materialized window in the DOM, so the
- // index-driven scroll must run (no-op when already visible) and one render
- // frame must pass before the row can be queried and focused.
- for (const position of [scroll, renderWait, query, missingRowGuard, focus]) expect(position).toBeGreaterThan(-1);
- expect(scroll).toBeLessThan(renderWait);
- expect(renderWait).toBeLessThan(query);
- expect(query).toBeLessThan(missingRowGuard);
- expect(missingRowGuard).toBeLessThan(focus);
- });
-
- it("keeps focus a no-op when the row is still not rendered after the scroll", () => {
- const body = focusSidebarTreeNodeBody();
- expect(body).toContain("if (!row) return;");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.collapsedSearch.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.collapsedSearch.spec.ts
index 0464b4cd3e..1d3a340f6a 100644
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.collapsedSearch.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.collapsedSearch.spec.ts
@@ -1,50 +1,7 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { runSidebarSearchTasks } from "../sidebarSearchTaskRunner";
-const source = readFileSync(new URL("../ConnectionTree.vue", import.meta.url), "utf8");
-
describe("ConnectionTree global search loading", () => {
- it("discovers collapsed database and schema containers before searching object groups", () => {
- expect(source).toContain("function isSidebarSearchContainer(node: TreeNode)");
- // A collapsed database already holds the saved-SQL root, so it has children
- // even when its object groups were never fetched; the search has to look for
- // a searchable group instead of an empty child list.
- expect(source).toMatch(/isSidebarSearchContainer\(node\) && needsSidebarObjectGroupDiscovery\(node, searchableObjectGroupTypes\)/);
- expect(source).not.toMatch(/isSidebarSearchContainer\(node\) && !node\.children\?\.length/);
- expect(source).toContain("store.loadTreeNodeChildren(node, { force: true, expectedSidebarSearchQuery: store.sidebarSearchQuery, sidebarSearch: true })");
- expect(source).toContain("searchExpansionState.markFiltered(node.id, wasCollapsed)");
- expect(source).toMatch(/if \(refreshedNodeIds && node\.children\) \{[\s\S]*?searchableObjectGroupTypes\.has\(child\.type\)/);
- });
-
- it("deduplicates each node within a search round and restores tracked nodes", () => {
- expect(source).toContain("const scheduledNodeIds = new Set<string>();");
- expect(source).toContain("while (deferredSearchQuery.value === query && store.sidebarSearchQuery === query)");
- expect(source).toContain("const restoreTasks = !newQuery && oldQuery ? restoreTrackedSearchTargets() : [];");
- expect(source).toContain("if (shouldCollapse) node.isExpanded = false;");
- expect(source).toContain("store.discardFilteredTreeNodeChildren(node.id);");
- });
-
- it("restores the pre-search children of an expanded group instead of reloading page one", () => {
- // Clearing a remote search must put back the pages the user had loaded
- // through "load more"; only an uncaptured group falls back to a reload.
- expect(source).toContain("} else if (!store.restoreFilteredObjectGroupChildren(node)) {");
- expect(source).toMatch(/restoreFilteredObjectGroupChildren\(node\)\) \{[\s\S]*?tasks\.push\(\(\) => store\.loadObjectGroupChildren\(node, \{ force: true, sidebarSearch: true \}\)\);/);
- });
-
- it("never lets the global search connect a connection on the user's behalf", () => {
- // Searching the sidebar is a background projection. Reconnecting here is what
- // surfaced a raw SQL Server TLS/login error for a connection whose saved
- // database no longer exists, so only already-connected connections may be
- // refreshed and every search-driven load is tagged for the store.
- expect(source).toContain("const connectionIsConnected = store.connectedIds.has(node.connectionId);");
- expect(source).toMatch(/if \(!connectionIsConnected \|\| node\.connectionId !== store\.activeConnectionId\) return;/);
- // Search-driven loads are tagged so the store degrades a failed reconnect to a
- // one-line skip hint instead of the raw driver error (see the store spec).
- expect(source.match(/sidebarSearch: true/g)?.length ?? 0).toBeGreaterThanOrEqual(7);
- expect(source).not.toMatch(/tasks\.push\(\(\) => store\.connect\(/);
- });
-
it("limits concurrent metadata loads without dropping a task", async () => {
let activeTasks = 0;
let maximumActiveTasks = 0;
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.locateCollapsedGroup.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.locateCollapsedGroup.spec.ts
deleted file mode 100644
index 4c2b68bd4d..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.locateCollapsedGroup.spec.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const connectionTreeSource = readFileSync(new URL("../ConnectionTree.vue", import.meta.url), "utf8");
-
-describe("ConnectionTree locate in collapsed groups", () => {
- it("reopens collapsed connection groups on the node path through the persisted layout op", () => {
- // Group expansion must flow through store.expandConnectionGroups so
- // layout.collapsed is flipped and the next layout rebuild keeps the group
- // open; flipping isExpanded directly would be reverted by that rebuild.
- expect(connectionTreeSource).toMatch(/const collapsedGroupIds = nodePath\s*\.filter\(\(node\) => node\.type === "connection-group" && !node\.isExpanded\)\s*\.map\(\(node\) => node\.id\);/);
- // The expansion happens before the flat-tree match that drives selection,
- // scrolling and flashing, so the reopened groups are visible to it.
- expect(connectionTreeSource).toMatch(/store\.expandConnectionGroups\(collapsedGroupIds\);\s*\}\s*\n\s*await nextTick\(\);\s*\n\s*const match = target \? findSidebarNodeForTarget\(target, flatNodes\.value\) : null;/);
- });
-
- it("still gates generic ancestor expansion on loaded children only (#5850)", () => {
- expect(connectionTreeSource).toMatch(/if \(!ancestor\.isExpanded && store\.canUseLoadedTreeNodeToggle\(ancestor\)\) \{\s*ancestor\.isExpanded = true;\s*\}/);
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.selectionPruning.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.selectionPruning.spec.ts
deleted file mode 100644
index 01fe5cd6e6..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.selectionPruning.spec.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const connectionTreeSource = readFileSync(new URL("../ConnectionTree.vue", import.meta.url), "utf8");
-
-describe("ConnectionTree selection pruning", () => {
- it("does not track the visible tree outside multi-selection", () => {
- expect(connectionTreeSource).toContain("store.connectionMultiSelectActive || store.selectedTreeNodeIds.length > 1");
- expect(connectionTreeSource).toContain("hasTreeMultiSelection.value ? flatTreeIndex.value.nodeById : null");
- expect(connectionTreeSource).not.toMatch(/watch\(\s*visibleNodes,/);
- });
-
- it("defers selection cleanup until after the tree render", () => {
- expect(connectionTreeSource).toMatch(/pruneTreeSelectionToVisibleNodeIds[\s\S]*?\{ flush: "post" \}/);
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.backupMenu.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.backupMenu.spec.ts
deleted file mode 100644
index 5795a16d9c..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.backupMenu.spec.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-
-describe("SidebarTreeRuntimeHost database backup menu", () => {
- it("uses the database backup support matrix independently from full-database export", () => {
- expect(source).toMatch(/const canOpenScheduledBackups = computed\(\(\) => \{[\s\S]*supportsScheduledDatabaseBackup\(rawDatabaseType\(\)\)/);
- expect(source).toMatch(/if \(canOpenScheduledBackups\.value\) \{[\s\S]*action: openScheduledBackups/);
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.compileRefresh.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.compileRefresh.spec.ts
deleted file mode 100644
index b01e4715bd..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.compileRefresh.spec.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string) {
- const start = source.indexOf(`async function ${name}`);
- const end = source.indexOf(`async function ${nextName}`, start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return source.slice(start, end);
-}
-
-describe("SidebarTreeRuntimeHost compile refresh routing", () => {
- it("refreshes the Dameng schema object list after compiling a view", () => {
- const compile = functionSource("compileDamengView", "executeXuguSchedulerJobAction");
-
- expect(compile).toContain("await connectionStore.refreshObjectListTreeNode(node.connectionId, node.database, node.schema);");
- expect(compile).not.toContain("await connectionStore.refreshTreeNode(node);");
- });
-
- it("keeps Xugu compile refresh behavior unchanged", () => {
- const compile = functionSource("compileXuguObject", "compileDamengView");
-
- expect(compile).toContain("await connectionStore.refreshTreeNode(node);");
- expect(compile).not.toContain("await connectionStore.refreshObjectListTreeNode");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.createViewQuoteSetting.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.createViewQuoteSetting.spec.ts
deleted file mode 100644
index e8c0286af7..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.createViewQuoteSetting.spec.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-
-const runtimeSource = readFileSync(fileURLToPath(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url)), "utf8");
-
-function functionSource(name: string): string {
- const start = runtimeSource.indexOf(`function ${name}(`);
- expect(start, `${name} not found`).toBeGreaterThan(-1);
- const next = runtimeSource.indexOf("\nfunction ", start + 1);
- return runtimeSource.slice(start, next === -1 ? undefined : next);
-}
-
-describe("SidebarTreeRuntimeHost createView identifier quoting (#9099)", () => {
- it("forwards the generate-SQL settings to qualifiedTableName", () => {
- const createView = functionSource("createView");
- const callStart = createView.indexOf("qualifiedTableName({");
- expect(callStart).toBeGreaterThan(-1);
- const callEnd = createView.indexOf("});", callStart);
- const call = createView.slice(callStart, callEnd);
-
- // Turning off the quote toggle must reach qualifiedTableName; otherwise it
- // unconditionally quotes the schema/view name regardless of the setting.
- expect(call).toContain("quoteIdentifiers: settingsStore.editorSettings.generateSqlQuoteIdentifiers");
- expect(call).toContain("includeDatabaseName: settingsStore.editorSettings.generateSqlIncludeDatabaseName");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.ddlQualifierSetting.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.ddlQualifierSetting.spec.ts
deleted file mode 100644
index 611a71094c..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.ddlQualifierSetting.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-
-const runtimeSource = readFileSync(fileURLToPath(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url)), "utf8");
-
-function asyncFunctionSource(name: string): string {
- const start = runtimeSource.indexOf(`async function ${name}(`);
- expect(start, `${name} not found`).toBeGreaterThan(-1);
- const next = runtimeSource.indexOf("\nasync function ", start + 1);
- return runtimeSource.slice(start, next === -1 ? undefined : next);
-}
-
-describe("SidebarTreeRuntimeHost DDL database qualifier setting (#9421)", () => {
- it("applies the setting with each target catalog before identifier quote formatting", () => {
- const openDdl = asyncFunctionSource("openSidebarMultiTableDdlTab");
- const formatterCall = openDdl.indexOf("formatSidebarDdlTemplateForDisplay(");
-
- expect(formatterCall).toBeGreaterThan(-1);
- expect(openDdl.slice(formatterCall, openDdl.indexOf(");", formatterCall))).toContain("target.catalog");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.executionIdOptIn.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.executionIdOptIn.spec.ts
deleted file mode 100644
index e5b53d51a6..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.executionIdOptIn.spec.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-
-describe("executeTreeNodeSqlWithProductionGuard executionId", () => {
- it("only registers a backend execution id for callers that opt in, instead of generating one for every caller", () => {
- expect(source).toContain("const executionId = options.executionId;");
- expect(source).not.toMatch(/executionId\s*=\s*options\.executionId\s*\?\?\s*uuid\(\)/);
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.objectCacheRefresh.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.objectCacheRefresh.spec.ts
deleted file mode 100644
index ff616d8129..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.objectCacheRefresh.spec.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-
-/**
- * Secondary evidence for the connection-node refresh wiring. The primary
- * behavioral coverage lives in connectionStore.refresh.spec.ts and the
- * metadata cache specs; this guards the component-side routing and error
- * classification without mounting the full sidebar tree host.
- */
-describe("SidebarTreeRuntimeHost connection refresh cache invalidation", () => {
- it("routes connection-node refresh through the awaited strict store method", () => {
- expect(source).toMatch(/if \(node\.type === "connection" && node\.connectionId\) \{\s*try \{\s*await connectionStore\.refreshConnectionTreeNode\(node\);/);
- });
-
- it("reports object cache failures distinctly without opening the driver store", () => {
- const connectionBranch = source.slice(source.indexOf("await connectionStore.refreshConnectionTreeNode(node);"), source.indexOf("await connectionStore.refreshTreeNode(node);", source.indexOf("await connectionStore.refreshConnectionTreeNode(node);")));
- const cacheFailureBlock = connectionBranch.match(/if \(isObjectCacheInvalidationError\(e\)\) \{[\s\S]*?\n\s*return;\s*\n/);
- expect(cacheFailureBlock).not.toBeNull();
- expect(cacheFailureBlock![0]).toContain('t("connection.objectCacheRefreshFailed"');
- expect(cacheFailureBlock![0]).not.toContain("openDriverStoreForInstallError");
- });
-
- it("keeps the regular refresh path and its connection-error handling for other nodes", () => {
- const refresh = source.slice(source.indexOf("async function refresh()"), source.indexOf("async function copyName()"));
- const nonConnection = refresh.slice(refresh.indexOf("await connectionStore.refreshTreeNode(node);"));
- expect(nonConnection).toMatch(/toast\(t\("connection\.connectFailed"/);
- expect(nonConnection).toContain("openDriverStoreForInstallError");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/VisibleNacosNamespacesDialog.spec.ts b/apps/desktop/src/components/sidebar/__tests__/VisibleNacosNamespacesDialog.spec.ts
deleted file mode 100644
index 8fa0c885e4..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/VisibleNacosNamespacesDialog.spec.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../VisibleNacosNamespacesDialog.vue", import.meta.url), "utf8");
-
-describe("VisibleNacosNamespacesDialog", () => {
- it("offers only namespaces readable by the current Nacos connection", () => {
- expect(source).toContain("loadReadableNacosNamespaces(props.connectionId, api)");
- expect(source).toContain("recordPrimaryVisibleObjectNames(props.connectionId, namespaces.value.map(nacosNamespaceValue))");
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts b/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts
deleted file mode 100644
index 423bfd4db4..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const runtimeSource = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-
-describe("cross-database table paste", () => {
- it("keeps the live node active after async tree loads", () => {
- expect(runtimeSource).toContain("function emitNodeToggled(node: TreeNode, wasExpanded: boolean, expandedOverride?: boolean)");
- expect(runtimeSource).toContain("findSidebarActionTarget(connectionStore.treeNodes, createSidebarActionTarget(node)) ?? node");
- expect(runtimeSource).toContain("activeNode.value = liveNode");
- expect(runtimeSource).toContain("emitNodeToggled(node, wasExpanded, false)");
- expect(runtimeSource).toMatch(/await connectionStore\.loadMongoDatabases\(node\.connectionId\);[\s\S]*?emitNodeToggled\(node, wasExpanded\)/);
- expect(runtimeSource).toContain("connectionStore.cancelTreeNodeLoad(node.id)");
- });
-
- it("routes a table clipboard from another context to data transfer", () => {
- expect(runtimeSource).toContain("function canTransferTreeClipboardToCurrentNode()");
- expect(runtimeSource).toContain("function openTransferFromTreeClipboard()");
- expect(runtimeSource).toContain("targetConnectionId: target.connectionId");
- expect(runtimeSource).toContain("targetDatabase: target.database");
- expect(runtimeSource).toContain("tables: clipboard.tables.map((entry) => entry.tableName)");
- expect(runtimeSource).toMatch(/function treeTableClipboardMenuItems[\s\S]*?tableClipboardMenuState\([\s\S]*?canTransferTreeClipboardToCurrentNode\(\),\s*\)/);
- });
-
- it("retains the local duplicate-table paste path", () => {
- expect(runtimeSource).toContain("if (canTransferTreeClipboardToCurrentNode()) return openTransferFromTreeClipboard();");
- expect(runtimeSource).toContain("pasteTableMode.value = defaultPasteTableMode(currentDatabaseType());");
- expect(runtimeSource).toContain('normalizeNewTargetName: mode === "structure-and-data"');
- });
-
- it("carries table comments through the local sidebar paste path", () => {
- expect(runtimeSource).toMatch(/tableName: node\.label,\s*tableComment: node\.comment/);
- expect(runtimeSource).toMatch(/targetName: `\$\{entry\.tableName\}_copy`,[\s\S]*?tableComment: entry\.tableComment/);
- expect(runtimeSource).toMatch(/targetName,\s*tableComment: entry\.tableComment/);
- expect(runtimeSource).toContain("executeAsScript: plan.executeAsScript");
- });
-
- it("uses the shared metadata-aware structure plan for duplicate and paste", () => {
- expect(runtimeSource).toContain("buildDuplicateTableStructurePlan");
- expect(runtimeSource).toMatch(/buildDuplicateTableStructurePlan\(\{[\s\S]*?connectionId: node\.connectionId[\s\S]*?sourceName: node\.label[\s\S]*?tableComment: node\.comment/);
- expect(runtimeSource).toMatch(/buildDuplicateTableStructurePlan\(\{[\s\S]*?connectionId: entry\.connectionId[\s\S]*?sourceName: entry\.sourceName[\s\S]*?tableComment: entry\.tableComment/);
- expect(runtimeSource).toContain("sourceColumns = plan.sourceColumns");
- });
-
- it("shows the first paste failure reason without concatenating every error", () => {
- expect(runtimeSource).toMatch(/pasteFailCount\+\+/);
- expect(runtimeSource).toMatch(/firstPasteError \?\?= e/);
- expect(runtimeSource).toMatch(/batchPastePartialFail[\s\S]*?tableOperationFailed[\s\S]*?translateBackendError\(t, pasteFeedback\.firstError\)/);
- });
-});
diff --git a/apps/desktop/src/components/sidebar/__tests__/mongoCollectionImportExportMenu.spec.ts b/apps/desktop/src/components/sidebar/__tests__/mongoCollectionImportExportMenu.spec.ts
deleted file mode 100644
index 8cf0c8babc..0000000000
--- a/apps/desktop/src/components/sidebar/__tests__/mongoCollectionImportExportMenu.spec.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { readFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-
-const here = dirname(fileURLToPath(import.meta.url));
-
-function read(relativePath: string) {
- return readFileSync(resolve(here, relativePath), "utf8");
-}
-
-describe("mongo collection import/export UI", () => {
- it("adds table-style import/export to the original mongo-collection menu", () => {
- const menu = read("../SidebarTreeRuntimeHost.vue");
- const start = menu.indexOf('if (node.type === "mongo-collection") {\n items.push({ label: t("contextMenu.copyName")');
- expect(start).toBeGreaterThan(-1);
- const end = menu.indexOf("return true;", start);
- const block = menu.slice(start, end);
- expect(block).toContain('t("contextMenu.viewData")');
- expect(block).toContain('t("contextMenu.cloneCollection")');
- expect(block.indexOf('t("contextMenu.cloneCollection")')).toBeLessThan(block.indexOf('t("contextMenu.importData")'));
- expect(block).toContain("openMongoImport");
- expect(block).toContain('t("contextMenu.exportData")');
- expect(block).toContain('exportMongoCollection("csv")');
- expect(block).toContain('exportMongoCollection("ndjson")');
- expect(block).not.toContain("openMongoExport");
- });
-
- it("opens import through AppDialogs like table import, without an export setup dialog", () => {
- const dialogs = read("../../layout/AppDialogs.vue");
- expect(dialogs).toContain("MongoImportDialog");
- expect(dialogs).not.toContain("MongoExportDialog");
- expect(dialogs).toContain("dialogs.showMongoImportDialog.value");
-
- const sources = read("../../../composables/useDialogSources.ts");
- expect(sources).toContain("connectionStore.mongoImportSource");
- expect(sources).not.toContain("connectionStore.mongoExportSource");
- });
-});
diff --git a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
index 89f713a863..57f66dee4e 100644
--- a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
+++ b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
@@ -135,15 +135,6 @@ describe("SshHostKeyPromptDialog web bridge", () => {
expect(dialogSource).not.toContain(':dismissible="false"');
});
- it("stacks above dialogs that mount later than it does", () => {
- // Dialog portals teleport into <body> when their component mounts, so paint
- // order at the shared z-50 follows mount order. This prompt mounts once at
- // app start, so an on-demand dialog (e.g. the connection editor) would bury
- // it and block the whole window. It must opt out of the default layer.
- expect(dialogSource).toContain('overlay-class="z-[200]"');
- expect(dialogSource).toContain('portal-class="z-[200]"');
- });
-
it("keeps the prompt above a later body-mounted connection dialog and answerable", async () => {
await mountDialog();
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlSearchSource.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlSearchSource.spec.ts
deleted file mode 100644
index 00432cb292..0000000000
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlSearchSource.spec.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../TableStructureEditor.vue", import.meta.url), "utf8");
-
-describe("TableStructureEditor DDL search wiring", () => {
- it("uses a CodeMirror editor and the shared search panel", () => {
- expect(source).toContain('import EditorSearchPanel from "@/components/editor/EditorSearchPanel.vue";');
- expect(source).toContain('key: "Mod-f"');
- expect(source).toMatch(/if \(activeTab\.value === "ddl"\) \{\s*ddlSearchPanelRef\.value\?\.openSearch\(\);\s*return true;/);
- expect(source).not.toContain("ddlPreRef");
- expect(source).not.toContain("onDdlKeydown");
- });
-
- it("routes the global search command to the active searchable structure tab", () => {
- expect(source).toMatch(/function focusSearch\(\): boolean \{[\s\S]*activeTab\.value === "columns"[\s\S]*focusColumnSearch\(\);[\s\S]*activeTab\.value === "indexes"[\s\S]*focusIndexSearch\(\);[\s\S]*activeTab\.value === "ddl"[\s\S]*ddlSearchPanelRef\.value\?\.openSearch\(\)/);
- expect(source).toContain("defineExpose({ applyChanges, focusSearch });");
- expect(source).toMatch(/if \(isPlainModShortcut\(event, "f"\)\) \{\s*if \(focusSearch\(\)\)/);
- });
-
- it("keeps the DDL editable only where an executable script makes sense", () => {
- // Editable for an existing table with loaded DDL; the create-table flow has
- // no DDL tab and an empty baseline only renders a placeholder string, which
- // must never become editable (and so never executable) text.
- expect(source).toContain("EditorState.readOnly.of(!ddlEditingEnabled.value)");
- expect(source).toMatch(/const ddlEditingEnabled = computed\(\(\) => !isCreateMode\.value && .*ddlContent\.value\.trim\(\)\)/);
- expect(source).not.toContain("EditorState.readOnly.of(true)");
- });
-
- it("records user edits into ddlDraft without echoing its own document writes", () => {
- expect(source).toContain("if (!update.docChanged || applyingDdlDocument || !ddlEditingEnabled.value) return;");
- expect(source).toContain("ddlDraft.value = update.state.doc.toString();");
- expect(source).toContain("applyingDdlDocument = true;");
- });
-
- it("initializes the editor from the container ref so a delayed tab mount still renders", () => {
- // Regression guard for the blank DDL tab: reka-ui's TabsContent mounts its
- // slot one tick after the tab becomes active, so a lone nextTick guess runs
- // while ddlEditorContainer is still undefined.
- expect(source).toMatch(/watch\(\s*ddlEditorContainer,/);
- expect(source).toContain('if (activeTab.value !== "ddl" || loading.value || ddlLoading.value) return;');
- });
-
- it("refreshes and disposes the DDL editor across its component lifecycle", () => {
- expect(source).toContain("if (force) destroyDdlEditor();");
- expect(source).toContain("observeDdlEditorScroll(editorView);");
- expect(source).toContain("ddlEditorView.value.scrollDOM.scrollTop");
- expect(source).toContain('if (activeTab.value !== "ddl") destroyDdlEditor();');
- expect(source).toContain("onDeactivated(() => {");
- expect(source).toContain("onBeforeUnmount(() => {");
- expect(source.match(/destroyDdlEditor\(\);/g)?.length).toBeGreaterThanOrEqual(4);
- });
-});
diff --git a/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts b/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts
deleted file mode 100644
index ed4ef4dd56..0000000000
--- a/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../DataTransferDialog.vue", import.meta.url), "utf8");
-
-describe("DataTransferDialog layout", () => {
- it("keeps only the main dialog resizable within safe viewport bounds", () => {
- const dialogContentTags = dialogSource.match(/<DialogContent\b[^>]*>/g) ?? [];
- const resizableDialogs = dialogContentTags.filter((tag) => tag.includes(" resize"));
-
- expect(resizableDialogs).toHaveLength(1);
- expect(resizableDialogs[0]).toContain('class="dbx-transfer-dialog sm:max-w-[1120px] max-h-[80vh] flex flex-col overflow-hidden resize"');
- expect(resizableDialogs[0]).toContain(':style="transferDialogStyle"');
- expect(dialogSource).toContain('width: "min(1120px, calc(100vw - 2rem))"');
- expect(dialogSource).toContain('height: "min(80vh, calc(var(--dbx-viewport-height) - 2rem))"');
- expect(dialogSource).toContain('minWidth: "min(780px, calc(100vw - 2rem))"');
- expect(dialogSource).toContain('minHeight: "min(480px, calc(var(--dbx-viewport-height) - 2rem))"');
- expect(dialogSource).toContain('maxWidth: "calc(100vw - 2rem)"');
- expect(dialogSource).toContain('maxHeight: "calc(var(--dbx-viewport-height) - 2rem)"');
- });
-
- it("keeps source and target side by side while the dialog changes size", () => {
- expect(dialogSource).toContain('class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start"');
- });
-
- it("keeps the header and footer outside the shrinking content region", () => {
- expect(dialogSource).toContain('<DialogHeader class="shrink-0">');
- expect(dialogSource).toContain('<DialogFooter class="shrink-0">');
- expect(dialogSource).toContain('class="min-h-0 flex-1 overflow-y-auto pl-4 pr-1 scrollbar-thin"');
- });
-
- it("allows layout scrolling on short viewports to prevent content clipping", () => {
- expect(dialogSource).toContain('class="flex flex-col gap-5 py-3"');
- expect(dialogSource).toContain('class="flex min-h-0 flex-col gap-2"');
- });
-
- it("keeps long table lists independently scrollable", () => {
- expect(dialogSource).toContain('class="min-h-0 flex-1"');
- });
-});
-
-describe("DataTransferDialog transfer prefill", () => {
- it("accepts source, target, schema, and selected-table prefills", () => {
- expect(dialogSource).toContain("prefillSchema?: string;");
- expect(dialogSource).toContain("prefillTables?: string[];");
- expect(dialogSource).toContain("prefillTargetConnectionId?: string;");
- expect(dialogSource).toContain("prefillTargetDatabase?: string;");
- expect(dialogSource).toContain("prefillTargetSchema?: string;");
- });
-
- it("keeps only copied tables selected after loading the source list", () => {
- expect(dialogSource).toContain("function applyPendingTableSelection()");
- expect(dialogSource).toContain("new Set(tables.filter((table) => pending.includes(table)))");
- });
-
- it("sends content and objects in the transfer request", () => {
- expect(dialogSource).toContain("buildTransferObjectSelections(selectedObjects.value, treeDisabledGroups.value)");
- expect(dialogSource).toContain('import { buildTransferObjectSelections } from "./transferSelections"');
- expect(dialogSource).toContain('createTable: transferContent.value !== "dataOnly"');
- expect(dialogSource).toContain('createTable: transferContent.value !== "dataOnly"');
- });
-
- it("loads non-table object groups per source database kind", () => {
- expect(dialogSource).toContain("transferObjectKindsForDatabase");
- expect(dialogSource).toContain("api.listObjects(connectionId, database, schema, [kind]");
- expect(dialogSource).toContain("groups[kind] = objects.map((o) => o.name)");
- });
-
- it("routes table-only database kinds through the table-list request", () => {
- expect(dialogSource).toContain("const kinds = transferObjectKindsForDatabase(transferDatabaseTypeForConnection(config))");
- expect(dialogSource).toContain("for (const kind of kinds)");
- expect(dialogSource).toContain('if (kind === "TABLE")');
- expect(dialogSource).toContain("await api.listTables(connectionId, database, schema");
- });
-
- it("keeps MongoDB collection loading ahead of the generic object-kind path", () => {
- const mongoCollectionBranch = dialogSource.indexOf("if (isMongoConnection(connectionId))");
- const genericObjectKinds = dialogSource.indexOf("const kinds = transferObjectKindsForDatabase(transferDatabaseTypeForConnection(config))");
-
- expect(mongoCollectionBranch).toBeGreaterThan(-1);
- expect(dialogSource).toContain("await api.mongoListCollections(connectionId, database)");
- expect(mongoCollectionBranch).toBeLessThan(genericObjectKinds);
- });
-
- it("admits connections via the transfer resolver so doris-family mysql connections stay selectable", () => {
- expect(dialogSource).toContain("supportsTransfer(transferDatabaseTypeForConnection(c))");
- expect(dialogSource).not.toContain("supportsTransfer(effectiveDatabaseTypeForConnection(c))");
- });
-
- it("disables non-table groups for data-only and cross-family transfers", () => {
- expect(dialogSource).toContain("treeDisabledGroups");
- expect(dialogSource).toContain('transferContent.value === "dataOnly"');
- expect(dialogSource).toContain("crossFamilyTransferableKinds");
- expect(dialogSource).toContain("objectDataOnlyDisabled");
- });
-
- it("allows a transfer between different schemas in the same database", () => {
- expect(dialogSource).toContain("isSameTransferDatabase");
- expect(dialogSource).toContain("const sameSourceAndTarget = sameCatalogAndDatabase && effectiveSourceSchema === effectiveTargetSchema");
- });
-
- it("keeps catalog filtering and completion refresh catalog-aware", () => {
- expect(dialogSource).toContain("fetchCatalogNamespaceOptions(connectionId, catalog, config)");
- expect(dialogSource).toContain("store.refreshObjectListTreeNode(request.targetConnectionId, request.targetDatabase, request.targetSchema, request.targetCatalog)");
- });
-
- it("keeps default tree-schema databases selectable without leaking sentinels", () => {
- expect(dialogSource).toContain("const sourceDatabaseName = computed(() => decodedDatabase(sourceConnectionId.value, sourceDatabase.value))");
- expect(dialogSource).toContain("const targetDatabaseName = computed(() => decodedDatabase(targetConnectionId.value, targetDatabase.value))");
- expect(dialogSource).toContain("sourceDatabase: sourceDatabaseName.value");
- expect(dialogSource).toContain("targetDatabase: targetDatabaseName.value");
- expect(dialogSource).toContain(':display-name="(option) => databaseOptionLabel(sourceConnectionId, option)"');
- expect(dialogSource).toContain(':display-name="(option) => databaseOptionLabel(targetConnectionId, option)"');
- });
-
- it("discards stale async results after the connection changes", () => {
- // 竞态防护:切换连接后旧请求的回调必须丢弃,不能覆盖新选择的下拉选项
- expect(dialogSource).toContain("if (isStale()) return;");
- expect(dialogSource).toContain("sourceConnectionId.value !== connectionId");
- expect(dialogSource).toContain("targetConnectionId.value !== connectionId");
- expect(dialogSource).toContain("if (sourceConnectionId.value !== id) return;");
- expect(dialogSource).toContain("if (targetConnectionId.value !== id) return;");
- });
-});
diff --git a/apps/desktop/src/components/ui/button/__tests__/buttonPressFeedback.spec.ts b/apps/desktop/src/components/ui/button/__tests__/buttonPressFeedback.spec.ts
deleted file mode 100644
index df3ab0740b..0000000000
--- a/apps/desktop/src/components/ui/button/__tests__/buttonPressFeedback.spec.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// Source-contract guard for shared button press feedback.
-
-// Overview: desktop click responsiveness depends on buttons giving immediate
-// visual feedback while pressed. DOM `click` only fires on pointer-up, so a
-// press with zero visual delta reads as "the click did nothing" and users
-// retry or hold the button (~1s holds measured in click-probe sessions).
-//
-// Two guarantees keep that regression from re-appearing:
-// 1. Every button variant styles an `active:` pressed state, so pressing
-// always changes something on screen before pointer-up.
-// 2. The pressed state must not move or scale the button (`scale-*` /
-// `translate-*`). A moving hit target can land pointer-up outside the
-// element it was pressed on, which genuinely drops the click.
-// Keep these assertions updated alongside the variant class strings.
-
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const buttonVariantsSource = readFileSync(new URL("../index.ts", import.meta.url), "utf8");
-
-const VARIANTS = ["default", "outline", "secondary", "ghost", "destructive", "link"] as const;
-
-function variantClasses(variant: string): string {
- const match = buttonVariantsSource.match(new RegExp(`${variant}:\\s*"([^"]+)"`));
- expect(match, `variant "${variant}" exists in buttonVariants`).toBeTruthy();
- return match![1];
-}
-
-describe("button press feedback guard", () => {
- it.each(VARIANTS)("styles an active pressed state for the %s variant", (variant) => {
- expect(variantClasses(variant)).toMatch(/(^|\s)active:/);
- });
-
- it.each(VARIANTS)("does not move the hit target while %s is pressed", (variant) => {
- expect(variantClasses(variant)).not.toMatch(/active:(scale|translate|-translate)-/);
- });
-
- it("does not move the hit target from the shared base classes", () => {
- const base = buttonVariantsSource.match(/cva\(\s*"([^"]+)"/);
- expect(base).toBeTruthy();
- expect(base![1]).not.toMatch(/active:(scale|translate|-translate)-/);
- });
-});
diff --git a/apps/desktop/src/components/ui/dialog/__tests__/dialogSurfaceOpacity.spec.ts b/apps/desktop/src/components/ui/dialog/__tests__/dialogSurfaceOpacity.spec.ts
deleted file mode 100644
index 599d5df868..0000000000
--- a/apps/desktop/src/components/ui/dialog/__tests__/dialogSurfaceOpacity.spec.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const DIALOG_SHELLS = ["DialogContent.vue", "DialogScrollContent.vue"] as const;
-
-function dialogShellSource(file: string): string {
- return readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
-}
-
-describe("dialog shell surfaces", () => {
- // While a wallpaper is active --background (and the other root surfaces) are
- // tinted with alpha, so a dialog painted with bg-background lets the image
- // bleed through its body. Card/popover surfaces stay opaque on purpose.
- it.each(DIALOG_SHELLS)("%s paints its surface with an opaque token", (file) => {
- const source = dialogShellSource(file);
-
- expect(source).toContain('data-slot="dialog-content"');
- expect(source).toMatch(/\bbg-(popover|card)\b/);
- expect(source).not.toMatch(/\bbg-background\b/);
- });
-});
diff --git a/apps/desktop/src/composables/__tests__/useCellDetailEditor.folding.spec.ts b/apps/desktop/src/composables/__tests__/useCellDetailEditor.folding.spec.ts
index ca77e039c5..2355ec1e5e 100644
--- a/apps/desktop/src/composables/__tests__/useCellDetailEditor.folding.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useCellDetailEditor.folding.spec.ts
@@ -1,20 +1,9 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { json } from "@codemirror/lang-json";
import { foldable } from "@codemirror/language";
-const redisJsonEditorSource = readFileSync(new URL("../../components/redis/RedisJsonEditor.vue", import.meta.url), "utf8");
-const cellDetailEditorSource = readFileSync(new URL("../useCellDetailEditor.ts", import.meta.url), "utf8");
-
describe("Redis JSON editor folding", () => {
- it("opts the Redis JSON editor into the shared folding controls", () => {
- expect(redisJsonEditorSource).toMatch(/language:\s*"json"[\s\S]*folding:\s*true/);
- expect(redisJsonEditorSource).toMatch(/lineNumbers:\s*props\.lineNumbers/);
- expect(cellDetailEditorSource).toContain("...(options.folding ? [foldGutter()] : []),");
- expect(cellDetailEditorSource).toContain("...(options.folding ? foldKeymap : []),");
- });
-
it("provides foldable ranges for JSON objects and arrays", () => {
const state = EditorState.create({
doc: `{
diff --git a/apps/desktop/src/composables/__tests__/useSaveSqlFolderSelection.spec.ts b/apps/desktop/src/composables/__tests__/useSaveSqlFolderSelection.spec.ts
index 1807065cc6..b2e6e4f62d 100644
--- a/apps/desktop/src/composables/__tests__/useSaveSqlFolderSelection.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSaveSqlFolderSelection.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { useSaveSqlFolderSelection } from "@/composables/useSaveSqlFolderSelection";
@@ -12,8 +11,6 @@ function deferred<T>() {
return { promise, resolve, reject };
}
-const appSource = readFileSync(new URL("../../App.vue", import.meta.url), "utf8");
-
describe("save SQL folder selection", () => {
it("keeps save and reselection blocked until folder creation completes", async () => {
const creation = deferred<string>();
@@ -24,9 +21,6 @@ describe("save SQL folder selection", () => {
expect(folder.pending.value).toBe(true);
expect(folder.selection.value).toBe("existing-folder");
- expect(appSource).toContain("if (saveSqlFolderCreationPending.value) return;");
- expect(appSource).toContain(':disabled="saveSqlFolderCreationPending"');
- expect(appSource).toContain(':disabled="saveSqlFolderCreationPending || !saveSqlName.trim()"');
creation.resolve("created-folder");
await pendingSelection;
diff --git a/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts b/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
index 40904a80da..b595031a10 100644
--- a/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSidebarTreeExportRuntime.spec.ts
@@ -1,9 +1,7 @@
-import { readFileSync } from "node:fs";
import { shallowRef, reactive, nextTick, effectScope } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ColumnInfo, TreeNode } from "@/types/database";
-const source = readFileSync(new URL("../useSidebarTreeExportRuntime.ts", import.meta.url), "utf8");
const toastMock = vi.hoisted(() => vi.fn());
const copyToClipboardMock = vi.hoisted(() => vi.fn());
const addExportTaskMock = vi.hoisted(() => vi.fn());
@@ -40,19 +38,6 @@ import { useSidebarTreeExportRuntime } from "@/composables/useSidebarTreeExportR
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS } from "@/lib/dataGrid/dataGridCopyExtractor";
import { isLoadingStructurePreview, showStructurePreviewDialog, structurePreviewDefaultFileName, structurePreviewError, structurePreviewSql, structurePreviewTitle } from "@/components/sidebar/sidebarTreeDialogState";
-function functionBody(name: string): string {
- const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`, "m").exec(source);
- if (!signature) throw new Error(`Missing function ${name}`);
- const bodyStart = signature.index + signature[0].length;
- let depth = 1;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- else if (source[index] === "}") depth -= 1;
- if (depth === 0) return source.slice(bodyStart, index);
- }
- throw new Error(`Unclosed function ${name}`);
-}
-
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
@@ -355,29 +340,6 @@ describe("useSidebarTreeExportRuntime", () => {
expect(showStructurePreviewDialog.value).toBe(true);
});
- it("prompts for export options before it opens the save dialog", () => {
- const exportDataXlsx = functionBody("exportDataXlsx");
-
- expect(source).toContain('import XlsxHeaderDialog from "@/components/export/XlsxHeaderDialog.vue"');
- expect(exportDataXlsx).toContain("await api.getColumns(");
- expect(exportDataXlsx).toContain("hasXlsxHeaderComments(columnInfos.map((column) => column.comment))");
- expect(exportDataXlsx.indexOf("await showSidebarTreeXlsxHeaderDialog(")).toBeLessThan(exportDataXlsx.indexOf('await exportTableData(target, "xlsx"'));
- });
-
- it("falls back to field-name headers when column metadata is unavailable", () => {
- const exportDataXlsx = functionBody("exportDataXlsx");
-
- expect(exportDataXlsx).toContain("// Export still works with field-name headers when column metadata is unavailable.");
- expect(exportDataXlsx).toContain('await exportTableData(target, "xlsx"');
- });
-
- it("sends the selected mode's header overrides to both XLSX export paths", () => {
- const exportTableData = functionBody("exportTableData");
-
- expect(exportTableData).toContain("buildXlsxHeaderOverrides(result.columns, comments, headerMode)");
- expect(exportTableData).toContain("columnComments,");
- });
-
it("keeps the original table and export options when selection changes during XLSX preparation", async () => {
const metadata = deferred<ColumnInfo[]>();
apiMock.getColumns.mockReturnValueOnce(metadata.promise);
diff --git a/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.ts b/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.ts
deleted file mode 100644
index a2272d44c7..0000000000
--- a/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import itLocale from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-type Messages = Record<string, unknown>;
-
-const locales: Array<[string, Messages]> = [
- ["az", az],
- ["es", es],
- ["it", itLocale],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function offlineExportEntries(locale: Messages): Map<string, string> {
- const driverStore = locale.driverStore as Record<string, unknown>;
- return new Map(
- Object.entries(driverStore)
- .filter(([key, value]) => key.startsWith("offlineExport") && typeof value === "string")
- .map(([key, value]) => [key, value as string]),
- );
-}
-
-function placeholders(message: string): string[] {
- return [...new Set([...message.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]))].sort();
-}
-
-describe("offline Agent export i18n parity", () => {
- const englishEntries = offlineExportEntries(en);
-
- it("declares the complete English message set", () => {
- expect(englishEntries.size).toBe(29);
- });
-
- it.each(locales)("%s declares matching keys and placeholders", (_name, locale) => {
- const localeEntries = offlineExportEntries(locale);
- expect([...localeEntries.keys()].sort()).toEqual([...englishEntries.keys()].sort());
-
- for (const [key, englishMessage] of englishEntries) {
- expect(placeholders(localeEntries.get(key) ?? ""), key).toEqual(placeholders(englishMessage));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/agentOfflineImportParity.spec.ts b/apps/desktop/src/i18n/__tests__/agentOfflineImportParity.spec.ts
deleted file mode 100644
index 52f30e669f..0000000000
--- a/apps/desktop/src/i18n/__tests__/agentOfflineImportParity.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import itLocale from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-type Messages = Record<string, unknown>;
-
-const locales: Array<[string, Messages]> = [
- ["az", az],
- ["es", es],
- ["it", itLocale],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function offlineImportEntries(locale: Messages): Map<string, string> {
- const driverStore = locale.driverStore as Record<string, unknown>;
- return new Map(
- Object.entries(driverStore)
- .filter(([key, value]) => (key.startsWith("offlineImport") || key.startsWith("offlineJreImport")) && typeof value === "string")
- .map(([key, value]) => [key, value as string]),
- );
-}
-
-function placeholders(message: string): string[] {
- return [...new Set([...message.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]))].sort();
-}
-
-describe("offline Agent import i18n parity", () => {
- const englishEntries = offlineImportEntries(en);
-
- it("declares the complete English message set", () => {
- expect([...englishEntries.keys()].sort()).toEqual(["offlineImportFailed", "offlineImportPartial", "offlineImportSuccess", "offlineImportWithJreSuccess", "offlineJreImportSuccess"]);
- });
-
- it.each(locales)("%s declares matching keys and placeholders", (_name, locale) => {
- const localeEntries = offlineImportEntries(locale);
- expect([...localeEntries.keys()].sort()).toEqual([...englishEntries.keys()].sort());
-
- for (const [key, englishMessage] of englishEntries) {
- expect(placeholders(localeEntries.get(key) ?? ""), key).toEqual(placeholders(englishMessage));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/aiAutoRoutingParity.spec.ts b/apps/desktop/src/i18n/__tests__/aiAutoRoutingParity.spec.ts
deleted file mode 100644
index 34acac26ff..0000000000
--- a/apps/desktop/src/i18n/__tests__/aiAutoRoutingParity.spec.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-// Keys the "Auto" picker entry (#9118) adds to the `ai` namespace: the menu
-// entry, the slow-path status line, and the per-message routing chip. The picker
-// and the chip render in whatever locale the user runs, so a missing key would
-// leak a raw key into the toolbar.
-const AI_AUTO_ROUTING_ACTIONS_KEYS = ["auto"] as const;
-const AI_AUTO_ROUTING_KEYS = ["recognizing", "chip", "switchTo"] as const;
-// Settings > AI toggle: new conversations start on the `auto` entry.
-const AI_AUTO_ROUTING_SETTINGS_KEYS = ["defaultAutoRouting", "defaultAutoRoutingDescription"] as const;
-
-describe("AI auto-routing locale parity", () => {
- it.each(locales)("%s exposes ai.actions.auto with non-empty copy", (_name, locale) => {
- const ai = (locale as { ai: { actions: Record<string, unknown> } }).ai;
- for (const key of AI_AUTO_ROUTING_ACTIONS_KEYS) {
- expect(ai.actions[key], `${_name}: ai.actions.${key}`).toBeTypeOf("string");
- expect(ai.actions[key] as string, `${_name}: ai.actions.${key}`).not.toHaveLength(0);
- }
- });
-
- it.each(locales)("%s exposes the full ai.routing.* key set with non-empty copy", (_name, locale) => {
- const routing = (locale as { ai: { routing: Record<string, unknown> } }).ai.routing;
- for (const key of AI_AUTO_ROUTING_KEYS) {
- expect(routing?.[key], `${_name}: ai.routing.${key}`).toBeTypeOf("string");
- expect(routing?.[key] as string, `${_name}: ai.routing.${key}`).not.toHaveLength(0);
- }
- // The chip interpolates the resolved action label.
- expect(routing.chip as string, `${_name}: ai.routing.chip`).toContain("{action}");
- expect(routing.switchTo as string, `${_name}: ai.routing.switchTo`).toContain("{action}");
- });
-
- it.each(locales)("%s exposes the default auto-routing setting keys with non-empty copy", (_name, locale) => {
- const ai = (locale as { ai: Record<string, unknown> }).ai;
- for (const key of AI_AUTO_ROUTING_SETTINGS_KEYS) {
- expect(ai[key], `${_name}: ai.${key}`).toBeTypeOf("string");
- expect(ai[key] as string, `${_name}: ai.${key}`).not.toHaveLength(0);
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/aiPluginConversationParity.spec.ts b/apps/desktop/src/i18n/__tests__/aiPluginConversationParity.spec.ts
deleted file mode 100644
index a133d00420..0000000000
--- a/apps/desktop/src/i18n/__tests__/aiPluginConversationParity.spec.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-// Keys the plugin AI conversation adds to the `ai` namespace. The panel renders
-// in whatever locale the user runs, so a missing key would leak a raw key into
-// the composer placeholder or the welcome copy.
-const AI_PLUGIN_CONVERSATION_KEYS = ["pluginHttpModelOnly", "pluginWelcome", "pluginFollowUp"] as const;
-
-describe("plugin AI conversation locale parity", () => {
- it.each(locales)("%s exposes the plugin conversation copy", (_name, locale) => {
- const ai = (locale as { ai: Record<string, unknown> }).ai;
- for (const key of AI_PLUGIN_CONVERSATION_KEYS) {
- expect(ai[key], `${_name}: ai.${key}`).toBeTypeOf("string");
- expect(ai[key] as string, `${_name}: ai.${key}`).not.toHaveLength(0);
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/aiRichContentParity.spec.ts b/apps/desktop/src/i18n/__tests__/aiRichContentParity.spec.ts
deleted file mode 100644
index 8ddb13434d..0000000000
--- a/apps/desktop/src/i18n/__tests__/aiRichContentParity.spec.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-// Keys the safe-HTML preview (PR2 of #6467) adds to the `ai` namespace. Every
-// locale must expose all of them — the preview UI renders in whatever locale
-// the user runs, and a missing key would leak raw keys into the toolbar.
-const AI_HTML_PREVIEW_KEYS = ["htmlPreviewLabel", "htmlExpandPreview", "htmlExpandPreviewHint", "htmlSaveSafe", "htmlSaveFailed", "htmlCopySource", "htmlCopyRiskBody", "htmlCopyRiskAccept", "htmlCopyRiskRemember", "htmlCopyRiskToast"] as const;
-
-// Keys the conversation export (PR3 of #6467) adds to the `ai` namespace —
-// header menu entry, report role labels, failure marker, and empty-state copy.
-const AI_CONVERSATION_EXPORT_KEYS = ["exportConversation", "conversationExportMarkdown", "conversationExportHtml", "conversationRoleUser", "conversationRoleAssistant", "conversationFailedMarker", "conversationExportEmpty"] as const;
-
-// Keys conversation rename and the database picker add to the `ai` namespace —
-// the picker renders in every locale and a missing key leaks raw keys into it.
-const AI_CONVERSATION_MANAGEMENT_KEYS = ["renameConversation", "conversationRenameFailed", "clearDatabaseSelection", "searchDatabases", "noDatabasesFound"] as const;
-
-describe("AI rich content locale parity", () => {
- it.each(locales)("%s exposes the full ai.html* key set with non-empty copy", (_name, locale) => {
- const ai = (locale as { ai: Record<string, unknown> }).ai;
- for (const key of AI_HTML_PREVIEW_KEYS) {
- expect(ai[key], `${_name}: ai.${key}`).toBeTypeOf("string");
- expect(ai[key] as string, `${_name}: ai.${key}`).not.toHaveLength(0);
- }
- });
-
- it.each(locales)("%s exposes the full conversation-export key set with non-empty copy", (_name, locale) => {
- const ai = (locale as { ai: Record<string, unknown> }).ai;
- for (const key of AI_CONVERSATION_EXPORT_KEYS) {
- expect(ai[key], `${_name}: ai.${key}`).toBeTypeOf("string");
- expect(ai[key] as string, `${_name}: ai.${key}`).not.toHaveLength(0);
- }
- });
-
- it.each(locales)("%s exposes the full conversation-management key set with non-empty copy", (_name, locale) => {
- const ai = (locale as { ai: Record<string, unknown> }).ai;
- for (const key of AI_CONVERSATION_MANAGEMENT_KEYS) {
- expect(ai[key], `${_name}: ai.${key}`).toBeTypeOf("string");
- expect(ai[key] as string, `${_name}: ai.${key}`).not.toHaveLength(0);
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/cachedResultMessages.spec.ts b/apps/desktop/src/i18n/__tests__/cachedResultMessages.spec.ts
deleted file mode 100644
index 9ccf341ecf..0000000000
--- a/apps/desktop/src/i18n/__tests__/cachedResultMessages.spec.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it as test } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import it from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-const contentAreaSource = readFileSync(new URL("../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-
-function cachedResultMessages(messages: Record<string, unknown>): Record<string, unknown> {
- return messages.grid as Record<string, unknown>;
-}
-
-describe("cached result messages", () => {
- test.each([
- ["Azerbaijani", az],
- ["English", en],
- ["Spanish", es],
- ["Italian", it],
- ["Japanese", ja],
- ["Korean", ko],
- ["Brazilian Portuguese", ptBR],
- ["Turkish", tr],
- ["Simplified Chinese", zhCN],
- ["Traditional Chinese", zhTW],
- ])("provides the missing-result actions in %s", (_locale, messages) => {
- const grid = cachedResultMessages(messages);
-
- expect(grid.cachedResultUnavailable).toEqual(expect.any(String));
- expect(grid.reexecuteQuery).toEqual(expect.any(String));
- });
-
- test("uses the grid namespace from the cached-result fallback UI", () => {
- expect(contentAreaSource).toContain('t("grid.cachedResultUnavailable")');
- expect(contentAreaSource).toContain('t("grid.reexecuteQuery")');
- expect(contentAreaSource).not.toContain('t("editor.cachedResultUnavailable")');
- expect(contentAreaSource).not.toContain('t("editor.reexecuteQuery")');
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/commonRefreshKey.spec.ts b/apps/desktop/src/i18n/__tests__/commonRefreshKey.spec.ts
deleted file mode 100644
index a5062d28ae..0000000000
--- a/apps/desktop/src/i18n/__tests__/commonRefreshKey.spec.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-// Shared actions such as KafkaMessagesPanel and DoltVersionControl render
-// `t("common.refresh")`. When the key is missing everywhere, vue-i18n echoes
-// the key path itself (issue #8768). KafkaMessagesPanel.spec.ts mocks i18n as
-// `t: (key) => key`, so that spec cannot catch a missing-from-everywhere key.
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az as Record<string, unknown>],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function commonRefresh(locale: Record<string, unknown>): unknown {
- const common = locale["common"];
- if (!common || typeof common !== "object") return undefined;
- return (common as Record<string, unknown>)["refresh"];
-}
-
-describe("common.refresh i18n key", () => {
- it("en resolves common.refresh to text", () => {
- const value = commonRefresh(en as Record<string, unknown>);
- expect(value, "common.refresh missing from locales/en.ts").toBeTypeOf("string");
- expect(value).not.toBe("");
- expect(value).not.toBe("common.refresh");
- });
-
- it.each(locales)("%s resolves common.refresh to text", (_name, locale) => {
- const value = commonRefresh(locale);
- expect(value, `${_name} common.refresh`).toBeTypeOf("string");
- expect(value).not.toBe("");
- expect(value).not.toBe("common.refresh");
- });
-
- it("zh-CN uses a Chinese refresh label", () => {
- expect(commonRefresh(zhCN)).toBe("刷新");
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts b/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts
deleted file mode 100644
index 8756550035..0000000000
--- a/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { readFileSync } from "node:fs";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function leafKeys(value: unknown, prefix = ""): string[] {
- if (value === null || typeof value !== "object" || Array.isArray(value)) return [prefix];
- return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) => leafKeys(child, prefix ? `${prefix}.${key}` : key));
-}
-
-describe("Consul advanced UI locale parity", () => {
- const expected = leafKeys((en as { consul: { ui: unknown } }).consul.ui).sort();
- const expectedTools = leafKeys((en as { consul: { tools: unknown } }).consul.tools).sort();
-
- it.each(locales)("%s exposes the full consul.ui key set", (_name, locale) => {
- const ui = (locale as { consul: { ui: unknown } }).consul.ui;
- expect(leafKeys(ui).sort()).toEqual(expected);
- });
-
- it.each(locales)("%s exposes the full consul.tools key set", (_name, locale) => {
- const tools = (locale as { consul: { tools: unknown } }).consul.tools;
- expect(leafKeys(tools).sort()).toEqual(expectedTools);
- });
-
- it("uses Chinese labels for the Consul KV workflow", () => {
- const consul = (zhCN as { consul: { tools: Record<string, unknown>; keyLabel: string; valueContent: string; format: string } }).consul;
- const tools = consul.tools;
- expect(tools.search).toBe("全文搜索");
- expect(tools.exportPrefix).toBe("导出");
- expect(tools.import).toBe("导入");
- expect(tools.migrate).toBe("同步");
- expect(tools.deletePrefix).toBe("前缀删除");
- expect(consul.keyLabel).toBe("键(Key)");
- expect(consul.valueContent).toBe("值");
- expect(consul.format).toBe("格式");
- });
-
- it("localizes Consul service, Session, and capability labels", () => {
- const ui = (zhCN as { consul: { ui: Record<string, unknown> } }).consul.ui;
- expect(ui.serviceKind).toBe("服务类型(ServiceKind)");
- expect(ui.serviceWeights).toBe("通过 / 警告权重");
- expect(ui.behaviorRelease).toBe("释放锁(release)");
- expect(ui.behaviorDelete).toBe("删除 Key(delete)");
- expect(ui.capabilityDisabled).toBe("未启用");
- });
-
- it.each(["ConsulOverview", "ConsulServices", "ConsulHealth", "ConsulSessions", "ConsulAcl", "ConsulScope", "ConsulMesh", "ConsulTools", "ConsulOperator", "ConsulWorkspace"])("%s uses the i18n composable", (component) => {
- const source = readFileSync(new URL(`../../components/consul/${component}.vue`, import.meta.url), "utf8");
- expect(source).toContain('import { useI18n } from "vue-i18n"');
- expect(source).toContain("useI18n()");
- });
-
- it("keeps Consul user-facing labels out of component templates", () => {
- const components = ["ConsulServices", "ConsulHealth", "ConsulSessions", "ConsulMesh", "ConsulKeyBrowser", "ConsulOperator"];
- const forbidden = [
- "Catalog nodes",
- "No visible services",
- "No visible nodes",
- "Agent target:",
- "Watch paused",
- "Watching index",
- "Pause watch",
- "Start watch",
- "HTTP Agent registrations belong",
- "Catalog instances",
- "Node services",
- "Local Agent services",
- "Enable maintenance",
- "Disable maintenance",
- "No matching health checks",
- "Service instances",
- "Local Agent checks",
- 'placeholder="Watch prefix"',
- ">Key</Badge>",
- ">Value</Badge>",
- 'placeholder="UPDATE AUTOPILOT"',
- 'placeholder="CHANGE KEYRING"',
- 'placeholder="UPDATE LICENSE"',
- ">ServiceKind<",
- ">Passing / Warning<",
- ">Node ID<",
- ">TaggedAddresses<",
- ">EnableTagOverride<",
- ">Behavior<",
- ">CreateIndex<",
- ">ModifyIndex<",
- "Session {{ row.session }}",
- ];
-
- for (const component of components) {
- const source = readFileSync(new URL(`../../components/consul/${component}.vue`, import.meta.url), "utf8");
- const template = source.slice(source.indexOf("<template>"));
- for (const literal of forbidden) expect(template, `${component} contains ${literal}`).not.toContain(literal);
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/customTypeMessages.spec.ts b/apps/desktop/src/i18n/__tests__/customTypeMessages.spec.ts
deleted file mode 100644
index fe9d1ae8d5..0000000000
--- a/apps/desktop/src/i18n/__tests__/customTypeMessages.spec.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-type Messages = {
- customType: typeof en.customType;
- contextMenu: typeof en.contextMenu;
-};
-
-const locales = { az, es, it: itLocale, ja, ko, "pt-BR": ptBR, tr, "zh-CN": zhCN, "zh-TW": zhTW } as unknown as Record<string, Messages>;
-
-describe("custom type translations", () => {
- it("provides localized labels in every supported non-English locale", () => {
- for (const [localeName, messages] of Object.entries(locales)) {
- expect(messages.customType.kinds.composite, localeName).not.toBe(en.customType.kinds.composite);
- expect(messages.customType.tabs.properties, localeName).not.toBe(en.customType.tabs.properties);
- expect(messages.customType.members.empty, localeName).not.toBe(en.customType.members.empty);
- expect(messages.customType.properties.empty, localeName).not.toBe(en.customType.properties.empty);
- expect(messages.customType.ddl.empty, localeName).not.toBe(en.customType.ddl.empty);
- expect(messages.customType.ddl.incomplete, localeName).not.toBe(en.customType.ddl.incomplete);
- expect(messages.contextMenu.viewDetails, localeName).not.toBe(en.contextMenu.viewDetails);
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/damengViewMessages.spec.ts b/apps/desktop/src/i18n/__tests__/damengViewMessages.spec.ts
deleted file mode 100644
index 42cbcd30d2..0000000000
--- a/apps/desktop/src/i18n/__tests__/damengViewMessages.spec.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { describe, expect, it } from "vitest";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-type ViewMessages = {
- contextMenu: { compileObjectFailedTitle: string; compileObjectFailedMessage: string };
- objects: { validStatus: string; invalidStatus: string };
-};
-
-const locales = { en, es, it: itLocale, ja, ko, "pt-BR": ptBR, "zh-CN": zhCN, "zh-TW": zhTW } as unknown as Record<string, ViewMessages>;
-
-describe.each(Object.entries(locales))("Dameng view messages: %s", (localeName, messages) => {
- it("provides a localized compilation failure with both placeholders", () => {
- expect(messages.contextMenu.compileObjectFailedTitle).toBeTypeOf("string");
- expect(messages.contextMenu.compileObjectFailedMessage).toContain("{name}");
- expect(messages.contextMenu.compileObjectFailedMessage).toContain("{message}");
- expect(messages.contextMenu.compileObjectFailedMessage).toContain("\n");
- if (localeName !== "en") expect(messages.contextMenu.compileObjectFailedTitle).not.toBe(en.contextMenu.compileObjectFailedTitle);
- });
-
- it("preserves the database validity labels", () => {
- expect(messages.objects.validStatus).toBe("VALID");
- expect(messages.objects.invalidStatus).toBe("INVALID");
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/executeShortcutHint.spec.ts b/apps/desktop/src/i18n/__tests__/executeShortcutHint.spec.ts
index 3a8399c370..5f5b8eb96b 100644
--- a/apps/desktop/src/i18n/__tests__/executeShortcutHint.spec.ts
+++ b/apps/desktop/src/i18n/__tests__/executeShortcutHint.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import i18n, { setLocale } from "@/i18n";
import { formatShortcutDisplay } from "@/lib/editor/shortcutDisplay";
@@ -8,9 +7,6 @@ import { formatShortcutDisplay } from "@/lib/editor/shortcutDisplay";
// Editor Settings "Execute Mode" label hardcode "(Cmd+Enter)" in every locale, including
// English, so the hints can disagree with both the current platform and a customized binding.
-const toolbarSource = readFileSync(new URL("../../components/layout/EditorToolbar.vue", import.meta.url), "utf8");
-const settingsDialogSource = readFileSync(new URL("../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
describe("execute-shortcut hints reflect the configured binding", () => {
it.each([
["MacIntel", "Mod+Enter", "⌘ ↵"],
@@ -35,18 +31,4 @@ describe("execute-shortcut hints reflect the configured binding", () => {
expect(i18n.global.t("settings.executeModeDescription", { shortcut })).toBe("执行 SQL 快捷键:Ctrl + Shift + ↵。用于控制默认执行全部 SQL 或光标所在语句。");
await setLocale("en");
});
-
- it("EditorToolbar.vue uses the saved executeSql shortcut", () => {
- expect(toolbarSource).toContain("formatShortcutDisplay(settingsStore.editorSettings.shortcuts.executeSql)");
- expect(toolbarSource).toMatch(/t\(\s*"toolbar\.executeShortcut"\s*,\s*\{\s*shortcut:\s*executeShortcutDisplay\.value/);
- });
-
- it("EditorSettingsDialog.vue uses the currently edited executeSql shortcut", () => {
- expect(settingsDialogSource).toMatch(/function translateWithExecuteShortcut\([^)]*\)[^}]*formatShortcutDisplay\(editShortcuts\.value\.executeSql\)/);
- expect(settingsDialogSource).toContain('translateWithExecuteShortcut("settings.executeModeDescription")');
- });
-
- it("EditorSettingsDialog.vue uses the same edited shortcut in settings search", () => {
- expect(settingsDialogSource).toMatch(/resolveSettingsSearchEntries\(\s*\[[^\]]*\]\s*,\s*\{[^}]*\}\s*,\s*translateWithExecuteShortcut\s*,/s);
- });
});
diff --git a/apps/desktop/src/i18n/__tests__/executionNamespaceParity.spec.ts b/apps/desktop/src/i18n/__tests__/executionNamespaceParity.spec.ts
deleted file mode 100644
index ee4e62db46..0000000000
--- a/apps/desktop/src/i18n/__tests__/executionNamespaceParity.spec.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-type Messages = Record<string, unknown>;
-
-const locales: Array<[string, Messages]> = [
- ["az", az],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-const namespaces = ["multiDbExecute", "exportProgress"] as const;
-
-function leafEntries(value: unknown, prefix = ""): Array<[string, string]> {
- if (typeof value === "string") return [[prefix, value]];
- if (value === null || typeof value !== "object" || Array.isArray(value)) return [];
- return Object.entries(value as Messages).flatMap(([key, child]) => leafEntries(child, prefix ? `${prefix}.${key}` : key));
-}
-
-function placeholders(message: string): string[] {
- return [...new Set([...message.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]))].sort();
-}
-
-describe.each(namespaces)("%s i18n namespace parity", (namespace) => {
- const englishEntries = new Map(leafEntries((en as Messages)[namespace]));
-
- it("english declares the namespace", () => {
- expect(englishEntries.size).toBeGreaterThan(0);
- });
-
- it.each(locales)("%s declares the same keys and placeholders", (_name, locale) => {
- const localeEntries = new Map(leafEntries(locale[namespace]));
- expect([...localeEntries.keys()].sort()).toEqual([...englishEntries.keys()].sort());
-
- for (const [key, englishMessage] of englishEntries) {
- expect(placeholders(localeEntries.get(key) ?? ""), `${namespace}.${key}`).toEqual(placeholders(englishMessage));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
new file mode 100644
index 0000000000..a7122b3fbf
--- /dev/null
+++ b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it, vi } from "vitest";
+import { createI18n } from "vue-i18n";
+import az from "../locales/az";
+import en from "../locales/en";
+import es from "../locales/es";
+import itLocale from "../locales/it";
+import ja from "../locales/ja";
+import ko from "../locales/ko";
+import ptBR from "../locales/pt-BR";
+import tr from "../locales/tr";
+import zhCN from "../locales/zh-CN";
+import zhTW from "../locales/zh-TW";
+
+// Non-English locales export `withEnglishFallback({ ... })`, which deep-merges
+// English underneath at import time, so an imported locale always "has" every
+// English key and a dropped translation is invisible. Swap the merge for the
+// identity to read what each locale file itself declares; the runtime check
+// below re-applies the real merge.
+vi.mock("../locales/fallback", () => ({ withEnglishFallback: (messages: Record<string, unknown>) => messages }));
+
+type Messages = Record<string, unknown>;
+type Locale = "az" | "en" | "es" | "it" | "ja" | "ko" | "pt-BR" | "tr" | "zh-CN" | "zh-TW";
+
+const declared: Record<Locale, Messages> = { az, en, es, it: itLocale, ja, ko, "pt-BR": ptBR, tr, "zh-CN": zhCN, "zh-TW": zhTW };
+const ALL_LOCALES = Object.keys(declared) as Locale[];
+const EXCEPT_AZ_TR = ALL_LOCALES.filter((locale) => locale !== "az" && locale !== "tr");
+
+interface FeatureMessages {
+ feature: string;
+ /** `a.b.key`, `a.b.*` (whole namespace, no extra keys) or `a.b.prefix*`, resolved against English. */
+ keys: string[];
+ /** Locales whose own file must declare every key; the others may fall back to English. */
+ locales?: Locale[];
+ /** The declared text must also differ from English. */
+ translated?: boolean;
+}
+
+const under = (namespace: string, keys: string[]) => keys.map((key) => `${namespace}.${key}`);
+
+// Message sets that render in every UI language: a key missing from `en`
+// leaks the raw key path, and a key missing from a locale silently shows
+// English.
+const FEATURE_MESSAGES: FeatureMessages[] = [
+ { feature: "AI HTML preview (#6467)", keys: under("ai", ["htmlPreviewLabel", "htmlExpandPreview", "htmlExpandPreviewHint", "htmlSaveSafe", "htmlSaveFailed", "htmlCopySource", "htmlCopyRiskBody", "htmlCopyRiskAccept", "htmlCopyRiskRemember", "htmlCopyRiskToast"]) },
+ { feature: "AI conversation export (#6467)", keys: under("ai", ["exportConversation", "conversationExportMarkdown", "conversationExportHtml", "conversationRoleUser", "conversationRoleAssistant", "conversationFailedMarker", "conversationExportEmpty"]) },
+ { feature: "AI conversation management", keys: under("ai", ["renameConversation", "conversationRenameFailed", "clearDatabaseSelection", "searchDatabases", "noDatabasesFound"]) },
+ { feature: "AI auto routing (#9118)", keys: ["ai.actions.auto", "ai.routing.recognizing", "ai.routing.chip", "ai.routing.switchTo", "ai.defaultAutoRouting", "ai.defaultAutoRoutingDescription"] },
+ { feature: "plugin AI conversation", keys: ["ai.pluginHttpModelOnly", "ai.pluginWelcome", "ai.pluginFollowUp"] },
+ { feature: "quick open", keys: ["quickOpen.*", "settings.shortcutGlobalSearch"] },
+ {
+ feature: "editor tab context menu",
+ keys: under("contextMenu", ["changeOrientation", "closeAllTabs", "closeLeftTabs", "closeOtherTabs", "closeRightTabs", "closeTab", "closeTabGroup", "compactTabTitle", "copyName", "editTabGroup", "fullTabTitle", "pinTab", "resetTabGroup", "splitDown", "splitRight", "unpinTab", "unsplit"]),
+ },
+ { feature: "offline Agent export", keys: ["driverStore.offlineExport*"] },
+ { feature: "offline Agent import", keys: ["driverStore.offlineImport*", "driverStore.offlineJreImport*"] },
+ { feature: "multi-database execution and export progress", keys: ["multiDbExecute.*", "exportProgress.*"], locales: ["en", "zh-CN"] },
+ { feature: "process list batch terminate", keys: under("processList", ["batchTerminate", "batchTerminateTitle", "batchTerminateConfirm", "batchTerminateRunning", "batchTerminateSummary"]) },
+ { feature: "cached result fallback", keys: ["grid.cachedResultUnavailable", "grid.reexecuteQuery"] },
+ { feature: "Nacos global replace", keys: ["nacos.contentReplace*", "nacos.replaceHistory.*"], locales: EXCEPT_AZ_TR, translated: true },
+ { feature: "SQLite table rebuild notice", keys: ["structureEditor.sqliteRebuildNotice"] },
+ { feature: "custom types", keys: ["customType.kinds.composite", "customType.tabs.properties", "customType.members.empty", "customType.properties.empty", "customType.ddl.empty", "customType.ddl.incomplete", "contextMenu.viewDetails"], translated: true },
+ { feature: "Dameng object compilation", keys: ["contextMenu.compileObjectFailedTitle", "contextMenu.compileObjectFailedMessage"], locales: EXCEPT_AZ_TR, translated: true },
+ { feature: "user administration Host change", keys: ["userAdmin.changeHost", "userAdmin.newHost"], translated: true },
+ { feature: "plugin batch actions", keys: ["pluginPlatform.batchDuplicateSources", "pluginPlatform.batchRefreshFailed"], locales: EXCEPT_AZ_TR },
+ { feature: "shared refresh action (#8768)", keys: ["common.refresh"] },
+ { feature: "transfer bulk select", keys: under("transfer", ["bulkSelectObjects", "bulkSelectTitle", "bulkSelectHint", "bulkSelectPlaceholder", "bulkSelectConfirm", "bulkSelectMatched", "bulkSelectUnmatched", "noMatchingObjects"]), translated: true },
+ { feature: "table info pin", keys: ["grid.pinTableInfo", "grid.unpinTableInfo"], translated: true },
+ { feature: "Consul workspace", keys: ["consul.ui.*", "consul.tools.*"] },
+ { feature: "MQTT max packet size", keys: ["connection.mqttMaxPacketSize"] },
+ { feature: "sidebar search skip hint", keys: ["sidebar.searchConnectionSkipped"] },
+ { feature: "PostgreSQL legacy TLS", keys: ["connection.postgresLegacyTls", "connection.postgresLegacyTlsHint"] },
+ { feature: "settings search sections", keys: ["settings.syncWebDavWebDescription", "settings.performanceSection"] },
+ { feature: "Redis batch expiration", keys: under("redis", ["batchExpiry", "batchExpiryTitle", "batchExpirySelected", "batchExpiryApply", "batchExpirySuccess", "batchExpiryPartial"]) },
+];
+
+function lookup(messages: unknown, path: string): unknown {
+ return path.split(".").reduce<unknown>((node, key) => (node && typeof node === "object" ? (node as Messages)[key] : undefined), messages);
+}
+
+function leafPaths(value: unknown, prefix = ""): string[] {
+ if (typeof value === "string") return [prefix];
+ if (!value || typeof value !== "object" || Array.isArray(value)) return [];
+ return Object.entries(value as Messages).flatMap(([key, child]) => leafPaths(child, prefix ? `${prefix}.${key}` : key));
+}
+
+function resolveKeys(selector: string): string[] {
+ if (!selector.endsWith("*")) return [selector];
+ const dot = selector.lastIndexOf(".");
+ const parent = selector.slice(0, dot);
+ const stem = selector.slice(dot + 1, -1);
+ const keys = leafPaths(lookup(en, parent))
+ .filter((path) => path.startsWith(stem))
+ .map((path) => `${parent}.${path}`);
+ expect(keys.length, `${selector} matches no English messages`).toBeGreaterThan(0);
+ return keys;
+}
+
+/** Named interpolations such as `{count}`; literal interpolations like `{'{'}` are text. */
+function placeholders(message: unknown): string[] {
+ if (typeof message !== "string") return [];
+ return [...new Set([...message.matchAll(/\{\s*([A-Za-z_][\w]*)\s*\}/g)].map((match) => match[1]))].sort();
+}
+
+describe.each(FEATURE_MESSAGES)("$feature messages", ({ keys: selectors, locales = ALL_LOCALES, translated }) => {
+ const keys = selectors.flatMap(resolveKeys);
+
+ it.each(ALL_LOCALES)("%s declares its messages with the English placeholders", (locale) => {
+ for (const key of keys) {
+ const text = lookup(declared[locale], key);
+ const english = lookup(en, key);
+ if (text === undefined && !locales.includes(locale)) continue;
+ expect(text, `${locale}: ${key}`).toBeTypeOf("string");
+ expect((text as string).trim(), `${locale}: ${key}`).not.toBe("");
+ expect(placeholders(text), `${locale}: ${key} placeholders`).toEqual(placeholders(english));
+ if (translated && locale !== "en") expect(text, `${locale}: ${key} must not reuse the English text`).not.toBe(english);
+ }
+ for (const selector of selectors.filter((entry) => entry.endsWith(".*"))) {
+ const namespace = selector.slice(0, -2);
+ const extra = leafPaths(lookup(declared[locale], namespace)).filter((path) => !keys.includes(`${namespace}.${path}`));
+ expect(extra, `${locale}: keys under ${namespace} that English does not declare`).toEqual([]);
+ }
+ });
+});
+
+describe("feature message rendering", () => {
+ const keys = FEATURE_MESSAGES.flatMap((entry) => entry.keys.flatMap(resolveKeys));
+
+ it.each(ALL_LOCALES)("%s renders every feature message through vue-i18n with its parameters", async (locale) => {
+ const { withEnglishFallback } = await vi.importActual<typeof import("../locales/fallback")>("../locales/fallback");
+ const messages = locale === "en" ? en : withEnglishFallback(declared[locale]);
+ const i18n = createI18n({ legacy: false, locale, messages: { [locale]: messages }, missingWarn: false, fallbackWarn: false });
+ for (const key of keys) {
+ const params = Object.fromEntries(placeholders(lookup(messages, key)).map((name) => [name, `<${name}>`]));
+ const text = i18n.global.t(key, params);
+ expect(text, `${locale}: ${key}`).not.toBe(key);
+ for (const value of Object.values(params)) expect(text, `${locale}: ${key}`).toContain(value);
+ }
+ i18n.dispose();
+ });
+});
+
+describe("feature message content rules", () => {
+ it.each(EXCEPT_AZ_TR)("%s keeps the Dameng validity labels as the database literals", (locale) => {
+ const objects = (locale === "en" ? en : declared[locale]).objects as Messages | undefined;
+ expect(objects?.validStatus ?? en.objects.validStatus).toBe("VALID");
+ expect(objects?.invalidStatus ?? en.objects.invalidStatus).toBe("INVALID");
+ });
+
+ it.each(ALL_LOCALES)("%s warns that a SQLite rebuild forces CAST conversion with lossy 0.0 values", (locale) => {
+ const notice = String(lookup(declared[locale], "structureEditor.sqliteRebuildNotice"));
+ expect(notice).toContain("CAST");
+ expect(notice).toContain("0.0");
+ });
+});
diff --git a/apps/desktop/src/i18n/__tests__/mqttConnectionLabelParity.spec.ts b/apps/desktop/src/i18n/__tests__/mqttConnectionLabelParity.spec.ts
deleted file mode 100644
index 607b67b655..0000000000
--- a/apps/desktop/src/i18n/__tests__/mqttConnectionLabelParity.spec.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { readFileSync } from "node:fs";
-import { createI18n } from "vue-i18n";
-import { describe, expect, it } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-// These assertions read the locale SOURCES as text instead of importing the modules.
-// Every non-English locale is `export default withEnglishFallback({ ... })`, and
-// withEnglishFallback deep-merges `en` UNDER the locale at import time, so the imported
-// default export already carries every english key — including the key this spec exists
-// to guard. Asserting on those objects would pass even if a locale silently dropped the
-// label (same trap documented in docsNamespaceParity.spec.ts), so the check has to happen
-// before the merge does.
-function localeSource(name: string): string {
- return readFileSync(new URL(`../locales/${name}.ts`, import.meta.url), "utf8");
-}
-
-function declaredString(source: string, key: string): string | undefined {
- return source.match(new RegExp(String.raw`^\s*${key}:\s*"((?:[^"\\]|\\.)*)",\s*$`, "m"))?.[1];
-}
-
-// The locales that carry the connection.mqtt* form cluster (led by mqttKeepAlive).
-const localesCarryingMqttCluster = ["en", "zh-CN", "zh-TW", "ja", "it", "es", "pt-BR", "tr", "az"];
-// Every locale FILE must declare the key in source. This is the assertion that actually
-// guards drift: the imported modules cannot show a removed source key, because
-// withEnglishFallback deep-merges english underneath at import time (see header).
-const allLocaleFiles = [...localesCarryingMqttCluster, "ko"];
-
-describe("mqtt max packet size label i18n parity", () => {
- it("english declares the label with its byte unit", () => {
- expect(declaredString(localeSource("en"), "mqttMaxPacketSize")).toContain("bytes");
- });
-
- it.each(allLocaleFiles)("%s declares the label in its source file", (name) => {
- const label = declaredString(localeSource(name), "mqttMaxPacketSize");
- expect(label, `${name}.ts must declare connection.mqttMaxPacketSize`).toBeTruthy();
- expect(label?.trim()).not.toBe("");
- });
-
- it.each(localesCarryingMqttCluster)("%s declares the label alongside its mqtt cluster", (name) => {
- const source = localeSource(name);
- // Anchor: only locales that already declare the cluster get the new key.
- expect(declaredString(source, "mqttKeepAlive"), `${name}.ts must declare connection.mqttKeepAlive`).toBeTruthy();
- // Semantic-cluster anchoring (i18n-locales.md): the label belongs next to mqttConnectTimeout.
- expect(source.indexOf("mqttMaxPacketSize:"), `${name}.ts must anchor the key after mqttConnectTimeout`).toBeGreaterThan(source.indexOf("mqttConnectTimeout:"));
- });
-
- it("ko declares the label without taking on the rest of the mqtt form cluster", () => {
- const source = localeSource("ko");
- // ko translates a few mqtt console strings but none of the form fields, so the form
- // renders in english there via withEnglishFallback. This one label is the deliberate
- // exception: it is declared in source so the Korean text exists in the file, and it is
- // the only form key ko owns — do not grow the cluster here.
- expect(declaredString(source, "mqttMaxPacketSize")).toBeTruthy();
- expect(declaredString(source, "mqttKeepAlive")).toBeUndefined();
- expect(declaredString(source, "mqttConnectTimeout")).toBeUndefined();
- });
-});
-
-// Layer (a) from the PRD: the label must also resolve through vue-i18n at runtime. This is
-// weaker than the source-level check above — the deep-merge hands a locale that drops the
-// key the english text, so it cannot see drift — but it is what catches a locale module
-// that fails to declare or parse the key at all, and the "key path leaks into the UI"
-// failure mode that a missing translation produces.
-const localeModules: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", itLocale],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-describe("mqtt max packet size label resolution", () => {
- it.each(localeModules)("%s resolves the label to a translated string", (name, messages) => {
- const connection = (messages.connection ?? {}) as typeof en.connection;
- const i18n = createI18n({ legacy: false, locale: name, messages: { [name]: { connection } } });
- const label = i18n.global.t("connection.mqttMaxPacketSize");
- expect(label).not.toBe("connection.mqttMaxPacketSize");
- expect(label.trim()).not.toBe("");
- i18n.dispose();
- });
-});
-
-describe("connection dialog mqtt label call site", () => {
- const componentSource = readFileSync(new URL("../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
- it("renders the label through vue-i18n instead of a hardcoded chinese string", () => {
- expect(componentSource).toContain('{{ t("connection.mqttMaxPacketSize") }}');
- expect(componentSource).not.toContain("最大报文");
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/nacosContentReplaceParity.spec.ts b/apps/desktop/src/i18n/__tests__/nacosContentReplaceParity.spec.ts
deleted file mode 100644
index 30aefb5091..0000000000
--- a/apps/desktop/src/i18n/__tests__/nacosContentReplaceParity.spec.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it } from "vitest";
-import en from "../locales/en";
-import es from "../locales/es";
-import itLocale from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-function entries(value: unknown, prefix = ""): Array<[string, string]> {
- if (typeof value === "string") return [[prefix, value]];
- if (value === null || typeof value !== "object" || Array.isArray(value)) return [];
- return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) => entries(child, prefix ? `${prefix}.${key}` : key));
-}
-
-function placeholders(message: string): string[] {
- return [...message.matchAll(/\{[^{}]+\}/g)].map(([match]) => match).sort();
-}
-
-const source = new Map(entries(zhCN.nacos).filter(([key]) => key.startsWith("contentReplace") || key.startsWith("replaceHistory.")));
-const english = new Map(entries(en.nacos));
-const locales = { en, es, it: itLocale, ja, ko, "pt-BR": ptBR, "zh-TW": zhTW };
-
-describe("Nacos global replacement translations", () => {
- it("declares the new source messages", () => {
- expect(source.size).toBe(51);
- });
-
- it.each(Object.entries(locales))("%s has localized messages with matching placeholders", (name, locale) => {
- const translated = new Map(entries(locale.nacos));
- for (const [key, text] of source) {
- expect(translated.get(key), key).toBeTruthy();
- expect(placeholders(translated.get(key) ?? ""), key).toEqual(placeholders(text));
- if (name !== "en") expect(translated.get(key), `${name}:${key} must not fall back to English`).not.toBe(english.get(key));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/pluginBatchMessages.spec.ts b/apps/desktop/src/i18n/__tests__/pluginBatchMessages.spec.ts
deleted file mode 100644
index a5b51accca..0000000000
--- a/apps/desktop/src/i18n/__tests__/pluginBatchMessages.spec.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { createI18n } from "vue-i18n";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-describe("plugin batch messages", () => {
- it.each(Object.entries({ az, en, es, it: itLocale, ja, ko, "pt-BR": ptBR, tr, "zh-CN": zhCN, "zh-TW": zhTW }))("interpolates source conflicts and refresh errors in %s", (locale, messages) => {
- const pluginPlatform = messages.pluginPlatform as Pick<typeof en.pluginPlatform, "batchDuplicateSources" | "batchRefreshFailed">;
- const i18n = createI18n({ legacy: false, locale, messages: { [locale]: { pluginPlatform } } });
- expect(pluginPlatform.batchDuplicateSources.match(/\{[^}]+\}/g)).toEqual(["{names}"]);
- expect(pluginPlatform.batchRefreshFailed.match(/\{[^}]+\}/g)).toEqual(["{error}"]);
- expect(i18n.global.t("pluginPlatform.batchDuplicateSources", { names: "example.plugin" })).toContain("example.plugin");
- expect(i18n.global.t("pluginPlatform.batchRefreshFailed", { error: "refresh offline" })).toContain("refresh offline");
- i18n.dispose();
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/processListBatchTerminateMessages.spec.ts b/apps/desktop/src/i18n/__tests__/processListBatchTerminateMessages.spec.ts
deleted file mode 100644
index 54df8336bb..0000000000
--- a/apps/desktop/src/i18n/__tests__/processListBatchTerminateMessages.spec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-const BATCH_TERMINATE_KEYS = ["batchTerminate", "batchTerminateTitle", "batchTerminateConfirm", "batchTerminateRunning", "batchTerminateSummary"];
-
-describe("process list batch terminate locale parity", () => {
- it.each(locales)("%s ships every batch terminate key", (_name, locale) => {
- const processList = (locale as { processList: Record<string, unknown> }).processList;
- for (const key of BATCH_TERMINATE_KEYS) {
- expect(typeof processList[key]).toBe("string");
- expect(String(processList[key]).trim().length).toBeGreaterThan(0);
- }
- });
-
- it("keeps the count and summary placeholders in every locale", () => {
- for (const [_name, locale] of locales) {
- const processList = (locale as { processList: Record<string, string> }).processList;
- expect(processList.batchTerminate).toContain("{count}");
- expect(processList.batchTerminateConfirm).toContain("{count}");
- expect(processList.batchTerminateSummary).toContain("{succeeded}");
- expect(processList.batchTerminateSummary).toContain("{failed}");
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/quickOpenNamespaceParity.spec.ts b/apps/desktop/src/i18n/__tests__/quickOpenNamespaceParity.spec.ts
deleted file mode 100644
index 90074b6fd2..0000000000
--- a/apps/desktop/src/i18n/__tests__/quickOpenNamespaceParity.spec.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-type Messages = Record<string, unknown>;
-
-const locales: Array<[string, Messages]> = [
- ["az", az],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-const namespaces = ["quickOpen"] as const;
-
-function leafEntries(value: unknown, prefix = ""): Array<[string, string]> {
- if (typeof value === "string") return [[prefix, value]];
- if (value === null || typeof value !== "object" || Array.isArray(value)) return [];
- return Object.entries(value as Messages).flatMap(([key, child]) => leafEntries(child, prefix ? `${prefix}.${key}` : key));
-}
-
-describe.each(namespaces)("%s i18n namespace parity", (namespace) => {
- const englishEntries = new Map(leafEntries((en as Messages)[namespace]));
-
- it("english declares the namespace", () => {
- expect(englishEntries.size).toBeGreaterThan(0);
- });
-
- it("english declares the global-search keys", () => {
- for (const key of ["searchingContent", "globalSearchHint", "modeObjects", "modeContent", "contentPlaceholder", "searchSettings", "searchRoots", "addDirectory", "noRootsConfigured", "removePath", "searchExtensions", "extensionsPlaceholder", "apply"]) {
- expect(englishEntries.has(key), `missing quickOpen.${key}`).toBe(true);
- }
- });
-
- it.each(locales)("%s declares the same keys", (_name, locale) => {
- const localeEntries = new Map(leafEntries(locale[namespace]));
- expect([...localeEntries.keys()].sort()).toEqual([...englishEntries.keys()].sort());
- });
-
- it("every locale declares the globalSearch shortcut label", () => {
- for (const [name, locale] of locales) {
- const settings = locale.settings as Messages | undefined;
- expect(settings?.shortcutGlobalSearch, `${name}.settings.shortcutGlobalSearch`).toBeTruthy();
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/sidebarSearchSkipParity.spec.ts b/apps/desktop/src/i18n/__tests__/sidebarSearchSkipParity.spec.ts
deleted file mode 100644
index 6ce153e511..0000000000
--- a/apps/desktop/src/i18n/__tests__/sidebarSearchSkipParity.spec.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { readFileSync } from "node:fs";
-import { createI18n } from "vue-i18n";
-import { describe, expect, it } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-// The sidebar-search skip hint is a single-line projection of a driver error
-// (see connectionStore.recordSidebarSearchConnectionFailure). Every locale has
-// to own the `{message}` placeholder, so this reads the locale SOURCES as text:
-// non-English locales are `export default withEnglishFallback({ ... })`, and the
-// import-time deep merge would hide a locale that silently dropped the key.
-function localeSource(name: string): string {
- return readFileSync(new URL(`../locales/${name}.ts`, import.meta.url), "utf8");
-}
-
-function declaredString(source: string, key: string): string | undefined {
- return source.match(new RegExp(String.raw`^\s*${key}:\s*"((?:[^"\\]|\\.)*)",\s*$`, "m"))?.[1];
-}
-
-const localeNames = ["az", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "zh-CN", "zh-TW"];
-
-describe("sidebar search skip hint i18n parity", () => {
- it("english declares the key with its message placeholder", () => {
- const label = declaredString(localeSource("en"), "searchConnectionSkipped");
- expect(label).toContain("{message}");
- });
-
- it.each(localeNames)("%s declares the key with the message placeholder in its source file", (name) => {
- const label = declaredString(localeSource(name), "searchConnectionSkipped");
- expect(label, `${name}.ts must declare sidebar.searchConnectionSkipped`).toBeTruthy();
- expect(label).toContain("{message}");
- });
-
- it.each(localeNames)("%s anchors the key inside the sidebar namespace", (name) => {
- const source = localeSource(name);
- expect(source.indexOf("searchConnectionSkipped:")).toBeGreaterThan(source.indexOf("sortConnectionsDescending:"));
- expect(source.indexOf("searchConnectionSkipped:")).toBeLessThan(source.indexOf("searchScopeConnection:"));
- });
-});
-
-const localeModules: Array<[string, Record<string, unknown>]> = [
- ["az", az],
- ["en", en],
- ["es", es],
- ["it", itLocale],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-describe("sidebar search skip hint resolution", () => {
- it.each(localeModules)("%s renders the driver detail inside the hint", (name, messages) => {
- const sidebar = (messages.sidebar ?? {}) as typeof en.sidebar;
- const i18n = createI18n({ legacy: false, locale: name, messages: { [name]: { sidebar } } });
- const hint = i18n.global.t("sidebar.searchConnectionSkipped", { message: "tls handshake eof" });
- expect(hint).not.toBe("sidebar.searchConnectionSkipped");
- expect(hint).toContain("tls handshake eof");
- i18n.dispose();
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/sqliteRebuildNotice.spec.ts b/apps/desktop/src/i18n/__tests__/sqliteRebuildNotice.spec.ts
deleted file mode 100644
index bb93ec1bff..0000000000
--- a/apps/desktop/src/i18n/__tests__/sqliteRebuildNotice.spec.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it as test } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import it from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-function sqliteRebuildNotice(messages: Record<string, unknown>): string {
- const structureEditor = messages.structureEditor as Record<string, unknown>;
- return String(structureEditor.sqliteRebuildNotice);
-}
-
-describe("SQLite rebuild notice", () => {
- test.each([
- ["Azerbaijani", az],
- ["English", en],
- ["Spanish", es],
- ["Italian", it],
- ["Japanese", ja],
- ["Korean", ko],
- ["Brazilian Portuguese", ptBR],
- ["Turkish", tr],
- ["Simplified Chinese", zhCN],
- ["Traditional Chinese", zhTW],
- ])("warns about retained backup, forced CAST conversion, lossy values, and rollback in %s", (_locale, messages) => {
- const notice = sqliteRebuildNotice(messages);
-
- expect(notice.length).toBeGreaterThan(30);
- expect(notice).toContain("CAST");
- expect(notice).toContain("0.0");
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/tabContextMenuKeys.spec.ts b/apps/desktop/src/i18n/__tests__/tabContextMenuKeys.spec.ts
deleted file mode 100644
index caf8087ef7..0000000000
--- a/apps/desktop/src/i18n/__tests__/tabContextMenuKeys.spec.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-// EditorGroupTabBar renders its context menu via `t("contextMenu.<key>")`.
-// When a key is missing everywhere, vue-i18n echoes the key path itself and
-// the menu shows raw text like "contextMenu.pinTab" (regression in 5a3a6e2bb:
-// the component landed without locale entries; spec mocks supplied their own
-// translations, so tests stayed green). en is the fallbackLocale, so a missing
-// en key leaks the raw path in every language — guard the full tab-menu key
-// set against the real en module, not a mock.
-const tabMenuKeys = ["changeOrientation", "closeAllTabs", "closeLeftTabs", "closeOtherTabs", "closeRightTabs", "closeTab", "closeTabGroup", "compactTabTitle", "copyName", "editTabGroup", "fullTabTitle", "pinTab", "resetTabGroup", "splitDown", "splitRight", "unpinTab", "unsplit"] as const;
-
-// Non-English locales are `export default withEnglishFallback({...})`, so
-// these imports are en-merged; the assertions below prove the key resolves to
-// real text for every UI language, while the en test above is the one that
-// actually catches a missing-from-everywhere key.
-const locales: Array<[string, Record<string, unknown>]> = [
- ["az", az as Record<string, unknown>],
- ["en", en as Record<string, unknown>],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function contextMenuEntry(locale: Record<string, unknown>, key: string): unknown {
- const contextMenu = locale["contextMenu"];
- if (!contextMenu || typeof contextMenu !== "object") return undefined;
- return (contextMenu as Record<string, unknown>)[key];
-}
-
-describe("tab context menu i18n keys", () => {
- it.each(tabMenuKeys)("en resolves contextMenu.%s to text", (key) => {
- const value = contextMenuEntry(en as Record<string, unknown>, key);
- expect(value, `contextMenu.${key} missing from locales/en.ts`).toBeTypeOf("string");
- expect(value).not.toBe("");
- });
-
- it.each(locales)("%s resolves pin/unpin tab menu labels", (_name, locale) => {
- for (const key of ["pinTab", "unpinTab"] as const) {
- expect(contextMenuEntry(locale, key), `${_name} contextMenu.${key}`).toBeTypeOf("string");
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/tableInfoPinMessages.spec.ts b/apps/desktop/src/i18n/__tests__/tableInfoPinMessages.spec.ts
deleted file mode 100644
index 4d960a2b41..0000000000
--- a/apps/desktop/src/i18n/__tests__/tableInfoPinMessages.spec.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["en", en as Record<string, unknown>],
- ["az", az as Record<string, unknown>],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function gridEntry(locale: Record<string, unknown>, key: string): unknown {
- const grid = locale["grid"];
- if (!grid || typeof grid !== "object") return undefined;
- return (grid as Record<string, unknown>)[key];
-}
-
-describe("table-info pin i18n messages", () => {
- it.each(["pinTableInfo", "unpinTableInfo"] as const)("en resolves grid.%s to text", (key) => {
- expect(gridEntry(en as Record<string, unknown>, key), `grid.${key} missing from locales/en.ts`).toBeTypeOf("string");
- });
-
- it.each(locales.slice(1))("%s translates table-info pin labels instead of using the English fallback", (_name, locale) => {
- for (const key of ["pinTableInfo", "unpinTableInfo"] as const) {
- const value = gridEntry(locale, key);
- expect(value, `${_name} grid.${key}`).toBeTypeOf("string");
- expect(value).not.toBe(gridEntry(en as Record<string, unknown>, key));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/transferBulkSelectParity.spec.ts b/apps/desktop/src/i18n/__tests__/transferBulkSelectParity.spec.ts
deleted file mode 100644
index f2cc5c07ea..0000000000
--- a/apps/desktop/src/i18n/__tests__/transferBulkSelectParity.spec.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "../locales/az";
-import en from "../locales/en";
-import es from "../locales/es";
-import it_ from "../locales/it";
-import ja from "../locales/ja";
-import ko from "../locales/ko";
-import ptBR from "../locales/pt-BR";
-import tr from "../locales/tr";
-import zhCN from "../locales/zh-CN";
-import zhTW from "../locales/zh-TW";
-
-// 数据传输「批量录入对象」相关文案,需要所有语言齐全,避免回落到英文
-const TRANSFER_BULK_SELECT_KEYS = ["bulkSelectObjects", "bulkSelectTitle", "bulkSelectHint", "bulkSelectPlaceholder", "bulkSelectConfirm", "bulkSelectMatched", "bulkSelectUnmatched", "noMatchingObjects"] as const;
-
-const locales: Array<[string, Record<string, unknown>]> = [
- ["en", en as Record<string, unknown>],
- ["az", az as Record<string, unknown>],
- ["es", es],
- ["it", it_],
- ["ja", ja],
- ["ko", ko],
- ["pt-BR", ptBR],
- ["tr", tr],
- ["zh-CN", zhCN],
- ["zh-TW", zhTW],
-];
-
-function transferEntry(locale: Record<string, unknown>, key: string): unknown {
- const transfer = locale["transfer"];
- if (!transfer || typeof transfer !== "object") return undefined;
- return (transfer as Record<string, unknown>)[key];
-}
-
-describe("transfer bulk-select i18n messages", () => {
- it.each(TRANSFER_BULK_SELECT_KEYS)("en resolves transfer.%s to text", (key) => {
- expect(transferEntry(en as Record<string, unknown>, key), `transfer.${key} missing from locales/en.ts`).toBeTypeOf("string");
- });
-
- it.each(locales.slice(1))("%s translates the bulk-select labels instead of using the English fallback", (_name, locale) => {
- for (const key of TRANSFER_BULK_SELECT_KEYS) {
- const value = transferEntry(locale, key);
- expect(value, `${_name} transfer.${key}`).toBeTypeOf("string");
- expect(value, `${_name} transfer.${key} should not reuse the English text`).not.toBe(transferEntry(en as Record<string, unknown>, key));
- }
- });
-});
diff --git a/apps/desktop/src/i18n/__tests__/userAdminHostMessages.spec.ts b/apps/desktop/src/i18n/__tests__/userAdminHostMessages.spec.ts
deleted file mode 100644
index c5d700225e..0000000000
--- a/apps/desktop/src/i18n/__tests__/userAdminHostMessages.spec.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, it } from "vitest";
-import az from "@/i18n/locales/az";
-import en from "@/i18n/locales/en";
-import es from "@/i18n/locales/es";
-import itLocale from "@/i18n/locales/it";
-import ja from "@/i18n/locales/ja";
-import ko from "@/i18n/locales/ko";
-import ptBR from "@/i18n/locales/pt-BR";
-import tr from "@/i18n/locales/tr";
-import zhCN from "@/i18n/locales/zh-CN";
-import zhTW from "@/i18n/locales/zh-TW";
-
-describe("user administration Host translations", () => {
- it("provides the Host-change labels in English", () => {
- expect(en.userAdmin.changeHost).toEqual(expect.any(String));
- expect(en.userAdmin.newHost).toEqual(expect.any(String));
- });
-
- it("provides localized Host-change labels in every non-English locale", () => {
- const locales = { az, es, it: itLocale, ja, ko, "pt-BR": ptBR, tr, "zh-CN": zhCN, "zh-TW": zhTW };
- for (const [locale, messages] of Object.entries(locales)) {
- expect(messages.userAdmin.changeHost, locale).not.toBe(en.userAdmin.changeHost);
- expect(messages.userAdmin.newHost, locale).not.toBe(en.userAdmin.newHost);
- }
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/ai/addToAiDatabaseContext.spec.ts b/apps/desktop/src/lib/__tests__/ai/addToAiDatabaseContext.spec.ts
deleted file mode 100644
index 42fd472282..0000000000
--- a/apps/desktop/src/lib/__tests__/ai/addToAiDatabaseContext.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-
-describe("add to AI database context", () => {
- it("accepts database tree nodes with an empty database identifier", () => {
- const addToAiStart = appSource.indexOf("async function addToAi");
- const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
- const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
-
- expect(addToAiSource).toContain("else if (hasTreeNodeDatabaseContext(node))");
- expect(addToAiSource).not.toContain("else if (node.database)");
- });
-
- it("adds every selected table as an AI mention", () => {
- const addToAiStart = appSource.indexOf("async function addToAi");
- const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
- const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
-
- expect(addToAiSource).toContain("Array.isArray(nodesInput) ? nodesInput : [nodesInput]");
- expect(addToAiSource).toContain('entry.type === "table"');
- // Every selected table still becomes a mention, and it now carries the
- // binding the conversation must adopt (#9902).
- expect(addToAiSource).toContain("for (const mention of tableMentions) handle.addTableMention(mention, binding)");
- });
-
- it("retargets the conversation instead of moving the workspace (#9902)", () => {
- const addToAiStart = appSource.indexOf("async function addToAi");
- const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
- const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
-
- expect(addToAiSource).toContain("const binding: AiConversationBinding = { connectionId: node.connectionId");
- // Asking about a table must not reassign the global active connection or
- // switch/create an editor tab — that is what made the AI panel's target
- // global.
- expect(addToAiSource).not.toContain("connectionStore.activeConnectionId =");
- expect(addToAiSource).not.toContain("queryStore.switchTab(");
- expect(addToAiSource).not.toContain("queryStore.createTab(");
- });
-
- it("retargets even when the entry adds no table mention", () => {
- // "Ask AI" on a connection or database node produces no mentions at all, so
- // applying the binding only inside the mention loop would silently skip it.
- const addToAiStart = appSource.indexOf("async function addToAi");
- const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
- const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
-
- expect(addToAiSource).toContain("void handle.bindConversation(binding);");
- // The call must not live inside the mention loop.
- const loopIdx = addToAiSource.indexOf("for (const mention of tableMentions)");
- const bindIdx = addToAiSource.indexOf("void handle.bindConversation(binding);");
- expect(bindIdx).toBeLessThan(loopIdx);
- });
-
- it("resolves the AI execution tab by the exact namespace", () => {
- // `(!schema || tab.schema === schema)` used to accept a tab on ANY schema
- // when the target had none, and execution then inherited that tab's schema.
- const start = appSource.indexOf("function ensureQueryTabForConnection");
- const body = appSource.slice(start, appSource.indexOf("queryStore.createTab", start));
-
- expect(body).toContain("(tab.schema || undefined) === schema");
- expect(body).not.toContain("!schema ||");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/ai/maxAgentTurnsRange.spec.ts b/apps/desktop/src/lib/__tests__/ai/maxAgentTurnsRange.spec.ts
index 6d3ef5839f..028e5873e1 100644
--- a/apps/desktop/src/lib/__tests__/ai/maxAgentTurnsRange.spec.ts
+++ b/apps/desktop/src/lib/__tests__/ai/maxAgentTurnsRange.spec.ts
@@ -1,9 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { MAX_AGENT_TURNS_DEFAULT, MAX_AGENT_TURNS_MAX, MAX_AGENT_TURNS_MIN, maxAgentTurnsOutOfRange, normalizeMaxAgentTurns } from "@/lib/ai/maxAgentTurns";
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
describe("maxAgentTurnsOutOfRange", () => {
it("accepts values within [min, max]", () => {
expect(maxAgentTurnsOutOfRange(30)).toBe(false);
@@ -27,24 +24,6 @@ describe("maxAgentTurnsOutOfRange", () => {
});
});
-describe("agent turn limit loading", () => {
- it("starts loading independently and blocks saves until the persisted value arrives", () => {
- const aiTabStart = settingsDialogSource.indexOf('if (tab === "ai") {');
- const aiTabBranch = settingsDialogSource.slice(aiTabStart, settingsDialogSource.indexOf('if (tab === "about"', aiTabStart));
- expect(aiTabBranch.indexOf("void loadMaxAgentTurnsSetting()")).toBeLessThan(aiTabBranch.indexOf("await promptTemplateStore.ensureLoaded()"));
- expect(settingsDialogSource).toContain("if (!maxAgentTurnsLoaded.value) return;");
- expect(settingsDialogSource).toContain(':disabled="!maxAgentTurnsLoaded || maxAgentTurnsSaving"');
- expect(settingsDialogSource).toContain(':disabled="!maxAgentTurnsLoaded || maxAgentTurnsSaving || maxAgentTurnsOutOfRange(editMaxAgentTurns)"');
- });
-
- it("keeps failed loads retryable instead of replacing them with the default", () => {
- const loadFunction = settingsDialogSource.slice(settingsDialogSource.indexOf("async function loadMaxAgentTurnsSetting()"), settingsDialogSource.indexOf("async function saveMaxAgentTurnsSetting()"));
- expect(loadFunction).toContain("maxAgentTurnsLoadError.value = e?.message || String(e)");
- expect(loadFunction).not.toContain("editMaxAgentTurns.value = MAX_AGENT_TURNS_DEFAULT");
- expect(settingsDialogSource).toContain('v-if="maxAgentTurnsLoadError"');
- });
-});
-
describe("normalizeMaxAgentTurns", () => {
it("preserves and rounds finite values within the supported range", () => {
expect(normalizeMaxAgentTurns(100)).toBe(100);
diff --git a/apps/desktop/src/lib/__tests__/app/rightSidebarPanels.spec.ts b/apps/desktop/src/lib/__tests__/app/rightSidebarPanels.spec.ts
deleted file mode 100644
index db90d857f8..0000000000
--- a/apps/desktop/src/lib/__tests__/app/rightSidebarPanels.spec.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
-
-function functionSource(name: string, nextName: string): string {
- const start = appSource.indexOf(`function ${name}`);
- const end = appSource.indexOf(`function ${nextName}`, start + 1);
- return appSource.slice(start, end);
-}
-
-describe("right sidebar panel entry points", () => {
- it("routes toolbar and close actions through the centralized controller", () => {
- expect(appSource).toContain("@toggle-ai=\"toggleRightSidebarPanel('ai')\"");
- expect(appSource).toContain("@toggle-history=\"toggleRightSidebarPanel('history')\"");
- expect(appSource).toContain("@toggle-sql-library=\"toggleRightSidebarPanel('sqlLibrary')\"");
- expect(appSource).toContain("@toggle-sql-file-panel=\"toggleRightSidebarPanel('sqlFile')\"");
- expect(appSource).toContain("@close=\"closeRightSidebarPanel('history')\"");
- expect(appSource).toContain("@close=\"closeRightSidebarPanel('sqlLibrary')\"");
- expect(appSource).toContain("@close=\"closeRightSidebarPanel('sqlFile')\"");
- });
-
- it("toggles the AI panel through the configured global shortcut", () => {
- expect(appSource).toContain("isToggleAiPanelShortcut(e, shortcuts)");
- expect(appSource).toContain('toggleRightSidebarPanel("ai");');
- });
-
- it("routes welcome, history analysis, selection, and error-fix opens through the same controller", () => {
- expect(appSource).toContain("@show-history=\"openRightSidebarPanel('history')\"");
- expect(functionSource("fixWithAi", "sendSelectionToAi")).toContain('openRightSidebarPanel("ai")');
- expect(functionSource("sendSelectionToAi", "openAiPanel")).toContain('openRightSidebarPanel("ai")');
- expect(functionSource("openAiPanel", "analyzeHistoryWithAi")).toContain('openRightSidebarPanel("ai")');
- });
-
- it("keeps existing persisted panel keys and synchronizes exclusivity after settings load", () => {
- expect(appSource).toContain('ai: "dbx-ai-panel-open"');
- expect(appSource).toContain('sqlLibrary: "dbx-sql-library-open"');
- expect(appSource).toContain('sqlFile: "dbx-sql-file-panel-open"');
- expect(appSource).not.toContain('history: "dbx-');
- expect(appSource).toContain("settingsStore.isEditorSettingsLoaded");
- expect(appSource).toContain("enforceRightSidebarPanelExclusivity(currentRightSidebarPanelState(), lastOpenedRightSidebarPanel)");
- });
-
- it("does not couple toolbar visibility to panel closing", () => {
- for (const [setting, event] of [
- ["sqlLibrary", "toggle-sql-library"],
- ["sqlFileTree", "toggle-sql-file-panel"],
- ["history", "toggle-history"],
- ["ai", "toggle-ai"],
- ]) {
- expect(toolbarSource).toContain(`<Tooltip v-if="toolbarItems.${setting}">`);
- expect(toolbarSource).toContain(`@click="emit('${event}')"`);
- }
- expect(appSource).not.toMatch(/watch\([\s\S]{0,180}toolbarItems\.(ai|history|sqlLibrary|sqlFileTree)[\s\S]{0,180}closeRightSidebarPanel/);
- });
-
- it("keeps the maximized AI surface in the parent layout", () => {
- expect(appSource).toContain("const isAiPanelMaximized = ref(false);");
- expect(appSource).toContain(':maximized="isAiPanelMaximized"');
- expect(appSource).toContain('@toggle-maximize="toggleAiPanelMaximized"');
- expect(appSource).toContain("isAiPanelMaximized ? 'min-w-0 flex-1' : 'min-w-[240px] max-w-full'");
- expect(appSource).toContain('v-show="!isAiPanelMaximized && !isZenMode"');
- expect(functionSource("setRightSidebarPanelOpen", "toggleRightSidebarPanel")).toContain("isAiPanelMaximized.value = false;");
- });
-
- it("keeps Zen mode as a temporary data or Nacos-tab layout", () => {
- expect(appSource).toContain("const isZenMode = ref(false);");
- expect(appSource).toContain('return mode === "data" || mode === "nacos";');
- expect(appSource).toContain("function toggleZenMode() {");
- expect(appSource).toContain("if (!supportsZenMode(activeTab.value?.mode)) return;");
- expect(appSource).toContain("isToggleZenModeShortcut(e, shortcuts) && supportsZenMode(activeTab.value?.mode)");
- expect(appSource).toContain('@toggle-zen-mode="toggleZenMode"');
- expect(appSource).toContain('v-show="sidebarOpen && !isZenMode"');
- expect(appSource).toContain(':show-sidebar-expand="!sidebarOpen && !isZenMode"');
- expect(toolbarSource).toContain('<Tooltip v-if="showSidebarExpand">');
- expect(toolbarSource).toContain("@click=\"emit('expand-sidebar')\"");
- expect(appSource).toContain('@expand-sidebar="setSidebarOpen(true)"');
- expect(appSource).toContain('v-show="!isAiPanelMaximized || isZenMode"');
- expect(appSource).toContain('v-show="!isZenMode"');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/app/snippetMigrationCleanup.spec.ts b/apps/desktop/src/lib/__tests__/app/snippetMigrationCleanup.spec.ts
deleted file mode 100644
index 800375753b..0000000000
--- a/apps/desktop/src/lib/__tests__/app/snippetMigrationCleanup.spec.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-const httpBackendSource = readFileSync(new URL("../../backend/http.ts", import.meta.url), "utf8");
-const tauriBackendSource = readFileSync(new URL("../../backend/tauri.ts", import.meta.url), "utf8");
-
-describe("snippet migration cleanup recovery", () => {
- it("restores pending cleanup state and keeps it visible after restart", () => {
- expect(settingsDialogSource).toContain('pendingLegacyCleanupId.value = settings.legacyCleanupRequiredId || ""');
- expect(settingsDialogSource).toContain('v-if="pendingLegacyCleanupId"');
- expect(settingsDialogSource).toContain('t("settings.syncSnippetMigrateLegacyCleanupRequired", { id: pendingLegacyCleanupId })');
- });
-
- it("clears the UI state only after the retry response confirms cleanup", () => {
- const retryStart = settingsDialogSource.indexOf("async function retryLegacySnippetCleanup()");
- const retryEnd = settingsDialogSource.indexOf("async function downloadSnippetSnapshot()", retryStart);
- const retrySource = settingsDialogSource.slice(retryStart, retryEnd);
- expect(retrySource).toContain("await retrySnippetLegacyCleanup(currentSnippetConfig())");
- expect(retrySource).toContain('pendingLegacyCleanupId.value = settings.legacyCleanupRequiredId || ""');
- expect(retrySource).toContain("if (settings.legacyCleanupRequiredId)");
- });
-
- it("wires the retry operation through both Web and Tauri backends", () => {
- expect(httpBackendSource).toContain('post("/api/cloud-sync/snippet/retry-legacy-cleanup", { config })');
- expect(tauriBackendSource).toContain('invoke("retry_snippet_legacy_cleanup", { config })');
- expect(httpBackendSource).toContain("legacyCleanupRequiredId?: string");
- expect(tauriBackendSource).toContain("legacyCleanupRequiredId?: string");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts
deleted file mode 100644
index 5d6f2f4f97..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialog.deepLinkServices.spec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const source = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
-describe("ConnectionDialog service deep-link hydration", () => {
- it("hydrates specialized refs after generic fields and before one-time submit", () => {
- const applyStart = source.indexOf("function applyConnectionDraftToForm");
- const applyEnd = source.indexOf("function applyConnectionPrefill", applyStart);
- const applyBody = source.slice(applyStart, applyEnd);
- expect(applyBody.indexOf("applyConnectionDraftToConfig")).toBeGreaterThanOrEqual(0);
- expect(applyBody.indexOf("hydrateConsulFields")).toBeGreaterThan(applyBody.indexOf("applyConnectionDraftToConfig"));
- expect(applyBody.indexOf("hydrateNacosFields")).toBeGreaterThan(applyBody.indexOf("applyConnectionDraftToConfig"));
-
- const prefillStart = source.indexOf("function applyConnectionPrefill");
- const prefillEnd = source.indexOf("watch(\n open", prefillStart);
- const prefillBody = source.slice(prefillStart, prefillEnd);
- expect(prefillBody.indexOf("applyConnectionDraftToForm")).toBeLessThan(prefillBody.indexOf("submitOneTimePrefill"));
- });
-
- it("includes service configuration in one-time submission deduplication", () => {
- const keyStart = source.indexOf("function oneTimePrefillKey");
- const keyEnd = source.indexOf("function submitOneTimePrefill", keyStart);
- expect(source.slice(keyStart, keyEnd)).toContain("draft.serviceConfig");
- });
-
- it("hydrates raw service URLs through the deep-link draft path", () => {
- const applyStart = source.indexOf("function applyConnectionUrlToForm");
- const applyEnd = source.indexOf("function hasPendingConnectionUrlInput", applyStart);
- const applyBody = source.slice(applyStart, applyEnd);
- expect(applyBody).toContain("parseConnectionDeepLink(input) ?? parseServiceConnectionUrl(input)");
- expect(applyBody.indexOf("applyConnectionDraftToForm")).toBeLessThan(applyBody.indexOf("parseConnectionUrl(input"));
- });
-
- it("keeps failed one-time connections available for error inspection and retry", () => {
- // The save path delegates one-time connects to startSavedConnection,
- // which owns the connectFailed emission for failed retries.
- const start = source.indexOf("function startSavedConnection");
- const saveStart = source.indexOf("async function save(", start);
- const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
- const saveBody = source.slice(start, saveEnd);
-
- expect(saveBody).not.toContain("store.removeConnection(config.id)");
- expect(saveBody).toContain('emit("connectFailed"');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts
deleted file mode 100644
index 6916f401d3..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogDriverProfileConfig.spec.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { readFileSync } from "node:fs";
-import { parse } from "vue/compiler-sfc";
-import ts from "typescript";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-const parsedDialog = parse(dialogSource, { filename: "ConnectionDialog.vue" });
-
-function connectionConfigForSubmitSource(): string {
- const script = parsedDialog.descriptor.scriptSetup;
- expect(parsedDialog.errors).toEqual([]);
- expect(script).toBeDefined();
-
- const source = ts.createSourceFile("ConnectionDialog.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
- const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === "connectionConfigForSubmit");
- expect(declaration).toBeDefined();
- return declaration!.getText();
-}
-
-describe("ConnectionDialog driver profile configuration", () => {
- it("preserves GaussDB routing and Dolt external configuration on submit", () => {
- const submitConfig = connectionConfigForSubmitSource();
-
- expect(submitConfig).toContain("setGaussdbTargetServerType(config, targetServerType)");
- expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
- });
-
- it("preserves plugin external configuration on submit", () => {
- const submitConfig = connectionConfigForSubmitSource();
-
- expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogErrorLayout.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogErrorLayout.spec.ts
deleted file mode 100644
index dd274bfac7..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogErrorLayout.spec.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
-describe("connection dialog error layout", () => {
- it("installs a required agent before running a connection test", () => {
- const installIndex = dialogSource.indexOf("await ensureRequiredAgentDriverInstalled(config);");
- const testIndex = dialogSource.indexOf("const result = await testConnectionWithTimeout(config, runId);");
-
- expect(installIndex).toBeGreaterThan(-1);
- expect(testIndex).toBeGreaterThan(installIndex);
- });
-
- it("wraps long connection and driver installation errors inside the dialog", () => {
- const wrappingClasses = "min-w-0 max-w-full overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-all [overflow-wrap:anywhere]";
-
- expect(dialogSource.split(wrappingClasses)).toHaveLength(3);
- expect(dialogSource).toContain('<DialogContent class="min-w-0 sm:max-w-[680px]">');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogPluginTimeoutInherit.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogPluginTimeoutInherit.spec.ts
deleted file mode 100644
index 73c766d43f..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogPluginTimeoutInherit.spec.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
-describe("ConnectionDialog plugin connection timeout inheritance", () => {
- const submitFn = dialogSource.slice(dialogSource.indexOf("function connectionConfigForSubmit"));
- const pluginBranch = submitFn.slice(0, submitFn.indexOf("} else {"));
-
- it("keeps the connect timeout inherit flag when submitting plugin connections", () => {
- // buildPluginConnectionConfig rebuilds the config from scratch and drops
- // the inherit flags; without this mirror the store normalizes the absent
- // flag back to the persisted scope and the Advanced-tab radio reverts.
- expect(pluginBranch).toContain("config.connect_timeout_inherit = form.value.connect_timeout_inherit;");
- });
-
- it("keeps the query timeout inherit flag when submitting plugin connections", () => {
- expect(pluginBranch).toContain("config.query_timeout_inherit = form.value.query_timeout_inherit;");
- });
-
- it("still forces connect inheritance off for providers declaring their own handshake timeout field", () => {
- // The resolvedPluginConnectTimeout override must run after the generic
- // mirror so a provider-declared connect_timeout_secs stays the single
- // source of truth and the host RPC deadline cannot inherit the global.
- const mirrorIndex = pluginBranch.indexOf("config.connect_timeout_inherit = form.value.connect_timeout_inherit;");
- const overrideIndex = pluginBranch.indexOf("config.connect_timeout_inherit = false;");
- expect(mirrorIndex).toBeGreaterThan(-1);
- expect(overrideIndex).toBeGreaterThan(mirrorIndex);
- });
-
- it("keeps the per-connection timeout scalars when submitting plugin connections", () => {
- // Toggling back to "current connection" must preserve the typed value:
- // the store treats a stored scalar with inherit=false as a local override.
- expect(pluginBranch).toContain("config.query_timeout_secs = form.value.query_timeout_secs;");
- expect(pluginBranch).toContain("config.connect_timeout_secs = form.value.connect_timeout_secs;");
- });
-});
-
-describe("ConnectionDialog plugin connection timeout scope UI", () => {
- const hydrateBlock = dialogSource.slice(dialogSource.indexOf("connect_timeout_inherit: config.connect_timeout_inherit === true"));
- const queryTimeoutRowStart = dialogSource.lastIndexOf("<div", dialogSource.indexOf('t("connection.queryTimeout")'));
- const connectTimeoutRowStart = dialogSource.lastIndexOf("<div", dialogSource.indexOf('t("connection.connectTimeout")'));
-
- it("hydrates the global scope only from an explicit inherit flag", () => {
- // Round trip with the submit mirror above: only a stored `true` counts as
- // "global", so a preserved flag reopens as global and a preserved scalar
- // reopens as a local override.
- expect(hydrateBlock).toContain("query_timeout_inherit: config.query_timeout_inherit === true,");
- });
-
- it("hides the generic query timeout radio from plugin connections", () => {
- // query_timeout_secs only feeds the database query pipeline, which plugin
- // connections (SSH, ...) never run, so the control would be dead weight.
- expect(dialogSource.slice(queryTimeoutRowStart, queryTimeoutRowStart + 220)).toContain('v-if="!isPluginConnection"');
- });
-
- it("keeps the generic connect timeout radio visible for plugin connections", () => {
- // Deliberate scope cut: for providers without their own handshake timeout
- // field the connect radio is still effective, so it stays rendered.
- expect(dialogSource.slice(connectTimeoutRowStart, connectTimeoutRowStart + 220)).not.toContain('v-if="!isPluginConnection"');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
index e3fa3ef4b4..c2710e5adc 100644
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
@@ -1,37 +1,8 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { DEFAULT_CONNECT_TIMEOUT_SECS, normalizeConnectTimeoutSecs } from "@/lib/connection/timeoutLimits";
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
describe("ConnectionDialog timeout controls", () => {
- it("uses separate maximums for connection and query timeouts", () => {
- expect(dialogSource).toMatch(/v-model\.number="editGlobalConnectTimeoutSecs"[\s\S]*?min="1"[\s\S]*?:max="MAX_CONNECT_TIMEOUT_SECS"[\s\S]*?step="1"/);
- expect(dialogSource).toMatch(/v-model\.number="form\.connect_timeout_secs"[\s\S]*?min="1"[\s\S]*?:max="MAX_CONNECT_TIMEOUT_SECS"[\s\S]*?step="1"/);
- expect(dialogSource).toMatch(/v-model\.number="editGlobalQueryTimeoutSecs"[\s\S]*?min="0"[\s\S]*?:max="MAX_QUERY_TIMEOUT_SECS"[\s\S]*?step="1"/);
- expect(dialogSource).toMatch(/v-model\.number="form\.query_timeout_secs"[\s\S]*?min="0"[\s\S]*?:max="MAX_QUERY_TIMEOUT_SECS"[\s\S]*?step="1"/);
- expect(dialogSource).not.toContain('v-model.number="editGlobalQueryTimeoutSecs" type="number" min="0" max="300"');
- expect(dialogSource).not.toContain('v-model.number="form.query_timeout_secs" type="number" min="0" max="300"');
- expect(dialogSource).toContain("@input=\"clampQueryTimeoutInput($event, 'global')\"");
- expect(dialogSource).toContain("@input=\"clampQueryTimeoutInput($event, 'connection')\"");
- expect(dialogSource).toContain("@input=\"clampConnectTimeoutInput($event, 'global')\"");
- expect(dialogSource).toContain("@input=\"clampConnectTimeoutInput($event, 'connection')\"");
- expect(dialogSource).not.toContain('@blur="editGlobalQueryTimeoutSecs = normalizeGlobalQueryTimeoutSecs');
- });
-
it("restores the default when the connection timeout input is cleared", () => {
expect(normalizeConnectTimeoutSecs("")).toBe(DEFAULT_CONNECT_TIMEOUT_SECS);
- expect(dialogSource).toContain("normalizeConnectionTimeouts(config");
- expect(dialogSource).not.toContain("Number(config.connect_timeout_secs)");
- });
-
- it("uses button-backed help tooltips beside both global timeout labels", () => {
- const connectGlobalControl = dialogSource.slice(dialogSource.indexOf('id="connect-timeout-global"'), dialogSource.indexOf('id="connect-timeout-connection"'));
- const queryGlobalControl = dialogSource.slice(dialogSource.indexOf('id="query-timeout-global"'), dialogSource.indexOf('id="query-timeout-connection"'));
-
- expect(connectGlobalControl).toContain(`<HelpTooltip :label="t('connection.globalConnectTimeoutHint')"`);
- expect(queryGlobalControl).toContain(`<HelpTooltip :label="t('connection.globalQueryTimeoutHint')"`);
- expect(connectGlobalControl).not.toContain("<TooltipTrigger");
- expect(queryGlobalControl).not.toContain("<TooltipTrigger");
});
});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogXuguDatabase.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogXuguDatabase.spec.ts
deleted file mode 100644
index 9ba69bb196..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogXuguDatabase.spec.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
-describe("ConnectionDialog Xugu database requirement", () => {
- it("shows the existing required-database hint only for Xugu", () => {
- const placeholder = dialogSource.slice(dialogSource.indexOf("const databasePlaceholder = computed"), dialogSource.indexOf("const transportLayers"));
- expect(placeholder).toContain('if (form.value.db_type === "xugu") return t("connection.databasePlaceholderRequired")');
- expect(placeholder).toContain('if (form.value.db_type === "kingbase") return t("connection.databasePlaceholderRequired")');
- });
-
- it("validates Xugu's effective database before connection testing or saving", () => {
- const submit = dialogSource.slice(dialogSource.indexOf("function connectionConfigForSubmit"), dialogSource.indexOf("function ", dialogSource.indexOf("function connectionConfigForSubmit") + 10));
- expect(submit).toContain('if (config.db_type === "xugu")');
- expect(submit).toContain("hasXuguConnectionDatabase(config.database, config.connection_string)");
- expect(submit).toContain('throw new Error(t("connection.xuguDatabaseRequired"))');
- expect(submit).toContain('if (config.db_type === "kingbase")');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/etcdConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/etcdConnectionDialog.spec.ts
index e35148f25d..5e117a1240 100644
--- a/apps/desktop/src/lib/__tests__/connection/etcdConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/etcdConnectionDialog.spec.ts
@@ -1,35 +1,9 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-const browserSource = readFileSync(new URL("../../../components/etcd/EtcdKeyBrowser.vue", import.meta.url), "utf8");
-
describe("etcd connection dialog API versions", () => {
- it("offers v3 and v2 API profile switches", () => {
- expect(dialogSource).toContain("@click=\"switchEtcdApiVersion('etcd')\"");
- expect(dialogSource).toContain("@click=\"switchEtcdApiVersion('etcd-v2')\"");
- expect(dialogSource).toContain("v3 (etcd 3.x)");
- expect(dialogSource).toContain("v2 (etcd 2.x)");
- });
-
it("hydrates the v2 profile without exposing a second catalog entry", () => {
expect(CONNECTION_PROFILES["etcd-v2"]).toMatchObject({ type: "etcd", port: 2379 });
expect(CONNECTION_PICKER_OPTIONS.some((option) => option.value === "etcd-v2")).toBe(false);
});
});
-
-describe("etcd v2 feature trimming", () => {
- it("detects the v2 profile from the connection config", () => {
- expect(browserSource).toContain('connectionStore.getConfig(props.connectionId)?.driver_profile === "etcd-v2"');
- });
-
- it("hides key history for v2 connections", () => {
- expect(browserSource).toContain("history: isV2Api.value ? undefined : api.etcdHistory");
- });
-
- it("hides lease binding and the maintenance/lease workspaces for v2 connections", () => {
- expect(browserSource).toContain(':supports-lease-binding="!isV2Api && canManageEtcd"');
- expect(browserSource).toContain('<Button v-if="!isV2Api && canManageEtcd"');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/gbase8sConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/gbase8sConnectionDialog.spec.ts
index a8fca5d995..4eeb385536 100644
--- a/apps/desktop/src/lib/__tests__/connection/gbase8sConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/gbase8sConnectionDialog.spec.ts
@@ -34,10 +34,6 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
}
describe("GBase 8s connection dialog", () => {
- it("hydrates DBSERVERNAME when editing a saved connection", () => {
- expect(dialogSource).toContain('gbase_server: config.gbase_server || ""');
- });
-
it.each([
["gbase8a", "南大通用 GBase 8a"],
["gbase8s", "南大通用 GBase 8s"],
diff --git a/apps/desktop/src/lib/__tests__/connection/h2ConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/h2ConnectionDialog.spec.ts
index 22ac19e954..97737ca6c3 100644
--- a/apps/desktop/src/lib/__tests__/connection/h2ConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/h2ConnectionDialog.spec.ts
@@ -1,39 +1,7 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-
describe("H2 connection dialog driver profiles", () => {
- it("offers auto, bundled compatibility ranges, and a custom JAR fallback", () => {
- expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2')\"");
- expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v1')\"");
- expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v2')\"");
- expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v3')\"");
- expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-custom')\"");
- expect(dialogSource).toContain(">Custom JAR</Button>");
- });
-
- it("reuses the JDBC classpath picker only for the custom profile", () => {
- expect(dialogSource).toContain('const isH2CustomDriver = computed(() => form.value.db_type === "h2" && form.value.driver_profile === "h2-custom");');
- expect(dialogSource).toContain('<template v-if="isH2CustomDriver">');
- expect(dialogSource).toContain('v-model="jdbcDriverPathsInput"');
- expect(dialogSource).toContain('@click="browseJdbcDriverPaths"');
- expect(dialogSource).toContain('placeholder="org.h2.Driver"');
- });
-
- it("defaults the custom class and clears stale classpath data for bundled profiles", () => {
- const switchBlock = dialogSource.match(/function switchH2DriverProfile[\s\S]*?\n\}/)?.[0] ?? "";
- expect(switchBlock).toContain('form.value.jdbc_driver_class = form.value.jdbc_driver_class?.trim() || "org.h2.Driver";');
- expect(switchBlock).toContain("form.value.jdbc_driver_paths = [];");
- expect(switchBlock).toContain('jdbcDriverPathsInput.value = "";');
-
- const submitBlock = dialogSource.match(/if \(config\.db_type === "h2"\) \{[\s\S]*?const h2Mode/)?.[0] ?? "";
- expect(submitBlock).toContain('config.driver_profile === "h2-custom"');
- expect(submitBlock).toContain("config.jdbc_driver_paths = parsedJdbcDriverPaths();");
- expect(submitBlock).toContain("config.jdbc_driver_paths = [];");
- });
-
it("keeps legacy profile hydration without exposing a second H2 catalog entry", () => {
expect(CONNECTION_PROFILES["h2-legacy"]).toMatchObject({ type: "h2", port: 9092, user: "sa" });
expect(CONNECTION_PICKER_OPTIONS.find((option) => option.value === "h2")?.category).toBe("lightweight");
diff --git a/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts
deleted file mode 100644
index 371bfab2d9..0000000000
--- a/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { readFileSync } from "node:fs";
-import { parse } from "vue/compiler-sfc";
-import ts from "typescript";
-import { describe, expect, it } from "vitest";
-
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-const parsedDialog = parse(dialogSource, { filename: "ConnectionDialog.vue" });
-
-function findFunction(name: string): ts.FunctionDeclaration {
- const script = parsedDialog.descriptor.scriptSetup;
- expect(parsedDialog.errors).toEqual([]);
- expect(script).toBeDefined();
-
- const source = ts.createSourceFile("ConnectionDialog.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
- const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
- expect(declaration).toBeDefined();
- return declaration!;
-}
-
-describe("JDBCX connection dialog", () => {
- it("preserves the connection-level high-privilege extension opt-in on submit", () => {
- const submitConfig = findFunction("connectionConfigForSubmit").getText();
-
- expect(submitConfig).toContain('config.db_type === "jdbc" && config.driver_profile === JDBCX_DRIVER_PROFILE');
- expect(submitConfig).toContain("config.agent_java_options = undefined");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts
index 42888a039c..feb2d1dfab 100644
--- a/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts
@@ -4,139 +4,6 @@ import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("Nacos connection dialog layout", () => {
- it("presents implementation and version as one explicit connection profile", () => {
- expect(source).toContain("data-nacos-profile-selector");
- expect(source).toContain('v-for="profile in NACOS_CONNECTION_PROFILES"');
- expect(source).toContain("selectNacosConnectionProfile(profile.value)");
- expect(source).not.toContain("nacosVersionMode = 'auto'");
- expect(source).not.toContain("tryNacosDockerConsoleFallback");
- expect(source).not.toContain("dockerNacosConsoleFallbackUrl");
- });
-
- it("persists the explicit Nacos 3 Admin or Console API selection", () => {
- expect(source).toContain('const nacosApiPlane = ref<NacosApiPlane>("admin")');
- expect(source).toContain('config?.apiPlane || "admin"');
- expect(source).toContain('apiPlane: nacosImplementation.value === "nacos" && nacosVersionMode.value === "v3" ? nacosApiPlane.value : undefined');
- expect(source).toContain("nacos.nacosConsoleServiceAddressHint");
- });
-
- it("keeps the primary form focused on endpoints and authentication", () => {
- const mainStart = source.indexOf("data-nacos-profile-selector");
- const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);
- const main = source.slice(mainStart, mainEnd);
-
- expect(main).toContain("data-nacos-endpoint-section");
- expect(main).toContain("data-nacos-access-section");
- expect(main).toContain("data-nacos-advanced-hint");
- expect(main).toContain('t("nacos.nacosAdvancedHint")');
- expect(main).toContain("@click=\"configTab = 'advanced'\"");
- expect(main).toContain('v-model="nacosServerAddr"');
- expect(main).not.toContain('v-model="nacosConsoleUrl"');
- expect(main).not.toContain('v-model="nacosManagedNamespacesText"');
- expect(main).not.toContain("data-nacos-namespace-access-scope");
- expect(main).not.toContain("data-nacos-ordinary-user-toggle");
- expect(main).not.toContain("nacosOrdinaryAccount");
- expect(main).toContain("nacosAuthKind === 'usernamePassword'");
- expect(main).not.toContain('v-model="nacosNamespace"');
- expect(main).toContain('t("nacos.nacosAuthHint")');
- expect(main).not.toContain('v-model="nacosMetricsMode"');
- expect(main).not.toContain('v-model.number="nacosPageSize"');
- });
-
- it("moves low-frequency and r-nacos console settings to the advanced tab", () => {
- const advancedStart = source.indexOf("data-nacos-advanced-settings");
- const advancedEnd = source.indexOf('v-if="showGaussdbConnectionMode"', advancedStart);
- const advanced = source.slice(advancedStart, advancedEnd);
-
- expect(advanced).not.toContain('v-model="nacosContextPathInput"');
- expect(advanced).not.toContain("配置上下文路径");
- expect(advanced).toContain('v-model="nacosContextPath"');
- expect(advanced).toContain('t("nacos.nacosContextPathHint")');
- expect(advanced).toContain('v-model="nacosMetricsMode"');
- expect(advanced).toContain('v-model="nacosConsoleUrl"');
- expect(advanced).toContain('t("connection.nacosWebConsoleUrlHint")');
- expect(advanced).toContain('v-if="isNacosV3AdminPlane"');
- expect(advanced).toContain('v-model="nacosRNacosConsoleAddr"');
- expect(advanced).toContain('v-if="nacosRNacosConsoleAddr.trim()"');
- expect(advanced).toContain('v-model="nacosHistoryEnabled"');
- expect(advanced).toContain('v-model="nacosTlsSkipVerify"');
- expect(advanced).toContain('v-model.number="nacosPageSize"');
- });
-
- it("documents product default ports instead of local Docker mappings", () => {
- expect(source).toContain('t("nacos.nacosServiceAddressHint")');
- expect(source).toContain('t("nacos.nacosMetricsHint")');
- expect(source).not.toContain("DBX 不需要配置该地址");
- const mainStart = source.indexOf("data-nacos-profile-selector");
- const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);
- expect(source.slice(mainStart, mainEnd)).not.toContain("data-nacos-managed-namespaces");
- expect(source.slice(mainStart, mainEnd)).not.toContain('placeholder="http://127.0.0.1:8080"');
- expect(source).toContain('return "http://127.0.0.1:8080";');
- expect(source).not.toContain("http://127.0.0.1:8010");
- expect(source).not.toContain("http://127.0.0.1:8818");
- });
-
- it("uses a dedicated namespace selector instead of the database selector", () => {
- expect(source).toContain("t(nacosNamespacePickerTitleKey)");
- expect(source).toContain('"nacos.nacosDetectAccessibleNamespaces"');
- expect(source).toContain("openVisibleNacosNamespacesPicker");
- expect(source).toContain("loadReadableNacosNamespaces(draftId, api)");
- expect(source).toContain("showVisibleNacosNamespacesDialog");
- expect(source).toContain('v-model="visibleNacosNamespaceAccessMode"');
- expect(source).toContain('TabsTrigger value="automatic"');
- expect(source).toContain('TabsTrigger v-if="canDetectNacosNamespaceAccess" value="manual"');
- expect(source).toContain('v-model="nacosManagedNamespacesText"');
- expect(source).not.toContain("!isNacosV3AdminPlane.value");
- expect(source).toContain('visibleNacosNamespaceAccessMode.value === "manual"');
- });
-
- it("guides namespace listing permission failures to manual scope entry", () => {
- expect(source).toContain("function isNacosNamespaceListingPermissionError(error: unknown): boolean");
- expect(source).toContain("NACOS_ERROR\\[rnacosNamespaceDirectoryUnavailable\\]");
- expect(source).toContain("NACOS_ERROR\\[(?:v3ManagedNamespacesRequired|managedNamespacesRequired)\\]");
- expect(source).toContain("/\\/v3\\/(?:admin|console)\\/core\\/namespace\\/list/");
- expect(source).toContain("visibleNacosNamespaceListingPermissionDenied.value = isNacosNamespaceListingPermissionError(e)");
- expect(source).toContain('t("nacos.nacosManagedNamespacesRequired")');
- expect(source).toContain('v-else-if="visibleNacosNamespaceListingPermissionDenied"');
- expect(source).toContain("@click=\"visibleNacosNamespaceAccessMode = 'manual'\"");
- });
-
- it("resolves unique manually entered namespace names to their Nacos IDs", () => {
- expect(source).toContain("function normalizeManualNacosNamespaceNames(namespaces: string[], availableNamespaces: NacosNamespaceInfo[]): string[]");
- expect(source).toContain("matchingNames.length === 1 ? matchingNames[0] : namespace");
- expect(source).toContain("async function resolveManualNacosNamespaceNames(namespaces: string[]): Promise<string[]>");
- expect(source).toContain("managedNamespaces: undefined");
- expect(source).toContain(": await resolveManualNacosNamespaceNames(manualNamespaces)");
- });
-
- it("distinguishes the manual namespace input for the V3 Admin and Console API planes", () => {
- expect(source).toContain("const isNacosV3ConsolePlane = computed(");
- expect(source).toContain('isNacosV3AdminPlane.value ? "nacos.nacosManagedNamespaces" : "nacos.nacosManagedNamespacesNameOrId"');
- expect(source).toContain('isNacosV3AdminPlane.value ? "nacos.nacosManagedNamespacesIdPlaceholder" : "nacos.nacosManagedNamespacesPlaceholder"');
- expect(source).toContain('if (isNacosV3AdminPlane.value) return "nacos.nacosV3AdminManagedNamespacesHint"');
- expect(source).toContain('if (isNacosV3ConsolePlane.value) return "nacos.nacosV3ConsoleManagedNamespacesHint"');
- expect(source).toContain('v-if="isNacosV3AdminPlane" class="flex gap-2 rounded-md border border-amber-500/30');
- expect(source).toContain('isNacosV3AdminPlane.value || nacosImplementation.value === "rnacos"');
- expect(source).toContain("? manualNamespaces");
- expect(source).toContain(": await resolveManualNacosNamespaceNames(manualNamespaces)");
- });
-
- it("opens namespace access setup instead of showing a save validation error", () => {
- expect(source).toContain("if (!hasNacosNamespaceScopeForSave()) {");
- expect(source).toContain("await openVisibleNacosNamespacesPicker();");
- expect(source).not.toContain('message: t("nacos.nacosNamespaceScopeRequiredBeforeSave")');
- });
-
- it("stores automatic full access as a dynamic namespace scope", () => {
- expect(source).toContain("const nacosDynamicAllNamespaces = ref(false)");
- expect(source).toContain("const useDynamicAll = selectsEntireReadableList && visibleNacosNamespaceDynamicAllSupported.value");
- expect(source).toContain("const readableSet = new Set(readableIds.map(nacosNamespaceIdentity))");
- expect(source).toContain("readableSet.size === sidebarSet.size");
- expect(source).toContain("form.value.visible_databases = useDynamicAll ? undefined : selected");
- expect(source).toContain("nacosDynamicAllNamespaces.value = useDynamicAll");
- expect(source).toContain("function showAllVisibleNacosNamespaces()");
- });
-
it("uses namespaces when scoping Nacos production safeguards", () => {
expect(source).toContain('form.value.db_type === "nacos"');
expect(source).toContain("production.allNamespaces");
diff --git a/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
index c1342aa344..0716268b49 100644
--- a/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
@@ -1,62 +1,9 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
-const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-const fieldsSource = readFileSync(new URL("../../../components/connection/SpannerConnectionFields.vue", import.meta.url), "utf8");
-
describe("Cloud Spanner connection dialog", () => {
it("registers the bundled agent profile in the SQL category", () => {
expect(CONNECTION_PROFILES.spanner).toMatchObject({ type: "spanner", port: 443, user: "", label: "Cloud Spanner", icon: "spanner" });
expect(CONNECTION_PICKER_OPTIONS.find((option) => option.value === "spanner")).toEqual({ value: "spanner", label: "Cloud Spanner", category: "sql" });
});
-
- it("does not expose external JDBC driver configuration because the driver is bundled", () => {
- const nativeAgentDriverSupport = dialogSource.match(/function supportsNativeAgentJdbcDriverConfigType\(dbType: DatabaseType\): boolean \{([\s\S]*?)\}/)?.[1] ?? "";
- const jdbcBackedDatabaseTypes = dialogSource.match(/const jdbcBackedDatabaseTypes = new Set<DatabaseType>\(\[([\s\S]*?)\]\);/)?.[1] ?? "";
-
- expect(nativeAgentDriverSupport).toContain('dbType === "bigquery"');
- expect(nativeAgentDriverSupport).not.toContain('dbType === "spanner"');
- expect(jdbcBackedDatabaseTypes).not.toContain('"spanner"');
- });
-
- it("collects the resource path through dedicated fields instead of host and credentials", () => {
- expect(dialogSource).toContain('import SpannerConnectionFields from "@/components/connection/SpannerConnectionFields.vue";');
- expect(dialogSource).toContain('<SpannerConnectionFields v-model:database="form.database" @change="resetTestState" />');
- // User, password, and the generic database row are hidden for Spanner.
- // These pin the whole v-if because the rows are shared, so adding another
- // database that opts out of one of them means updating the string here too.
- expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
- expect(dialogSource).toContain('<div v-if="form.db_type !== \'spanner\'" class="grid grid-cols-4 items-center gap-4">');
- expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'solr' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
- // Switching to the Spanner profile clears host and credentials.
- expect(dialogSource).toContain('if (profile.type === "spanner") {');
- // Save/Test gating and submit-time normalization.
- expect(dialogSource).toContain("if (isSpannerConnection(form.value)) return hasSpannerResourcePath(form.value);");
- expect(dialogSource).toContain("normalizeSpannerConnection(config);");
- expect(dialogSource).toContain('throw new Error(t("connection.spannerFieldsRequired"));');
- });
-
- it("stays inside the generic branch so the agent install hint and URL params remain available", () => {
- const spannerBlockStart = dialogSource.indexOf("<!-- Cloud Spanner: project/instance/database resource path instead of user/password/database -->");
- const genericBranchStart = dialogSource.indexOf("<!-- MySQL / PostgreSQL: host, port, user, password, database -->");
- const urlParamsRow = dialogSource.indexOf('v-if="supportsGenericUrlParams"');
- const agentInstallHint = dialogSource.indexOf('v-if="shouldShowAgentDriverInstallHint"');
-
- expect(genericBranchStart).toBeGreaterThan(0);
- expect(spannerBlockStart).toBeGreaterThan(genericBranchStart);
- expect(urlParamsRow).toBeGreaterThan(spannerBlockStart);
- expect(agentInstallHint).toBeGreaterThan(spannerBlockStart);
- expect(dialogSource).toContain("'credentials=/path/key.json;autocommit=true'");
- });
-
- it("offers both the structured editor and the raw resource path editor", () => {
- expect(fieldsSource).toContain('const database = defineModel<string | undefined>("database");');
- expect(fieldsSource).toContain("data-spanner-resource-fields");
- expect(fieldsSource).toContain('t("connection.spannerProject")');
- expect(fieldsSource).toContain('t("connection.spannerInstance")');
- expect(fieldsSource).toContain('t("connection.spannerDatabase")');
- expect(fieldsSource).toContain('t("connection.spannerResourcePathMode")');
- expect(fieldsSource).toContain('emit("change")');
- });
});
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/cellDetailPresentation.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/cellDetailPresentation.spec.ts
index 88d7ef7854..5542255dd2 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/cellDetailPresentation.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/cellDetailPresentation.spec.ts
@@ -1,18 +1,10 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { compactJsonText, valueEditorActions } from "@/lib/dataGrid/cellDetailPresentation";
-const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
-
describe("cellDetailPresentation", () => {
it("offers compact JSON beside format JSON for editable JSON values", () => {
expect(valueEditorActions({ canSetNull: true, canFormatJson: true })).toEqual(["formatJson", "compactJson", "setNull", "restoreOriginal"]);
expect(valueEditorActions({ canSetNull: false, canFormatJson: false })).toEqual(["restoreOriginal"]);
expect(compactJsonText('{\n "name": "DBX",\n "enabled": true\n}')).toBe('{"name":"DBX","enabled":true}');
});
-
- it("wires the value editor compact action to the existing compact handler", () => {
- expect(dataGridSource).toContain("activeValueEditorActions.includes('compactJson')");
- expect(dataGridSource).toContain('@click="compactDetailJson"');
- });
});
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/customBasemap.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/customBasemap.spec.ts
index cf48b462d3..fea6b3f40f 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/customBasemap.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/customBasemap.spec.ts
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
-import { readFileSync } from "node:fs";
import { escapeCustomBasemapAttribution, loadCustomBasemapConfig, loadSelectedBasemapId, normalizeCustomBasemapConfig, resolveSelectedBasemapId, saveCustomBasemapConfig, saveSelectedBasemapId } from "@/lib/dataGrid/customBasemap";
-const layerPreviewSource = readFileSync(new URL("../../../components/grid/LayerPreviewDialog.vue", import.meta.url), "utf8");
-
function storage() {
const values = new Map<string, string>();
return {
@@ -13,12 +10,6 @@ function storage() {
}
describe("custom basemap configuration", () => {
- it("keeps a saved custom basemap available after switching to a built-in basemap", () => {
- expect(layerPreviewSource).toMatch(/<option v-if="customBasemapConfig" value="custom">/);
- expect(layerPreviewSource).toMatch(/id === "custom" && customBasemapConfig\.value/);
- expect(layerPreviewSource).toMatch(/v-model="customBasemapName"/);
- });
-
it("normalizes a valid XYZ configuration", () => {
expect(
normalizeCustomBasemapConfig({
@@ -57,7 +48,6 @@ describe("custom basemap configuration", () => {
expect(escaped).toBe("&lt;img src=x onerror=&quot;alert(1)&quot;&gt;&lt;svg onload=&#39;alert(2)&#39;&gt;&lt;script&gt;alert(3)&lt;/script&gt;&amp;");
expect(escaped).not.toMatch(/<(?:img|svg|script)\b/i);
- expect(layerPreviewSource).toMatch(/basemap\.custom \? escapeCustomBasemapAttribution\(basemap\.attribution\) : basemap\.attribution/);
});
it("persists the actual basemap selection separately from the custom configuration", () => {
@@ -67,7 +57,6 @@ describe("custom basemap configuration", () => {
expect(saveSelectedBasemapId(target, "osm")).toBe(true);
expect(loadSelectedBasemapId(target)).toBe("osm");
- expect(layerPreviewSource).toMatch(/saveSelectedBasemapId\(basemapStorage, basemap\.id\)/);
});
it("does not enable a stored custom basemap unless it was selected", () => {
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellTypeVisual.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellTypeVisual.spec.ts
index a29bd89091..c0ecc198f1 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellTypeVisual.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellTypeVisual.spec.ts
@@ -1,11 +1,7 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveDataGridCellTextRole } from "@/lib/dataGrid/dataGridCellTextVisual";
import { resolveDataGridTypeVisualKind, resolveHeaderColumnType, type DataGridTypeVisualKind } from "@/lib/dataGrid/dataGridColumnType";
-const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
-const globalStylesSource = readFileSync(new URL("../../../styles/globals.css", import.meta.url), "utf8");
-
describe("data grid type visual kind", () => {
it.each<[string, DataGridTypeVisualKind]>([
["BIGINT", "integer"],
@@ -75,8 +71,6 @@ describe("data grid header type color", () => {
expect(displayedType).toBe("decimal(10,2)");
expect(resolveDataGridTypeVisualKind(displayedType)).toBe("numeric");
- expect(dataGridSource).toContain(':type-class="typeColorClass(headerColumnType(col.name, col.actualColIdx))"');
- expect(dataGridSource).not.toContain("typeColorClass(allColumnTypes[col.actualColIdx]");
});
});
@@ -101,24 +95,4 @@ describe("data grid cell text visual priority", () => {
it("keeps NULL muted when type colors are disabled", () => {
expect(resolveDataGridCellTextRole({ ...ordinaryInteger, colorizeTypes: false, isNull: true })).toBe("muted");
});
-
- it("uses a neutral foreground on editable DOM hover surfaces", () => {
- expect(dataGridSource).toContain("'hover:bg-gray-200 hover:text-foreground dark:hover:bg-gray-800':");
- expect(dataGridSource).toContain("'cursor-text hover:bg-gray-200 hover:text-foreground dark:hover:bg-gray-800':");
- });
-
- it("checks NULL before applying the optional type-color setting", () => {
- expect(dataGridSource).toContain("function gridCellTextColorClass(item: RowItem, actualColIdx: number, visibleColIdx: number): string {\n const value = item.data[actualColIdx];");
- expect(dataGridSource).toContain("function transposeCellTextColorClass(recordIndex: number, actualColIdx: number): string {\n const item = displayItems.value[recordIndex];");
- expect(dataGridSource).not.toContain('function gridCellTextColorClass(item: RowItem, actualColIdx: number, visibleColIdx: number): string {\n if (!colorizeDataGridCellTypes.value) return "text-foreground";');
- expect(dataGridSource).not.toContain('function transposeCellTextColorClass(recordIndex: number, actualColIdx: number): string {\n if (!colorizeDataGridCellTypes.value) return "text-foreground";');
- });
-
- it("places data-grid type selectors in the components layer", () => {
- const componentsLayerStart = globalStylesSource.indexOf("@layer components {");
- const integerTypeSelector = globalStylesSource.indexOf(".data-grid-type-integer");
-
- expect(componentsLayerStart).toBeGreaterThan(-1);
- expect(integerTypeSelector).toBeGreaterThan(componentsLayerStart);
- });
});
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridContextMenuState.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridContextMenuState.spec.ts
deleted file mode 100644
index fd28d8dbac..0000000000
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridContextMenuState.spec.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
-
-describe("DataGrid context menu state", () => {
- it("clears the context target whenever the result is replaced", () => {
- expect(dataGridSource).toMatch(/watch\(\s*\(\) => props\.result,[\s\S]*?clearRowSelection\(\);\s*invalidateContextMenuTarget\(\);[\s\S]*?exitTransaction\(\);/);
- });
-
- it("uses the actual copyable row count in the copy menu", () => {
- expect(dataGridSource).toContain('label: copyRowCount.value > 1 ? t("grid.copyRows", { count: copyRowCount.value }) : t("grid.copyRow")');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
index 9cfe33cf8d..6cb0905ac4 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, normalizeDataGridCopyPreference, normalizeDataGridExtractorOptions, resolveDataGridCopyPreference, validateDataGridExtractorOptions } from "@/lib/dataGrid/dataGridCopyExtractor";
@@ -37,14 +36,6 @@ describe("data-grid extractor options", () => {
expect(normalizeDataGridExtractorOptions({ json: { camelCaseFieldNames: "true" } }).json.camelCaseFieldNames).toBe(false);
});
- it("exposes the camel-case field-name switch only with JSON extractor options", () => {
- const dialog = readFileSync(new URL("../../../components/grid/DataGridExtractorDialog.vue", import.meta.url), "utf8");
-
- expect(dialog).toContain('v-if="isJson"');
- expect(dialog).toContain("draftOptions.json.camelCaseFieldNames");
- expect(dialog).toContain('t("grid.copyExtractorCamelCaseJsonFields")');
- });
-
it("rejects overlapping effective row and column separators", () => {
const options = normalizeDataGridExtractorOptions(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS);
options.dsv.rowSeparator = ",";
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridPaintTheme.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridPaintTheme.spec.ts
index b9730f98ef..7c63d78f7f 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridPaintTheme.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridPaintTheme.spec.ts
@@ -1,5 +1,4 @@
import { describe, expect, it } from "vitest";
-import { readFileSync } from "node:fs";
import {
DATA_GRID_DARK_ACTIVE_ROW_BG,
DATA_GRID_DARK_CROSSHAIR_COL_BG,
@@ -104,16 +103,6 @@ describe("data grid paint theme", () => {
expect(theme.cellCrosshairCol).toBe("rgb(153, 187, 177)");
});
- it("propagates crosshair fills through the base cell variable so DOM and frozen cells stay visible", () => {
- const gridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
-
- expect(gridSource).toMatch(/\.crosshair-row\s*\{\s*--data-grid-cell-bg:\s*var\(--data-grid-cell-crosshair-row-bg\)\s*!important;/);
- expect(gridSource).toMatch(/\.crosshair-column\s*\{\s*--data-grid-cell-bg:\s*var\(--data-grid-cell-crosshair-col-bg\)\s*!important;/);
- expect(gridSource).toContain("color-mix(in srgb, var(--primary) 34%, var(--background))");
- expect(gridSource).toContain("color-mix(in srgb, var(--primary) 50%, var(--background))");
- expect(gridSource).toMatch(/\.data-grid-cell--frozen\s*\{\s*background-color:\s*var\(--data-grid-cell-bg,/);
- });
-
it("falls back to the built-in type palette for the active appearance", () => {
const emptyCssVariable = () => "";
@@ -245,16 +234,3 @@ describe("data grid paint theme", () => {
expect(theme.typeForegrounds.spatial).toBe("rgb(12, 98, 74)");
});
});
-
-describe("dbx-control-chrome cascade contract", () => {
- it("keeps chrome defaults layered and low-specificity so invalid/focus utilities can win", () => {
- const css = readFileSync(new URL("../../../styles/globals.css", import.meta.url), "utf8");
- const chromeBlockStart = css.indexOf("Shared control chrome defaults");
- expect(chromeBlockStart).toBeGreaterThanOrEqual(0);
- const chromeSlice = css.slice(chromeBlockStart - 40, chromeBlockStart + 1600);
- expect(chromeSlice).toMatch(/@layer components/);
- expect(chromeSlice).toMatch(/:where\(\.dbx-control-chrome\)/);
- expect(chromeSlice).toMatch(/\[aria-invalid="true"\]/);
- expect(chromeSlice).not.toMatch(/box-shadow:\s*none/);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridRuntime.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridRuntime.spec.ts
index 225b322c75..f0880839ff 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridRuntime.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridRuntime.spec.ts
@@ -3,37 +3,7 @@ import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createDataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";
-const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
-
-function extractFunction(name: string): string {
- const start = dataGridSource.indexOf(`async function ${name}(`);
- if (start < 0) throw new Error(`Missing DataGrid function: ${name}`);
- const bodyStart = dataGridSource.indexOf("{", start);
- let depth = 0;
- for (let index = bodyStart; index < dataGridSource.length; index++) {
- const character = dataGridSource[index];
- if (character === "{") depth++;
- if (character === "}" && --depth === 0) return dataGridSource.slice(start, index + 1);
- }
- throw new Error(`Unterminated DataGrid function: ${name}`);
-}
-
describe("dataGridRuntime", () => {
- it("keeps WHERE and ORDER BY execution errors separate from save errors", () => {
- for (const name of ["applyWhereFilter", "applyOrderBySearch"]) {
- const source = extractFunction(name);
- expect(source).toContain('queryControlError.value = ""');
- expect(source).toContain("queryControlError.value = String(e?.message || e)");
- expect(source).not.toContain("saveError.value");
- }
- expect(dataGridSource).toContain('v-if="queryControlError"');
- expect(dataGridSource).toContain(":title=\"t('grid.queryError')\"");
- });
-
- it("redraws canvas rows when multiline flattening changes", () => {
- expect(dataGridSource).toContain("watch(flatteningMultiLineEnabled, () => scheduleCanvasDraw());");
- });
-
it("disposes registered resources in reverse order and only once", () => {
const scope = createDataGridRuntimeScope();
const calls: string[] = [];
diff --git a/apps/desktop/src/lib/__tests__/editor/editorSearchSelection.spec.ts b/apps/desktop/src/lib/__tests__/editor/editorSearchSelection.spec.ts
index 8653b6d845..fced19f2b5 100644
--- a/apps/desktop/src/lib/__tests__/editor/editorSearchSelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/editorSearchSelection.spec.ts
@@ -1,12 +1,7 @@
-import { readFileSync } from "node:fs";
import { EditorSelection } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { appendSearchMatchSelection, findSearchMatch, isSearchAddSelectionModifier, selectionRangesForSearchMatches } from "@/lib/editor/editorSearchSelection";
-const searchPanelSource = readFileSync(new URL("../../../components/editor/EditorSearchPanel.vue", import.meta.url), "utf8");
-const ddlViewSource = readFileSync(new URL("../../../components/objects/DdlViewDialog.vue", import.meta.url), "utf8");
-const nacosSource = readFileSync(new URL("../../../components/nacos/NacosAdminConsole.vue", import.meta.url), "utf8");
-
const matches = [
{ from: 0, to: 3 },
{ from: 6, to: 9 },
@@ -76,22 +71,4 @@ describe("editorSearchSelection", () => {
expect(isSearchAddSelectionModifier({ metaKey: true }, "Win32")).toBe(false);
expect(isSearchAddSelectionModifier({ ctrlKey: true }, "Linux x86_64")).toBe(true);
});
-
- it("wires select-all and platform-modifier-click match selection into the search panel", () => {
- expect(searchPanelSource).toContain("selectionRangesForSearchMatches");
- expect(searchPanelSource).toContain("appendSearchMatchSelection");
- expect(searchPanelSource).toContain("isSearchAddSelectionModifier(event)");
- expect(searchPanelSource).toContain('@click="selectAllMatches"');
- expect(searchPanelSource).toContain("editor.search.selectAll");
- expect(searchPanelSource).toContain("collectAllMatches(v, limit + 1)");
- expect(searchPanelSource).toContain("matches.slice(0, limit)");
- expect(searchPanelSource).toContain("countEditorSearchMatches");
- expect(searchPanelSource).toContain("editor.search.selectionLimitSummary");
- expect(searchPanelSource).not.toContain("matchCountLimited");
- });
-
- it("enables multiple selections in every editor using the shared panel", () => {
- expect(ddlViewSource).toContain("EditorState.allowMultipleSelections.of(true)");
- expect(nacosSource).toContain("EditorState.allowMultipleSelections.of(true)");
- });
});
diff --git a/apps/desktop/src/lib/__tests__/editor/editorZoom.spec.ts b/apps/desktop/src/lib/__tests__/editor/editorZoom.spec.ts
index e151a6b5a4..a815a91b52 100644
--- a/apps/desktop/src/lib/__tests__/editor/editorZoom.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/editorZoom.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { createEditorWheelZoomGestureGuard } from "@/lib/editor/editorZoom";
@@ -44,16 +43,3 @@ describe("createEditorWheelZoomGestureGuard", () => {
expect(guard.accepts(wheelEvent(120, true))).toBe(true);
});
});
-
-describe("editor wheel zoom integration", () => {
- it.each([
- ["SQL editor", "../../../components/editor/QueryEditor.vue", "wheelZoomGestureGuard"],
- ["cell detail editor", "../../../composables/useCellDetailEditor.ts", "wheelZoomGestureGuard"],
- ["Nacos editor", "../../../components/nacos/NacosAdminConsole.vue", "configEditorWheelZoomGestureGuard"],
- ])("guards %s wheel zoom by gesture origin", (_name, path, guardName) => {
- const source = readFileSync(new URL(path, import.meta.url), "utf8");
-
- expect(source).toContain("createEditorWheelZoomGestureGuard");
- expect(source).toContain(`if (!${guardName}.accepts(event)) return false;`);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorBlockComment.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorBlockComment.spec.ts
index 4cc9dbae5b..91287abc8c 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorBlockComment.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorBlockComment.spec.ts
@@ -1,15 +1,8 @@
-import { readFileSync } from "node:fs";
import { toggleBlockComment } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorSelection, EditorState, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
-const contextMenuSource = readFileSync(new URL("../../../components/editor/QueryEditorContextMenu.vue", import.meta.url), "utf8");
-
-const runtimeSource = readFileSync(new URL("../../../components/editor/queryEditorCodeMirrorRuntime.ts", import.meta.url), "utf8");
-
function runToggleBlockComment(doc: string, selection: EditorSelection | { anchor: number; head?: number }) {
let state = EditorState.create({ doc, selection, extensions: [sql()] });
const dispatch = vi.fn((transaction: Transaction) => {
@@ -26,19 +19,6 @@ function runToggleBlockComment(doc: string, selection: EditorSelection | { ancho
}
describe("QueryEditor block comment", () => {
- it("wires toggleBlockComment into the right-click context menu, the keymap, and the editor module load", () => {
- expect(runtimeSource).toContain('codeMirrorToggleBlockComment: typeof import("@codemirror/commands").toggleBlockComment | null;');
- expect(runtimeSource).toContain("codeMirrorToggleBlockComment: null,");
- expect(queryEditorSource).toContain("codeMirrorToggleBlockComment?.(currentView);");
- expect(contextMenuSource).toContain('label: t("editor.contextMenu.blockCommentSelection")');
- expect(contextMenuSource).toContain("shortcut: shortcuts.toggleBlockComment");
- expect(queryEditorSource).toContain("...binding(shortcuts.toggleBlockComment, (view) => {");
- expect(queryEditorSource).toContain("!supportsQueryEditorBlockComments(props.databaseType)");
- expect(queryEditorSource).toContain("defaultKeymapForGlobalShortcuts(codeMirrorRuntime.codeMirrorDefaultKeymap, settingsStore.editorSettings.shortcuts).filter((item) => item.run !== codeMirrorRuntime.codeMirrorToggleBlockComment)");
- expect(queryEditorSource).toContain("defaultKeymapComp.reconfigure(defaultKeymapExtension())");
- expect(runtimeSource).toContain("runtime.codeMirrorToggleBlockComment = toggleBlockComment;");
- });
-
it("wraps the selected SQL in a block comment", () => {
const doc = "SELECT id FROM users;";
const selection = EditorSelection.range(doc.indexOf("id"), doc.indexOf("id") + "id".length);
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionKeymap.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionKeymap.spec.ts
index c90b404644..e3eeb63a2c 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionKeymap.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionKeymap.spec.ts
@@ -188,9 +188,6 @@ afterEach(() => {
});
describe("QueryEditor completion Tab keymap", () => {
- it("guards the batch INSERT snippet factory before applying", () => {
- expect(batchSource).toContain('if (session.mode === "insert" && !runtime.codeMirrorSnippetCompletion)');
- });
it("closes completion and suppresses its restart for the Enter newline", () => {
const closeCompletion = vi.fn(() => true);
let harness: TabHarness;
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionSelection.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionSelection.spec.ts
index 7f7848eb44..45f7e1a380 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionSelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorCompletionSelection.spec.ts
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { acceptCompletion, autocompletion, completionStatus, currentCompletions, moveCompletionSelection, selectedCompletionIndex, startCompletion } from "@codemirror/autocomplete";
import { EditorState, Prec, Transaction } from "@codemirror/state";
import { insertNewlineKeepIndent } from "@codemirror/commands";
@@ -9,8 +7,6 @@ import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { describe, expect, it, vi } from "vitest";
import { acceptSelectedCompletionWithRetry, acceptSelectedOrFirstCompletion } from "@/lib/editor/queryEditorCompletionAcceptance";
-const queryEditorSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/editor/queryEditorSqlExtensions.ts"), "utf8");
-
function createCompletionView(doc = "", selectFirstCompletionOnOpen = false, interactionDelay: number | null = 0) {
return new EditorView({
parent: document.createElement("div"),
@@ -67,10 +63,6 @@ async function expectCompletionOpenWithoutSelection(view: EditorView) {
}
describe("QueryEditor completion selection", () => {
- it("binds SQL completion to CodeMirror's unselected-on-open mode", () => {
- expect(queryEditorSource).toMatch(/selectOnOpen: settingsStore\.editorSettings\.selectFirstCompletionOnOpen/);
- });
-
it("opens manual completion unselected and accepts the first option with Tab", async () => {
const view = createCompletionView();
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorDatabaseNameCompletion.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorDatabaseNameCompletion.spec.ts
deleted file mode 100644
index 8c54b9a403..0000000000
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorDatabaseNameCompletion.spec.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
-const diagnosticsSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
-
-const completionSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletion.ts", import.meta.url), "utf8");
-const metadataSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
-
-function extractFunction(name: string): string {
- const source = [queryEditorSource, completionSource, metadataSource, diagnosticsSource].find((candidate) => candidate.includes(`function ${name}(`)) ?? "";
- const start = source.indexOf(`function ${name}(`);
- if (start < 0) throw new Error(`Missing QueryEditor function: ${name}`);
- const bodyStart = source.indexOf("{", start);
- let depth = 0;
- for (let index = bodyStart; index < source.length; index++) {
- const character = source[index];
- if (character === "{") depth++;
- if (character === "}" && --depth === 0) return source.slice(start, index + 1);
- }
- throw new Error(`Unterminated QueryEditor function: ${name}`);
-}
-
-describe("QueryEditor database name completion wiring", () => {
- it("uses the shared capability for local lookup, background refresh, and async loading", () => {
- expect(extractFunction("localCompletionDatabaseNames")).toContain("supportsDatabaseNameCompletion(props.databaseType)");
- expect(extractFunction("scheduleCompletionMetadataRefresh")).toMatch(/supportsDatabaseNameCompletion\(props\.databaseType\)[\s\S]*?refreshCompletionDatabases\(connectionId\)/);
- expect(extractFunction("performAsyncCompletionWithResult")).toMatch(/supportsDatabaseNameCompletion\(props\.databaseType\)[\s\S]*?listCompletionDatabases\(props\.connectionId!\)/);
- });
-
- it("does not reuse cached tables while completing schemas inside a database", () => {
- expect(extractFunction("buildLocalSqlCompletionResult")).toMatch(/const tables = schemaLookupDatabase\s*\?\s*\[\]/);
- expect(extractFunction("performAsyncCompletionWithResult")).toMatch(/let tables = schemaLookupDatabase\s*\?\s*\[\]/);
- });
-
- it("limits database and schema disambiguation to engines with both capabilities", () => {
- const guard = extractFunction("mayCompleteDatabaseSchemaQualifier");
-
- expect(guard).toContain("supportsDatabaseNameCompletion(props.databaseType)");
- expect(guard).toContain("supportsDatabaseSchemaQualifierCompletion()");
- });
-
- it("uses the resolved database scope for routine completion and isolates the editor cache", () => {
- expect(extractFunction("routineCompletionTargetForContext")).toContain("currentDatabase: scope.database");
- expect(extractFunction("routineCompletionTargetForContext")).toContain("supportsDatabaseSchemaQualifier: supportsDatabaseSchemaQualifierCompletion()");
- expect(extractFunction("lookupLocalCompletionObjectsForContext")).toContain("target.database");
- expect(extractFunction("listCompletionObjectsForContext")).toContain("target.database");
- expect(extractFunction("routineCompletionScopeForContext")).toContain("database: target.database");
- expect(extractFunction("completionObjectScopeKey")).toContain("scope.database");
- expect(extractFunction("completionObjectScopeKey")).toContain("scope.schema");
- expect(metadataSource).toContain("cachedCompletionObjectsByScope");
- });
-
- it("loads SQL Server capability metadata before offering or applying USE completion", () => {
- const provider = extractFunction("provideSqlCompletions");
-
- expect(provider).toContain("getSqlServerCompletionContext");
- expect(provider).toContain("supports_session_database_switch");
- expect(provider).toContain("useDatabaseDefaultSchema");
- });
-
- it("scopes SQL Server semantic metadata to the database selected by a preceding USE", () => {
- const scope = extractFunction("semanticDiagnosticMetadataScope");
- expect(scope).toContain("sqlServerUseDatabaseBeforeCursor(sql, range.from)");
- expect(scope).toContain("lookupLocalCompletionDatabases");
- expect(diagnosticsSource).toMatch(/async function refreshSemanticDiagnostics[\s\S]*?semanticDiagnosticTablesForScope\(semanticAnalysis\.tables, metadataScope\)/);
- expect(diagnosticsSource).toContain("enrichSemanticDiagnosticTables(scopedAnalysis.tables, metadataScope)");
- expect(diagnosticsSource).toContain("ensureColumnsForSemanticDiagnostics(tables, metadataScope)");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorDiagnosticCaretAnchor.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorDiagnosticCaretAnchor.spec.ts
index a5b9533663..65d6bb1fe4 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorDiagnosticCaretAnchor.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorDiagnosticCaretAnchor.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { needsDiagnosticCaretReanchor, type DiagnosticCaretAnchorState } from "@/lib/editor/queryEditorDiagnosticCaretAnchor";
@@ -47,14 +46,3 @@ describe("needsDiagnosticCaretReanchor", () => {
expect(needsDiagnosticCaretReanchor(state({ domRangeCount: 0, currentAnchorNode: null }))).toBe(false);
});
});
-
-describe("QueryEditor diagnostic caret re-anchor wiring", () => {
- const queryEditorSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
-
- it("re-anchors the browser caret after applying diagnostics, outside a transaction", () => {
- expect(queryEditorSource).toMatch(/function reconfigureDiagnostics\(\)[\s\S]*?reanchorCaretAfterDiagnostics\(currentView\)/);
- // The re-anchor must not dispatch a selection transaction: that closes the
- // completion popup the user is looking at (#9480).
- expect(queryEditorSource).toMatch(/function reanchorCaretAfterDiagnostics\(currentView: EditorViewType\)[\s\S]*?domSelection\.collapse\(target\.node, target\.offset\)/);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts
index 63a221adc7..c4574cb08d 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts
@@ -3,153 +3,12 @@ import { describe, expect, it } from "vitest";
import { createQueryEditorExecutionViewportOwnership, isQueryEditorPositionVisible } from "../../editor/queryEditorExecutionViewport";
const queryEditorSource = ["QueryEditor.vue", "useQueryEditorExecution.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
-const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-const editorToolbarSource = readFileSync(new URL("../../../components/layout/EditorToolbar.vue", import.meta.url), "utf8");
-const editorGroupSource = readFileSync(new URL("../../../components/layout/EditorGroup.vue", import.meta.url), "utf8");
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-const sqlExecutionSource = readFileSync(new URL("../../../composables/useSqlExecution.ts", import.meta.url), "utf8");
-const queryStoreSource = readFileSync(new URL("../../../stores/queryStore.ts", import.meta.url), "utf8");
describe("QueryEditor execution routing", () => {
it("routes the execution shortcut through the shared execution-mode contract while bypassing the picker", () => {
expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSql");
expect(queryEditorSource).not.toContain("forceCurrent");
});
-
- it("guards both CodeMirror execution bindings and the app-level fallback during IME composition", () => {
- expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSql");
- expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSqlInNewResultTab");
- expect(queryEditorSource).toContain("isEditorComposing");
- expect(queryEditorSource).toContain("function shouldBlockExecutionShortcut(event?: KeyboardEvent");
- expect(queryEditorSource).toContain("postCompositionKeyGuard.blocks(event)");
- expect(contentAreaSource).toContain("function shouldBlockQueryEditorExecutionShortcut(event: KeyboardEvent)");
- expect(contentAreaSource).toContain("queryEditorRef.value?.shouldBlockExecutionShortcut?.(event)");
- expect(appSource).toContain("if (!contentAreaRef.value?.shouldBlockQueryEditorExecutionShortcut?.(e)) requestActiveEditorExecuteInNewResultTab();");
- expect(appSource).toContain("if (!contentAreaRef.value?.shouldBlockQueryEditorExecutionShortcut?.(e)) requestActiveEditorExecute();");
- });
-
- it("keeps toolbar, context-menu, and gutter execution outside the shortcut guard", () => {
- expect(queryEditorSource).toContain("function executeFromContextMenu()");
- expect(queryEditorSource).toContain("requestExecute();\n focusEditor();");
- expect(queryEditorSource).toContain("function executeSqlStatementFromGutter");
- expect(queryEditorSource).toContain("const hasSelectedSql = !selection.empty && currentView.state.sliceDoc(selection.from, selection.to).trim().length > 0;");
- expect(queryEditorSource).toContain("const selectionOverlapsStatement = hasSelectedSql && selection.from < statementRange.to && statementRange.from < selection.to;");
- expect(queryEditorSource).toContain("const executionSnapshot = selectionOverlapsStatement ? sqlExecutionSnapshotFromView(currentView) : sqlExecutionSnapshotForRange(currentView, statementRange);");
- expect(queryEditorSource).toContain("emitExecutionRequest({ ...executionSnapshot, editorViewportRequestId })");
- });
-
- it("routes the new-result-tab shortcut through the same target selection contract", () => {
- expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSqlInNewResultTab");
- expect(queryEditorSource).toContain('emit("executeInNewResultTab", source)');
- expect(queryEditorSource).toContain("requestExecute({ bypassPicker: true, openInNewResultTab: true })");
- expect(contentAreaSource).toContain('const showResultRunTabs = computed(() => resultRuns.value.length > 0 && resultRunDisplayMode.value === "tabs")');
- expect(contentAreaSource).toContain("!!props.activeTab.resultRuns?.length");
- expect(contentAreaSource).toContain('role="tablist" :aria-label="t(\'tabs.resultRuns\')"');
- });
-
- it("keeps selection priority and the configured current/all target choice", () => {
- const selectionBranch = queryEditorSource.indexOf("if (!options.ignoreSelection && !selection.empty)");
- const executeModeBranch = queryEditorSource.indexOf("executionCandidateForMode(candidates, executeMode");
-
- expect(selectionBranch).toBeGreaterThan(-1);
- expect(executeModeBranch).toBeGreaterThan(selectionBranch);
- });
-
- it("captures the toolbar selection before the click event can change focus", () => {
- expect(queryEditorSource).toContain("function captureExecutionSnapshot(): SqlExecutionSnapshot | undefined");
- expect(queryEditorSource).toContain("return sqlExecutionSnapshotFromView(currentView);");
- expect(contentAreaSource).toContain("function captureQueryEditorExecutionSnapshot()");
- expect(contentAreaSource).toContain("queryEditorRef.value?.captureExecutionSnapshot();");
- expect(appSource).toContain("const pendingToolbarExecutionSnapshot = ref<SqlExecutionSnapshot & { tabId?: string }>();");
- expect(appSource).toContain("contentAreaRef.value?.captureQueryEditorExecutionSnapshot?.(tabId)");
- expect(appSource).toContain("pendingToolbarExecutionSnapshot.value = snapshot ? { ...snapshot, tabId } : undefined;");
- expect(appSource).toContain('if (source === "pointer" && snapshot && snapshot.tabId === targetTabId)');
- expect(appSource).toContain("pendingToolbarExecutionSnapshot.value = undefined;");
- expect(appSource).toContain("void tryExecute(snapshot, { tabId: targetTabId });");
- expect(appSource).toContain('@execute="(tabId: string, override?: SqlExecutionOverride) => tryExecute(override, { tabId })"');
- expect(appSource).toContain("async function resolveActiveExecutableSql(snapshot?: SqlExecutionSnapshot, executionTab?: QueryTab)");
- expect(appSource).toContain("const connection = connectionStore.getConfig(tab.connectionId) ?? activeConnection.value;");
- // Per-group toolbars call back into App-owned orchestration via injection.
- expect(appSource).toContain("provide(EDITOR_TOOLBAR_ACTIONS, {");
- expect(appSource).toContain("captureExecutionSnapshot: captureActiveEditorExecutionSnapshot,");
- expect(appSource).toContain("toolbarExecute: requestActiveEditorExecute,");
- expect(editorGroupSource).toContain('@execute-pointer-down="toolbar.captureExecutionSnapshot(activeTab.id)"');
- expect(editorGroupSource).toContain('@toolbar-execute="toolbar.toolbarExecute($event, activeTab.id)"');
- expect(editorToolbarSource).toContain("function onExecutePointerDown(event: MouseEvent)");
- expect(editorToolbarSource).toContain('emit("toolbarExecute", event.detail > 0 ? "pointer" : "keyboard")');
- expect(editorToolbarSource).not.toContain('emit("execute", event.detail > 0 ? "pointer" : "keyboard")');
- });
-
- it("uses the opt-in blank-line fallback and otherwise reports the missing cursor statement", () => {
- expect(queryEditorSource).toContain("executeAllOnBlankLine: settingsStore.editorSettings.executeAllOnBlankLine");
- expect(queryEditorSource).toContain('toast(t("editor.noExecutableStatementAtCursor"), 3000)');
- expect(queryEditorSource).not.toContain("?? candidates[0]");
- });
-
- it("consumes the execution shortcut and reports an empty current target", () => {
- expect(queryEditorSource).toContain("if (candidates.length === 0)");
- expect(queryEditorSource).toContain('if (executeMode === "current") toast(t("editor.noExecutableStatementAtCursor"), 3000)');
- });
-
- it("preserves the source range when executing a current/all candidate without a manual selection", () => {
- expect(queryEditorSource).toContain("emitExecutionRequest(sqlExecutionSnapshotForRange(currentView, candidate), options.openInNewResultTab)");
- expect(queryEditorSource).toContain("currentView ? sqlExecutionSnapshotForRange(currentView, candidate) : candidate.sql");
- expect(queryEditorSource).toContain("selectionFrom: range.from");
- expect(queryEditorSource).toContain("selectionTo: range.to");
- });
-
- it("preserves the source range when executing from the statement gutter", () => {
- expect(queryEditorSource).toContain("const editorViewportRequestId = executionViewportOwnership.beginRequest()");
- expect(queryEditorSource).toContain("sqlExecutionSnapshotFromView(currentView)");
- expect(queryEditorSource).toContain("sqlExecutionSnapshotForRange(currentView, statementRange)");
- expect(queryEditorSource).toContain("emitExecutionRequest({ ...executionSnapshot, editorViewportRequestId })");
- expect(queryEditorSource).not.toContain('emit("execute", statementRange.sql)');
- });
-
- it("claims gutter viewport ownership only after the matching execution starts", () => {
- expect(appSource).toContain("acceptQueryEditorExecutionViewport(editorViewportRequestId)");
- expect(appSource).toContain("onExecutionCancelled: (editorViewportRequestId) => contentAreaRef.value?.cancelQueryEditorExecutionViewport(editorViewportRequestId)");
- expect(contentAreaSource).toContain("acceptGutterExecutionViewport(requestId)");
- expect(contentAreaSource).toContain("cancelGutterExecutionViewport(requestId)");
- expect(sqlExecutionSource).toContain("onExecutionStarted: () => deps.onExecutionStarted?.(options.editorViewportRequestId!)");
- expect(sqlExecutionSource).toContain("onExecutionCancelled?: (editorViewportRequestId: number) => void;");
- expect(queryStoreSource.indexOf("tab.isExecuting = true")).toBeLessThan(queryStoreSource.indexOf("options?.onExecutionStarted?.()"));
- });
-
- it("tracks editor interaction while a query is executing", () => {
- expect(contentAreaSource).toContain("queryEditorRef.value?.beginExecutionViewportTracking()");
- expect(queryEditorSource).toContain('@wheel="recordExecutionViewportInteraction"');
- expect(queryEditorSource).toContain('@pointerdown="recordExecutionViewportInteraction"');
- expect(queryEditorSource).toContain("executionViewportOwnership.recordUserInteraction()");
- });
-
- it("lets the shortcut skip the picker without affecting other execution entry points", () => {
- // The picker guard must also honor the shortcut's bypass flag, otherwise Ctrl+Enter would keep popping the dialog.
- expect(queryEditorSource).toContain("if (options.bypassPicker || !settingsStore.editorSettings.showExecutionTargetPicker");
- });
-
- it("inserts a complete indented line below the current line", () => {
- expect(queryEditorSource).toContain('userEvent: "input.insertLineBelow"');
- expect(queryEditorSource).toContain("changes: { from: line.to, to: line.to, insert: insertion }");
- expect(queryEditorSource).toContain("const cursor = line.to + insertion.length");
- expect(queryEditorSource).not.toMatch(/key:\s*"Enter"[\s\S]{0,180}shift:\s*codeMirrorInsertNewlineKeepIndent/);
- });
-
- it("routes custom SQL shortcuts through selection-aware execution with dual keymap and DOM handlers", () => {
- expect(queryEditorSource).toContain("function runSqlShortcutAction(");
- expect(queryEditorSource).toContain('if (queryEditorSelectionLanguage() !== "sql") return false;');
- expect(queryEditorSource).toContain("buildSqlShortcutExecutionSql(action, selected, props.databaseType)");
- expect(queryEditorSource).toContain("enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts)");
- expect(queryEditorSource).toContain("uniqueSqlShortcutBindings(sqlShortcutActions)");
- expect(queryEditorSource).toContain("resolveSqlShortcutForDatabase(settingsStore.editorSettings.sqlShortcuts, shortcut, props.databaseType)");
- expect(queryEditorSource).toContain("isCharacterProducingShortcut(shortcut)");
- expect(queryEditorSource).toContain("createQueryEditorSqlShortcutDomHandler(");
- expect(queryEditorSource).toContain("() => props.databaseType");
- expect(queryEditorSource).toContain("shouldBlockExecutionShortcut(event, currentView)");
- expect(queryEditorSource).toContain("if (props.readOnly) return true;");
- expect(queryEditorSource).toContain("settingsStore.editorSettings.sqlShortcuts");
- expect(queryEditorSource).toContain("runKeymapComp.reconfigure(runKeymapExtension(codeMirrorRuntime.editorViewModule.keymap))");
- });
});
describe("QueryEditor execution viewport ownership", () => {
@@ -253,24 +112,4 @@ describe("QueryEditor completion cursor visibility", () => {
expect(isQueryEditorPositionVisible(15, [], viewport)).toBe(true);
expect(isQueryEditorPositionVisible(21, undefined, viewport)).toBe(false);
});
-
- it("checks visibility after completion ownership and before centering", () => {
- const ownershipCheck = queryEditorSource.indexOf("executionViewportOwnership.consumeCompletionPreservation()");
- const visibilityCheck = queryEditorSource.indexOf("if (isQueryEditorPositionVisible(pos, currentView.visibleRanges, currentView.viewport)) return");
- const centerScroll = queryEditorSource.indexOf('EditorView.scrollIntoView(pos, { y: "center" })');
-
- expect(ownershipCheck).toBeGreaterThan(-1);
- expect(visibilityCheck).toBeGreaterThan(ownershipCheck);
- expect(centerScroll).toBeGreaterThan(visibilityCheck);
- });
-});
-
-describe("ContentArea execution summary errors", () => {
- it("keeps batch errors selectable and copyable without triggering statement navigation", () => {
- expect(contentAreaSource).toContain('class="absolute inset-0 z-0 cursor-pointer');
- expect(contentAreaSource).toContain('data-native-clipboard class="min-w-0 flex-1 cursor-text select-text truncate"');
- expect(contentAreaSource).toContain("@mousedown.stop @click.stop @dblclick.stop");
- expect(contentAreaSource).toContain('@click.stop="copyExecutionSummaryError(item.error)"');
- expect(contentAreaSource).toContain("await copyToClipboard(error)");
- });
});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorExtendSelection.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorExtendSelection.spec.ts
index e65f40b883..49f673dfcf 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorExtendSelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorExtendSelection.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { selectParentSyntax } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorSelection, EditorState } from "@codemirror/state";
@@ -9,8 +8,6 @@ import { extendQueryEditorSelection, runQueryEditorAltExtendSelection } from "@/
import { chooseNextSemanticSelectionRange, type SemanticSelectionRange } from "@/lib/editor/semanticSelectionRanges";
import { sqlSemanticSelectionRanges } from "@/lib/editor/sqlSemanticSelectionRanges";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
function runCommand(command: Command, state: EditorState): EditorState {
let nextState = state;
const handled = command({
@@ -390,18 +387,6 @@ describe("query editor extend selection", () => {
expect(next.sliceDoc(next.selection.main.from, next.selection.main.to)).toBe("'001'");
});
- it("binds the configurable editor shortcut to CodeMirror semantic selection", () => {
- expect(queryEditorSource).toContain("extendQueryEditorSelection");
- expect(queryEditorSource).not.toContain("selectParentSyntax");
- expect(queryEditorSource).not.toContain("codeMirrorSelectParentSyntax");
- expect(queryEditorSource).toContain("shortcuts.extendSelection");
- expect(queryEditorSource).toContain("runQueryEditorAltExtendSelection");
- });
-
- it("registers a high-priority SQL string mouse selection style", () => {
- expect(queryEditorSource).toMatch(/Prec\.highest\(\s*EditorView\.mouseSelectionStyle\.of/);
- });
-
it("matches macOS Option+W by physical key when the event key is transformed", () => {
let commandRuns = 0;
let prevented = false;
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorFocus.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorFocus.spec.ts
index fe5ea23e2c..c4ed830b97 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorFocus.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorFocus.spec.ts
@@ -1,11 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { focusEditorView, type EditorViewLike } from "@/lib/editor/queryEditorFocus";
-const queryEditorSource = ["QueryEditor.vue", "queryEditorTypes.ts", "useQueryEditorExecution.ts", "useQueryEditorDocumentState.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
-const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-const editorToolbarSource = readFileSync(new URL("../../../components/layout/EditorToolbar.vue", import.meta.url), "utf8");
-
function createMockView(overrides: Partial<EditorViewLike> = {}): EditorViewLike {
return {
hasFocus: false,
@@ -37,25 +32,3 @@ describe("focusEditorView", () => {
expect(focusEditorView(undefined)).toBe(false);
});
});
-
-describe("QueryEditor auto focus wiring", () => {
- it("keeps auto focus opt-in for shared editor instances", () => {
- expect(queryEditorSource).toContain("autoFocus?: boolean;");
- expect(queryEditorSource).toMatch(/if \(props\.autoFocus\) \{[\s\S]*focusEditorView\(view\.value\);/);
- });
-
- it("enables auto focus for query tabs", () => {
- expect(contentAreaSource).toMatch(/<QueryEditor[\s\S]*?:\s*auto-focus="autoFocus !== false"\s[\s\S]*?:model-value="activeTab\.sql"/);
- });
-
- it("restores focus when the active query tab changes", () => {
- expect(queryEditorSource).toMatch(/if \(tabId !== prevTabId\) \{[\s\S]*?activateTabDocument\(prevTabId, tabId, val\);[\s\S]*?if \(props\.autoFocus\) restoreEditorFocus\(\);/);
- });
-});
-
-describe("QueryEditor toolbar focus", () => {
- it("does not move focus from the editor when clicking execute", () => {
- expect(editorToolbarSource).toMatch(/:disabled="activeTab\.isCancelling[\s\S]*?@mousedown\.prevent="onExecutePointerDown"[\s\S]*?@click="onExecuteClick"/);
- expect(queryEditorSource).toMatch(/function requestExecute\([\s\S]*?const currentView = view\.value;[\s\S]*?currentView\.focus\(\);[\s\S]*?requestExecuteFromView\(currentView/);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorHoverDdlCopy.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorHoverDdlCopy.spec.ts
deleted file mode 100644
index 4ac5d1b1e2..0000000000
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorHoverDdlCopy.spec.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const queryEditorSource = readFileSync(new URL("../../../components/editor/useQueryEditorHover.ts", import.meta.url), "utf8");
-const contentSource = readFileSync(new URL("../../../components/editor/queryEditorHoverContent.ts", import.meta.url), "utf8");
-
-describe("QueryEditor hover DDL copy", () => {
- it("reconciles the local sidebar index before remote hover fallback", () => {
- const hoverStart = queryEditorSource.indexOf("async function resolveSqlHoverTooltip");
- const hoverEnd = queryEditorSource.indexOf("\n }\n", hoverStart);
- const hoverSource = queryEditorSource.slice(hoverStart, hoverEnd);
- const localLookup = hoverSource.indexOf("connectionStore.lookupLocalCompletionTables");
- const remoteLookup = hoverSource.indexOf("connectionStore.listCompletionTables");
-
- expect(hoverStart).toBeGreaterThanOrEqual(0);
- expect(hoverEnd).toBeGreaterThan(hoverStart);
- expect(localLookup).toBeGreaterThanOrEqual(0);
- expect(remoteLookup).toBeGreaterThan(localLookup);
- expect(hoverSource).toContain("hoverTables = mergeCompletionTables(localHoverTables, hoverTables);");
- expect(hoverSource).toContain("completionMetadata.cachedTables = mergeCompletionTables(localHoverTables, completionMetadata.cachedTables);");
- });
-
- it("gates only the table DDL branch on the preference, keeping column hover", () => {
- expect(queryEditorSource).not.toContain("if (!settingsStore.editorSettings.showTableDdlHoverPreview) return null;");
- expect(queryEditorSource).toContain("if (table && settingsStore.editorSettings.showTableDdlHoverPreview && !semanticQualifierIsRowSource");
- });
-
- it("adds an accessible copy button that preserves SQL whitespace semantics", () => {
- expect(contentSource).toContain('copyButton.textContent = t("grid.copyDdl");');
- expect(contentSource).toContain('copyButton.setAttribute("aria-label", t("grid.copyDdl"));');
- expect(contentSource).toContain('copyButton.addEventListener("pointerdown"');
- expect(contentSource).toContain("event.stopPropagation();");
- expect(contentSource).toContain("await copyToClipboard(normalizeAlignedSqlWhitespace(sqlContent));");
- expect(contentSource).toContain('toast(t("contextMenu.ddlCopied"), 2000);');
- expect(contentSource).toContain('toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorJoinLines.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorJoinLines.spec.ts
index f0dcc66089..01f4ef732a 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorJoinLines.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorJoinLines.spec.ts
@@ -1,10 +1,7 @@
-import { readFileSync } from "node:fs";
import { EditorSelection, EditorState, type Extension, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { joinQueryEditorLines } from "@/lib/editor/queryEditorJoinLines";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
function runJoinLines(doc: string, selection: EditorSelection | { anchor: number; head?: number }, extensions: Extension[] = []) {
let state = EditorState.create({ doc, selection, extensions });
const dispatch = vi.fn((transaction: Transaction) => {
@@ -21,11 +18,6 @@ function runJoinLines(doc: string, selection: EditorSelection | { anchor: number
}
describe("joinQueryEditorLines", () => {
- it("binds the configurable join-lines shortcut in QueryEditor", () => {
- expect(queryEditorSource).toContain('import { joinQueryEditorLines } from "@/lib/editor/queryEditorJoinLines";');
- expect(queryEditorSource).toContain("...binding(shortcuts.joinLines, joinQueryEditorLines)");
- });
-
it("joins every selected line with one separating space", () => {
const doc = "SELECT id,\n name\nFROM users;";
const result = runJoinLines(doc, EditorSelection.range(0, doc.length));
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorLargePaste.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorLargePaste.spec.ts
index ea2902625b..54da5071c7 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorLargePaste.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorLargePaste.spec.ts
@@ -1,11 +1,8 @@
-import { readFileSync } from "node:fs";
import { history, undo, undoDepth } from "@codemirror/commands";
import { EditorState, Transaction } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { LARGE_PASTE_HISTORY_USER_EVENT, LARGE_PASTE_NATIVE_RECOVERY_THRESHOLD, normalizeQueryEditorPasteText, recoverableNativePasteSuffix, shouldRecoverLargeTauriPaste } from "@/lib/editor/queryEditorLargePaste";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
describe("QueryEditor large paste recovery", () => {
it("recovers the suffix of a SQL paste truncated at the WebView boundary", () => {
const sql = Array.from({ length: 10_925 }, (_, index) => `('Z${String(index).padStart(13, "0")}'),`).join("\r\n");
@@ -59,8 +56,4 @@ describe("QueryEditor large paste recovery", () => {
expect(state.doc.toString()).toBe("SELECT ");
expect(state.selection.main.from).toBe(7);
});
-
- it("wires the recovery into the editor paste event", () => {
- expect(queryEditorSource).toMatch(/paste\(event, currentView\)[\s\S]*?recoverLargeTauriPaste\(event, currentView\)/);
- });
});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorLineComment.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorLineComment.spec.ts
index cc0c5e7653..00fb59e5f9 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorLineComment.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorLineComment.spec.ts
@@ -1,15 +1,9 @@
-import { readFileSync } from "node:fs";
import { toggleLineComment } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorState, Prec, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { queryEditorCommentTokens, queryEditorLineCommentToken, queryEditorWordLanguageData } from "@/lib/editor/queryEditorLineComment";
-const editorThemesSource = readFileSync(new URL("../../editor/editorThemes.ts", import.meta.url), "utf8");
-const shellHighlightSource = readFileSync(new URL("../../editor/codemirrorShellLineCommentHighlight.ts", import.meta.url), "utf8");
-
-const extensionsSource = readFileSync(new URL("../../../components/editor/queryEditorSqlExtensions.ts", import.meta.url), "utf8");
-
function runToggleLineComment(doc: string, commentToken: string) {
let state = EditorState.create({
doc,
@@ -72,24 +66,6 @@ describe("QueryEditor word selection", () => {
});
describe("QueryEditor line comment", () => {
- it("overrides the language comment tokens in the SQL language compartment", () => {
- expect(extensionsSource).toContain("Prec.highest(EditorState.languageData.of(() => [{ commentTokens: queryEditorCommentTokens(props.databaseType) }]))");
- });
-
- it("highlights // comments with the theme's comment style", () => {
- expect(extensionsSource).toContain('queryEditorLineCommentToken(props.databaseType) === "//" ? shellLineCommentHighlightPlugin : []');
- expect(extensionsSource).toContain("const shellLineCommentHighlightPlugin = createShellLineCommentHighlight({ ViewPlugin, Decoration, highlightingFor, syntaxTree });");
- expect(extensionsSource).toContain("shellLineCommentTheme(EditorView),");
- expect(editorThemesSource).toContain('".cm-shell-line-comment *"');
- expect(editorThemesSource).toContain('color: "inherit !important"');
- });
-
- it("bounds shell comment scanning to syntax-aware visible lines", () => {
- expect(shellHighlightSource).toContain("view.state.doc.lineAt(visibleRange.from).from");
- expect(shellHighlightSource).toContain("tree.resolveInner(absoluteFrom, 1)");
- expect(shellHighlightSource).not.toContain("sliceString(0, end)");
- });
-
it("comments a MongoDB line with //", () => {
const result = runToggleLineComment("db.users.find({})", "//");
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorPasteCaretResync.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorPasteCaretResync.spec.ts
index 4cc8f0a4a8..d078861f77 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorPasteCaretResync.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorPasteCaretResync.spec.ts
@@ -1,10 +1,7 @@
-import { readFileSync } from "node:fs";
import { EditorSelection } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { computePasteCaretResyncTarget } from "@/lib/editor/queryEditorPasteCaretResync";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
describe("computePasteCaretResyncTarget", () => {
it("nudges a single caret forward when there is room", () => {
expect(computePasteCaretResyncTarget(EditorSelection.single(3), 10)).toBe(4);
@@ -27,10 +24,3 @@ describe("computePasteCaretResyncTarget", () => {
expect(computePasteCaretResyncTarget(EditorSelection.single(0), 0)).toBeNull();
});
});
-
-describe("QueryEditor paste caret resync wiring", () => {
- it("resyncs only an unchanged single caret after an input.paste transaction", () => {
- expect(queryEditorSource).toMatch(/update\.transactions\.some\(\(tr\) => tr\.isUserEvent\("input\.paste"\)\)[\s\S]*?resyncCaretAfterPaste\(update\.view\)/);
- expect(queryEditorSource).toMatch(/computePasteCaretResyncTarget\(selection, view\.state\.doc\.length\)/);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorSemanticHighlightPerformance.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorSemanticHighlightPerformance.spec.ts
index 880221ed3c..728df976f1 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorSemanticHighlightPerformance.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorSemanticHighlightPerformance.spec.ts
@@ -1,13 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { expandToSqlStatementWindow } from "@/lib/sql/insertValueHints";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
-const diagnosticsSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
-
-const extensionsSource = readFileSync(new URL("../../../components/editor/queryEditorSqlExtensions.ts", import.meta.url), "utf8");
-
describe("QueryEditor semantic highlighting while scrolling", () => {
it("recognizes the large single-statement shape from the reported regression", () => {
const sql = `CREATE TABLE [dbo].[code] ([id] int, [label] nvarchar(32));\nINSERT INTO [dbo].[code] ([id], [label]) VALUES\n${Array.from({ length: 240 }, (_, index) => `(${index}, N'row-${String(index).padStart(4, "0")}'),`).join("\n")}`;
@@ -17,42 +10,4 @@ describe("QueryEditor semantic highlighting while scrolling", () => {
expect(window.to - window.from).toBeGreaterThan(2_000);
expect(window.from).toBe(insertStart);
});
-
- it("reuses semantic statement windows across viewport-only updates", () => {
- expect(extensionsSource).toContain('private cachedDoc: import("@codemirror/state").Text | null = null;');
- expect(extensionsSource).toContain("private cachedWindows: Array<{");
- expect(extensionsSource).toContain("const cached = this.cachedWindows.find");
- expect(extensionsSource).toContain("const pendingWindows: Array<{ from: number; to: number }>");
- expect(extensionsSource).toContain("MAX_SQL_SEMANTIC_HIGHLIGHT_WINDOWS = 32");
- expect(extensionsSource).toContain("this.cachedWindows.splice(0, this.cachedWindows.length - MAX_SQL_SEMANTIC_HIGHLIGHT_WINDOWS)");
- });
-
- it("defers semantic highlighting while the document is changing", () => {
- expect(extensionsSource).toContain("SQL_SEMANTIC_HIGHLIGHT_DEBOUNCE_MS = 100");
- expect(extensionsSource).toContain("this.decorations = this.decorations.map(update.changes)");
- expect(extensionsSource).toContain("refreshSqlSemanticHighlightEffect.of(null)");
- });
-
- it("never exposes undefined decorations and prewarms the full document only once per document", () => {
- expect(extensionsSource).toContain("this.decorations = Decoration.none;");
- expect(extensionsSource).toContain('private prewarmedDoc: import("@codemirror/state").Text | null = null;');
- expect(extensionsSource).toContain("const shouldPrewarmFullDocument =");
- expect(extensionsSource).toContain("if (shouldPrewarmFullDocument) this.prewarmedDoc = doc;");
- });
-
- it("keeps existing highlights while the parser catches up instead of wiping them", () => {
- // An incomplete Lezer parse must not clear table-name decorations: the
- // deferred refresh retries, so a freshly mounted editor (tab switch) also
- // recovers even without a later viewport change.
- expect(extensionsSource).toContain("this.scheduleRefresh(currentView);");
- expect(extensionsSource).toContain("return this.decorations;");
- });
-
- it("keeps preview and diagnostics on the shared statement-range cache", () => {
- expect(queryEditorSource).toContain("executableStatementRangeCache = executableStatementRangeCacheForDoc");
- expect(diagnosticsSource).toContain('props.databaseType === "sqlserver" ? undefined : runtime.executableStatementRangeCache?.ranges');
- expect(queryEditorSource).toContain("get executableStatementRangeCache()");
- expect(queryEditorSource).toContain("set executableStatementRangeCache(value)");
- expect(queryEditorSource).toContain("const cursorRange = executableStatementRangeAtCursor(executableStatementRangeCache, cursorPos)");
- });
});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts
deleted file mode 100644
index 05677822a9..0000000000
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorSqlSignature.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-
-const runtimeSource = readFileSync(new URL("../../../components/editor/queryEditorCodeMirrorRuntime.ts", import.meta.url), "utf8");
-
-describe("QueryEditor SQL signature refresh wiring", () => {
- it("reconfigures signature help when the database dialect or driver profile changes", () => {
- expect(runtimeSource).toContain('sqlSignatureComp: import("@codemirror/state").Compartment | null;');
- expect(runtimeSource).toContain("runtime.sqlSignatureComp = new Compartment();");
- expect(queryEditorSource).toContain("initializedRuntime.sqlSignatureComp.of(sqlExtensions.buildSqlSignatureExtension())");
-
- const watcherStart = queryEditorSource.indexOf("watch([() => props.databaseType, () => props.dialect, () => props.syntaxDialect, sqlDriverProfile]");
- const watcherEnd = queryEditorSource.indexOf("\n});", watcherStart);
- const dialectWatcher = queryEditorSource.slice(watcherStart, watcherEnd);
-
- expect(watcherStart).toBeGreaterThanOrEqual(0);
- expect(watcherEnd).toBeGreaterThan(watcherStart);
- expect(dialectWatcher).toContain("codeMirrorRuntime.sqlSignatureComp.reconfigure(codeMirrorRuntime.buildSqlSignatureExtension())");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorTextEdits.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorTextEdits.spec.ts
index 2e49aeaec5..747ef2de7e 100644
--- a/apps/desktop/src/lib/__tests__/editor/queryEditorTextEdits.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorTextEdits.spec.ts
@@ -1,12 +1,7 @@
-import { readFileSync } from "node:fs";
import { EditorSelection, EditorState } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { blankLineDeletionChanges, replaceSelectedEditorText } from "@/lib/editor/queryEditorTextEdits";
-const queryEditorSource = ["QueryEditor.vue", "useQueryEditorTextActions.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
-
-const contextMenuSource = readFileSync(new URL("../../../components/editor/QueryEditorContextMenu.vue", import.meta.url), "utf8");
-
function applyBlankLineDeletion(doc: string, from: number, to: number): string {
const state = EditorState.create({
doc,
@@ -27,12 +22,6 @@ describe("replaceSelectedEditorText", () => {
expect(replaceSelectedEditorText({ state, dispatch }, "'a','b'")).toBe(false);
expect(dispatch).not.toHaveBeenCalled();
});
-
- it("disables and guards delimited-list generation in QueryEditor", () => {
- expect(contextMenuSource).toContain("disabled: state.readOnly || !canCopySelectedSql");
- expect(queryEditorSource).toMatch(/function openDelimitedListDialog\(\) \{\s+if \(props\.readOnly\) return;/);
- expect(queryEditorSource).toMatch(/function applyDelimitedListResult\(result: string\) \{[\s\S]*if \(!currentView \|\| props\.readOnly\) return;[\s\S]*replaceSelectedEditorText/);
- });
});
describe("blankLineDeletionChanges", () => {
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
index 6585086e6e..028f6ff3b2 100644
--- a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
@@ -16,7 +16,6 @@ import {
} from "@/lib/mcp/mcpPolicySelection";
const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-const scopePickerSource = readFileSync(new URL("../../../components/settings/McpConnectionScopePicker.vue", import.meta.url), "utf8");
const mcpServerSource = readFileSync(new URL("../../../../../../crates/dbx-mcp/src/server.rs", import.meta.url), "utf8");
describe("MCP execution permission selection", () => {
@@ -133,76 +132,6 @@ describe("MCP policy settings state", () => {
expect(loadingStart).toBeLessThan(policyLoad);
expect(loadingEnd).toBeGreaterThan(policyLoad);
});
-
- it("renders one static mode hint in place of stacked per-mode description tracks", () => {
- expect(settingsDialogSource).not.toContain("data-mcp-execution-mode-description");
- const groupStart = settingsDialogSource.indexOf('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');
- const hintIndex = settingsDialogSource.indexOf("settings.mcpPermissionGlobalDefaultHint");
- expect(groupStart).toBeGreaterThan(-1);
- expect(hintIndex).toBeGreaterThan(groupStart);
- });
-
- it("keeps execution mode cards accessible as a keyboard radio group", () => {
- expect(settingsDialogSource).toContain('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');
- expect(settingsDialogSource).toContain('v-for="mode in mcpExecutionModeOptions"');
- expect(settingsDialogSource.match(/role="radio"/g)).toHaveLength(1);
- expect(settingsDialogSource).toContain(':aria-checked="mcpExecutionMode === mode"');
- expect(settingsDialogSource).toContain(':tabindex="mcpExecutionMode === mode ? 0 : -1"');
- expect(settingsDialogSource).toContain("onMcpExecutionModeKeydown($event, mode)");
- expect(settingsDialogSource).toContain('@keydown="onMcpExecutionModeKeydown($event, mode)"');
- });
-
- it("keeps MCP client config tabs on a single scrollable row", () => {
- const tabsStart = settingsDialogSource.indexOf('<Tabs v-model="mcpConfigTab"');
- const tabsEnd = settingsDialogSource.indexOf("</TabsList>", tabsStart);
- const tabsSource = settingsDialogSource.slice(tabsStart, tabsEnd);
-
- expect(tabsStart).toBeGreaterThan(-1);
- expect(tabsEnd).toBeGreaterThan(tabsStart);
- expect(tabsSource).toContain("overflow-x-auto");
- expect(tabsSource).toContain("min-w-0");
- expect(tabsSource).toContain("max-w-full");
- expect(tabsSource).toContain("overscroll-x-contain");
- expect(tabsSource).not.toContain("flex-wrap");
- expect(tabsSource).not.toContain("grid-cols-");
- expect(tabsSource.match(/flex-none shrink-0/g)).toHaveLength(14);
- expect(tabsSource).toContain('<TabsTrigger value="deepseek-harness"');
- expect(tabsSource).toContain('<TabsTrigger value="codebuddy"');
- expect(tabsSource).toContain('<TabsTrigger value="zcode"');
- expect(tabsSource).toContain('<TabsTrigger value="qoder"');
- expect(tabsSource).toContain('<TabsTrigger value="workbuddy"');
- expect(tabsSource).not.toContain("min-w-0 px-");
-
- const codeBuddyStart = settingsDialogSource.indexOf('<TabsContent value="codebuddy"', tabsEnd);
- const codeBuddyEnd = settingsDialogSource.indexOf("</TabsContent>", codeBuddyStart);
- const codeBuddySource = settingsDialogSource.slice(codeBuddyStart, codeBuddyEnd);
-
- expect(codeBuddyStart).toBeGreaterThan(tabsEnd);
- expect(codeBuddyEnd).toBeGreaterThan(codeBuddyStart);
- expect(codeBuddySource).toContain("settings.mcpCodeBuddyConfigPath");
- expect(codeBuddySource).toContain("mcpJsonRecommendedConfig");
- expect(codeBuddySource).toContain("copyMcpText('codebuddy-config', mcpJsonRecommendedConfig)");
-
- const zCodeStart = settingsDialogSource.indexOf('<TabsContent value="zcode"', tabsEnd);
- const zCodeEnd = settingsDialogSource.indexOf("</TabsContent>", zCodeStart);
- const zCodeSource = settingsDialogSource.slice(zCodeStart, zCodeEnd);
-
- expect(zCodeStart).toBeGreaterThan(tabsEnd);
- expect(zCodeEnd).toBeGreaterThan(zCodeStart);
- expect(zCodeSource).toContain("settings.mcpZCodeConfigPath");
- expect(zCodeSource).toContain("mcpJsonRecommendedConfig");
- expect(zCodeSource).toContain("copyMcpText('zcode-config', mcpJsonRecommendedConfig)");
-
- const qoderStart = settingsDialogSource.indexOf('<TabsContent value="qoder"', tabsEnd);
- const qoderEnd = settingsDialogSource.indexOf("</TabsContent>", qoderStart);
- const qoderSource = settingsDialogSource.slice(qoderStart, qoderEnd);
-
- expect(qoderStart).toBeGreaterThan(tabsEnd);
- expect(qoderEnd).toBeGreaterThan(qoderStart);
- expect(qoderSource).toContain("settings.mcpQoderConfigPath");
- expect(qoderSource).toContain("mcpQoderRecommendedConfig");
- expect(qoderSource).toContain("copyMcpText('qoder-config', mcpQoderRecommendedConfig)");
- });
});
describe("MCP connection search", () => {
@@ -218,12 +147,4 @@ describe("MCP connection search", () => {
expect(matchesMcpSearchQuery(" ", [null, undefined])).toBe(true);
expect(matchesMcpSearchQuery("missing-id", ["missing-id-123", "Previously selected connection (unavailable)"])).toBe(true);
});
-
- it("uses responsive allowed and available panes with an allowed-first compact view", () => {
- expect(scopePickerSource).toContain('const compactPane = ref<ScopePane>("allowed")');
- expect(scopePickerSource).toContain('data-scope-pane="available"');
- expect(scopePickerSource).toContain('data-scope-pane="allowed"');
- expect(scopePickerSource).toContain("@container mcp-scope (min-width: 42rem)");
- expect(scopePickerSource).toContain("filteredUnavailableAllowedIds");
- });
});
diff --git a/apps/desktop/src/lib/__tests__/mq/mqListPanels.spec.ts b/apps/desktop/src/lib/__tests__/mq/mqListPanels.spec.ts
deleted file mode 100644
index 6e3c9eaab4..0000000000
--- a/apps/desktop/src/lib/__tests__/mq/mqListPanels.spec.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-function componentSource(name: string): string {
- return readFileSync(new URL(`../../../components/mq/${name}`, import.meta.url), "utf8");
-}
-
-describe("MQ list panels", () => {
- it("does not issue per-tenant detail requests from the tenant list UI", () => {
- const source = componentSource("TenantsPanel.vue");
-
- expect(source).not.toContain("mqGetTenant");
- });
-
- it("does not issue per-namespace permission requests from the namespace list UI", () => {
- const source = componentSource("NamespacesPanel.vue");
-
- expect(source).not.toContain("mqListPermissions");
- });
-
- it("refreshing policies hydrates missing fields from defaults instead of dirty form values", () => {
- const source = componentSource("PoliciesPanel.vue");
-
- expect(source).not.toContain("policyFormsFromEffectivePolicies(loaded, currentPolicyForms())");
- expect(source).toContain("policyFormsFromEffectivePolicies(loaded, defaultMqPolicyForms())");
- });
-
- it("raw api panel includes common endpoint presets that use the selected mq context", () => {
- const rawSource = componentSource("RawApiPanel.vue");
- const consoleSource = componentSource("MqAdminConsole.vue");
-
- expect(rawSource).toContain("const presets = computed<RawApiPreset[]>");
- expect(rawSource).toContain("/admin/v2/brokers/version");
- expect(rawSource).toContain("/internalStats");
- expect(rawSource).toContain("/partitioned-stats");
- expect(rawSource).toContain("/schema");
- expect(rawSource).toContain("presetsCollapsed");
- expect(rawSource).toContain("formatJsonBody");
- expect(rawSource).toContain("bodyTextareaRows");
- expect(rawSource).toContain("body: isReadMethod.value ? undefined : parseBody()");
- expect(consoleSource).toContain(':tenant="selectedTenant"');
- expect(consoleSource).toContain(':namespace="selectedNamespace"');
- expect(consoleSource).toContain(':topic="selectedTopic"');
- });
-
- it("keeps Kafka topic subscriptions and cluster-wide consumer groups on separate panels", () => {
- const consoleSource = componentSource("MqAdminConsole.vue");
-
- expect(consoleSource).toContain("KafkaConsumerGroupsPanel");
- expect(consoleSource).toContain("activeTab === 'subscriptions' && canManageSubscriptions");
- expect(consoleSource).toContain("activeTab === 'consumerGroups' && isKafkaCluster");
- expect(consoleSource).not.toContain("activeTab === 'subscriptions' && canManageSubscriptions && isKafkaCluster");
- });
-
- it("routes a Kafka consumer-group partition topic to its topic-scoped subscriptions", () => {
- const consoleSource = componentSource("MqAdminConsole.vue");
-
- expect(consoleSource).toContain("function handleKafkaConsumerGroupTopicSelected(topic: string)");
- expect(consoleSource).toContain("shortName: topic");
- expect(consoleSource).toContain('setActiveTab("subscriptions")');
- expect(consoleSource).toContain('@navigate-subscriptions="handleKafkaConsumerGroupTopicSelected"');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts b/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts
deleted file mode 100644
index 7b53551e11..0000000000
--- a/apps/desktop/src/lib/__tests__/plugins/pluginCenterIntegration.spec.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
-const groupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
-const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
-const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
-const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
-const pluginCenterSource = readFileSync(new URL("../../../components/plugins/PluginContributionsPanel.vue", import.meta.url), "utf8");
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-const connectionStoreSource = readFileSync(new URL("../../../stores/connectionStore.ts", import.meta.url), "utf8");
-
-describe("plugin center integration", () => {
- it("opens from the top toolbar as an independent app surface", () => {
- expect(toolbarSource).toContain("toolbarItems.pluginCenter");
- expect(toolbarSource).toContain("emit('open-plugin-center')");
- expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
- expect(appSource).toContain("<PluginCenterPage");
- // The plugin center pill lives in the focused group's tab strip, like the
- // settings and driver-store special pages.
- expect(groupTabBarSource).toContain("data-plugin-center-tab");
- expect(appSource).toContain(':plugin-center-open="pluginCenterTabOpen"');
- });
-
- it("keeps plugin management out of Driver Manager", () => {
- expect(driverStoreSource).not.toContain('value="plugins"');
- expect(driverStoreSource).not.toContain("PluginContributionsPanel");
- });
-
- it("refreshes toolbar update state after manual and component update checks", () => {
- expect(appSource).toContain('if (componentRefresh.status === "fulfilled" && componentRefresh.value) syncToolbarComponentUpdateState()');
- expect(appSource).toContain("if (result.failed.length === 0) syncToolbarComponentUpdateState()");
- expect(appSource).toContain("function syncToolbarComponentUpdateState()");
- });
-
- it("refreshes all update sources in the background whenever the update center opens", () => {
- expect(appSource).toContain("function handleToolbarUpdateClick() {\n showUpdateDialog.value = true;\n if (!checkingAllUpdates.value) void checkAllUpdates();\n}");
- });
-
- it("refreshes the plugin center after component-level plugin updates", () => {
- expect(appSource).toContain("notifyComponentPluginsUpdated()");
- expect(pluginCenterSource).toContain("COMPONENT_PLUGINS_UPDATED_EVENT");
- expect(pluginCenterSource).toContain("window.addEventListener(COMPONENT_PLUGINS_UPDATED_EVENT, handleComponentPluginsUpdated)");
- expect(pluginCenterSource).toContain("installedPlugins.value = await api.listPlugins()");
- });
-
- it("refreshes global component update state after manual management-surface changes", () => {
- expect(appSource).toContain("COMPONENT_UPDATES_CHANGED_EVENT");
- expect(appSource).toContain("window.addEventListener(COMPONENT_UPDATES_CHANGED_EVENT, handleComponentUpdatesChanged)");
- expect(appSource).toContain("componentUpdates.refresh({ force: true })");
- for (const source of [pluginCenterSource, driverStoreSource, settingsDialogSource, connectionDialogSource, connectionStoreSource]) {
- expect(source).toContain("notifyComponentUpdatesChanged()");
- }
- });
-
- it("formats structured backend errors for local and URL package installs", () => {
- const localInstall = pluginCenterSource.slice(pluginCenterSource.indexOf("async function installPlugin("), pluginCenterSource.indexOf("function isHttpPackageUrl("));
- const urlInstall = pluginCenterSource.slice(pluginCenterSource.indexOf("async function installPluginFromUrl("), pluginCenterSource.indexOf("const urlProgressPercent"));
-
- for (const installSource of [localInstall, urlInstall]) {
- expect(installSource).toContain("toast(translateBackendError(t, cause), 8000)");
- expect(installSource).not.toContain("String(cause)");
- }
- });
-
- it("creates and edits plugin connections in the unified connection dialog", () => {
- expect(appDialogsSource).toContain(':edit-config="editConfig"');
- expect(appDialogsSource).toContain(':plugin-provider="connectionPluginProvider"');
- expect(appDialogsSource).not.toContain("pluginEditConfig");
- expect(connectionDialogSource).toContain("pluginConnectionProviderOptionValue");
- expect(connectionDialogSource).toContain("<PluginConnectionFields");
- expect(connectionDialogSource).toContain("buildPluginConnectionConfig");
- });
-
- it("keeps marketplace security automatic and developer controls hidden", () => {
- const template = pluginCenterSource.split("<template>")[1];
- const settingsIndex = template.indexOf('value="settings"');
- const developerOptionsIndex = template.indexOf("pluginPlatform.developerOptionsTitle");
- const allowUnsignedIndex = template.indexOf("pluginPlatform.allowUnsignedDevelopmentPackage");
- expect(template).toContain('value="marketplace"');
- expect(template).toContain('value="installed"');
- expect(template).toContain('value="settings"');
- expect(settingsIndex).toBeLessThan(developerOptionsIndex);
- expect(developerOptionsIndex).toBeLessThan(allowUnsignedIndex);
- expect(template).toContain("pluginPlatform.signedPackagesVerifiedAutomatically");
- expect(template).toContain('<template v-if="showCustomRepositoryTrustSettings">');
- expect(pluginCenterSource).toContain("customRepositories.value.length > 0 || trustedKeys.value.length > 0");
- expect(template).not.toContain("pluginPlatform.advancedSecurityTitle");
- expect(pluginCenterSource).toContain("fetchPluginMarketplaceCatalogs");
- expect(template).not.toContain("pluginPlatform.centerTitle");
- expect(template).not.toContain("marketplaceTarget");
- expect(template).not.toContain("<select");
- expect(template).toContain("<SelectTrigger");
- expect(template).not.toContain("max-w-md grid-cols-3");
- expect(template).not.toContain("marketplaceCategory");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/redis/RedisExpiryWiring.spec.ts b/apps/desktop/src/lib/__tests__/redis/RedisExpiryWiring.spec.ts
deleted file mode 100644
index 3cce2f72b7..0000000000
--- a/apps/desktop/src/lib/__tests__/redis/RedisExpiryWiring.spec.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { readFileSync } from "node:fs";
-import { parse } from "vue/compiler-sfc";
-import ts from "typescript";
-import { describe, expect, it } from "vitest";
-
-const browserSource = readFileSync(new URL("../../../components/redis/RedisKeyBrowser.vue", import.meta.url), "utf8");
-const viewerSource = readFileSync(new URL("../../../components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
-const localeSources = {
- az: readFileSync(new URL("../../../i18n/locales/az.ts", import.meta.url), "utf8"),
- en: readFileSync(new URL("../../../i18n/locales/en.ts", import.meta.url), "utf8"),
- es: readFileSync(new URL("../../../i18n/locales/es.ts", import.meta.url), "utf8"),
- it: readFileSync(new URL("../../../i18n/locales/it.ts", import.meta.url), "utf8"),
- ja: readFileSync(new URL("../../../i18n/locales/ja.ts", import.meta.url), "utf8"),
- ko: readFileSync(new URL("../../../i18n/locales/ko.ts", import.meta.url), "utf8"),
- "pt-BR": readFileSync(new URL("../../../i18n/locales/pt-BR.ts", import.meta.url), "utf8"),
- tr: readFileSync(new URL("../../../i18n/locales/tr.ts", import.meta.url), "utf8"),
- "zh-CN": readFileSync(new URL("../../../i18n/locales/zh-CN.ts", import.meta.url), "utf8"),
- "zh-TW": readFileSync(new URL("../../../i18n/locales/zh-TW.ts", import.meta.url), "utf8"),
-};
-
-function findFunction(source: string, name: string): ts.FunctionDeclaration {
- const parsed = parse(source, { filename: `${name}.vue` });
- expect(parsed.errors).toEqual([]);
- const script = parsed.descriptor.scriptSetup;
- expect(script).toBeDefined();
- const program = ts.createSourceFile(`${name}.ts`, script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
- const declaration = program.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
- expect(declaration).toBeDefined();
- return declaration!;
-}
-
-function callsIn(node: ts.Node): ts.CallExpression[] {
- const calls: ts.CallExpression[] = [];
- const visit = (child: ts.Node) => {
- if (ts.isCallExpression(child)) calls.push(child);
- ts.forEachChild(child, visit);
- };
- visit(node);
- return calls;
-}
-
-function callName(call: ts.CallExpression): string | undefined {
- if (ts.isIdentifier(call.expression)) return call.expression.text;
- if (ts.isPropertyAccessExpression(call.expression)) return `${call.expression.expression.getText()}.${call.expression.name.text}`;
- return undefined;
-}
-
-describe("Redis expiry mode wiring", () => {
- it("writes every create type before applying exactly one shared expiration policy", () => {
- const create = findFunction(browserSource, "createRedisKey");
- const calls = callsIn(create);
- const expectedWriterArgumentCounts: Record<string, number> = {
- "api.redisSetString": 4,
- "api.redisJsonSet": 4,
- "api.redisHashSet": 5,
- "api.redisListPush": 4,
- "api.redisSetAdd": 4,
- "api.redisZadd": 5,
- "api.redisStreamAdd": 5,
- };
-
- for (const [name, argumentCount] of Object.entries(expectedWriterArgumentCounts)) {
- const writerCalls = calls.filter((call) => callName(call) === name);
- expect(writerCalls.length, `${name} should be used by the create flow`).toBeGreaterThan(0);
- expect(
- writerCalls.every((call) => call.arguments.length === argumentCount),
- `${name} must not receive a per-write TTL`,
- ).toBe(true);
- }
-
- expect(calls.map(callName)).toContain("applyRedisExpiryPolicy");
- expect(create.getText()).toContain("if (creatingKey.value) return;");
- expect(calls.map(callName)).not.toContain("api.redisSetTtl");
- expect(calls.map(callName)).not.toContain("api.redisSetExpireAt");
- expect(create.getText().lastIndexOf("applyRedisExpiryPolicy")).toBeGreaterThan(create.getText().lastIndexOf("api.redisStreamAdd"));
- expect(findFunction(browserSource, "syncWrittenKey").getText()).toContain('if (created.redis_type === "none")');
- expect(create.getText()).toContain('toast(t("redis.keyExpiredBeforeDisplay"), 3000)');
- expect(create.getText()).toContain("if (wroteValue && writtenKeyRaw)");
- expect(findFunction(browserSource, "reflectWrittenKey").getText()).toContain("removeKnownKey(keyRaw)");
- });
-
- it("keeps only unwritten structured entries after a later writer fails", () => {
- const create = findFunction(browserSource, "createRedisKey").getText();
- const partialRecoveryStart = create.indexOf("if (writingStructuredEntries)");
- const genericRecoveryStart = create.lastIndexOf("if (wroteValue && writtenKeyRaw)");
- const partialRecovery = create.slice(partialRecoveryStart, genericRecoveryStart);
-
- expect(create).toContain("let writingStructuredEntries = false;");
- expect(create).toContain("const pendingEntries = createKeyEntries.value.slice();");
- expect(create.match(/for \(const entry of pendingEntries\)/g)).toHaveLength(4);
- expect(create.match(/removeWrittenCreateKeyEntry\(entry\.id\)/g)).toHaveLength(4);
- expect(create).toContain("createKeyPartiallyWritten.value = true;");
- expect(partialRecovery).toContain("await reflectWrittenKey(writtenKeyRaw);");
- expect(partialRecovery).toContain('t("redis.createKeyPartialWrite")');
- expect(partialRecovery).not.toContain("showCreateKeyDialog.value = false;");
- expect(browserSource).toContain(':disabled="creatingKey || createKeyPartiallyWritten"');
- expect(findFunction(browserSource, "onCreateKeyDialogOpenChange").getText()).toContain("if (!open && creatingKey.value) return;");
- expect(findFunction(browserSource, "onCreateKeyTypeChange").getText()).toContain("if (creatingKey.value || createKeyPartiallyWritten.value) return;");
- });
-
- it("defaults TTL editing by server state, supports absolute prefill, and keeps teleported controls inside the editor", () => {
- const start = findFunction(viewerSource, "startEditTtl").getText();
- const save = findFunction(viewerSource, "saveTtl").getText();
- const currentTtl = findFunction(viewerSource, "currentEditableTtl").getText();
-
- expect(start).toContain("redisExpiryModeForTtl(ttl)");
- expect(currentTtl).toContain("computeTtlForExpiryEdit(countdownTtl.value, data.value.ttl)");
- expect(viewerSource).toContain("unixSecondsToCalendarDateTime(Math.ceil(Date.now() / 1_000) + ttl)");
- expect(save).toContain("validateRedisExpiry");
- expect(save).toContain("applyRedisExpiryPolicy");
- expect(save).toContain("toast(errorMessage(error), 3000)");
- expect(viewerSource).toContain('"[data-date-time-picker-content]"');
- expect(viewerSource).toContain('"[data-redis-expiry-mode-content]"');
- expect(viewerSource).toContain('v-model="ttlExpireAt" compact');
- expect(viewerSource.match(/as="button"/g) ?? []).toHaveLength(2);
- expect(viewerSource).toContain(":aria-label=\"t('redis.expiry')\"");
- expect(viewerSource).toContain(":aria-label=\"t('grid.save')\"");
- });
-
- it("moves keyboard focus to the active TTL editor control", () => {
- const start = findFunction(viewerSource, "startEditTtl").getText();
- const focus = findFunction(viewerSource, "focusTtlExpiryControl").getText();
-
- expect(start).toContain("focusTtlExpiryControl()");
- expect(focus).toContain('mode === "ttl"');
- expect(focus).toContain("ttlInputEl.value?.$el?.focus()");
- expect(focus).toContain("[data-slot='select-trigger']");
- expect(focus).toContain("[data-date-time-picker-trigger]");
- expect(viewerSource).toContain("if (editingTtl.value && mode !== previousMode) focusTtlExpiryControl(mode);");
- });
-
- it("serializes expiry saves and preserves unrelated value drafts", () => {
- const save = findFunction(viewerSource, "saveTtl").getText();
- const load = findFunction(viewerSource, "load").getText();
-
- expect(save).toContain("if (savingTtl.value) return;");
- expect(save).toContain("savingTtl.value = true;");
- expect(save).toContain("await refreshTtlState(error);");
- expect(save).toContain("const refreshError = await refreshTtlState();");
- expect(save).toContain("savingTtl.value = false;");
- expect(load).toContain("const preservedValue = { ...currentValue, ttl: loadedValue.ttl };");
- expect(viewerSource).toContain(':disabled="savingTtl"');
- });
-
- it("keeps expiry controls compact and inline in the value header", () => {
- expect(viewerSource).toContain("flex min-w-0 max-w-full flex-wrap items-center gap-1");
- expect(viewerSource).toContain('SelectTrigger size="sm"');
- expect(viewerSource).toContain("max-w-[min(100%,14rem)]");
- expect(viewerSource).toContain('v-model="ttlExpireAt" compact');
- expect(viewerSource).not.toContain("full-width");
- expect(viewerSource).not.toContain("basis-full");
- expect(viewerSource).not.toContain("redis-expiry-mode-trigger");
- expect(viewerSource).not.toContain('class="h-6 w-30 text-xs"');
- });
-
- it("uses the positive-seconds TTL placeholder in both expiration editors", () => {
- const obsoletePlaceholders = {
- en: "empty = no expiry",
- es: "vacío = sin expiración",
- it: "vuoto = senza scadenza",
- ja: "空 = 期限なし",
- "pt-BR": "vazio = sem expiração",
- "zh-CN": "留空表示永不过期",
- "zh-TW": "留空表示永不過期",
- };
-
- for (const [locale, source] of Object.entries(localeSources)) {
- const ttlPlaceholder = source.match(/createKeyTtlPlaceholder: "([^"]+)"/)?.[1];
-
- expect(ttlPlaceholder, locale).toBeDefined();
- expect(source, locale).toContain("createKeyPartialWrite:");
- expect(ttlPlaceholder, locale).not.toBe(obsoletePlaceholders[locale as keyof typeof obsoletePlaceholders]);
- }
- expect(browserSource).toContain("t('redis.createKeyTtlPlaceholder')");
- expect(viewerSource).toContain("t('redis.createKeyTtlPlaceholder')");
- });
-
- it("removes a key that expires while its detail view is refreshing", () => {
- const load = findFunction(viewerSource, "load").getText();
- const deleted = findFunction(browserSource, "onKeyDeleted").getText();
- const loaded = findFunction(browserSource, "onKeyLoaded").getText();
-
- expect(load).toContain('if (loadedValue.redis_type === "none")');
- expect(load).toContain('emit("deleted", props.keyRaw)');
- expect(deleted).toContain("removeKnownKey(keyRaw)");
- expect(loaded).toContain('if (value.redis_type === "none")');
- });
-
- it("reuses the shared expiry validator and the batch transport for one bulk policy", () => {
- const open = findFunction(browserSource, "openBatchExpiryDialog").getText();
- const save = findFunction(browserSource, "saveBatchExpiry").getText();
- const calls = callsIn(findFunction(browserSource, "saveBatchExpiry"));
-
- expect(open).toContain("if (checkedKeys.value.size === 0 || selectionBusy.value) return;");
- expect(open).toContain("batchExpiryKeyRaws.value = [...checkedKeys.value];");
- expect(save).toContain("validateRedisExpiry");
- expect(save).toContain("expiryValidationMessage(validation.reason)");
- expect(calls.map(callName)).toContain("applyRedisBatchExpiryPolicy");
- expect(calls.map(callName)).toContain("applyBatchExpiryMetadata");
- // The single-key API must never be looped over a multi-selection.
- expect(calls.map(callName)).not.toContain("api.redisSetTtl");
- expect(calls.map(callName)).not.toContain("api.redisSetExpireAt");
- expect(calls.map(callName)).not.toContain("applyRedisExpiryPolicy");
- expect(save).toContain("if (savingBatchExpiry.value || batchExpiryKeyRaws.value.length === 0) return;");
- expect(browserSource).toContain("setKeysTtl: api.redisSetKeysTtl");
- expect(browserSource).toContain("setKeysExpireAt: api.redisSetKeysExpireAt");
- // A batch mutation owns the selection like a batch delete does.
- expect(browserSource).toContain("const mutatingKeys = computed(() => deletingKeys.value || savingBatchExpiry.value);");
- expect(findFunction(browserSource, "retainCheckedKeys").getText()).toContain("loadedKeyRaws.has(keyRaw)");
- });
-
- it("updates the loaded TTL badge instead of rescanning every applied key", () => {
- const applyMetadata = findFunction(browserSource, "applyBatchExpiryMetadata").getText();
- const applyTtl = findFunction(browserSource, "applyKeyTtlMetadata").getText();
-
- expect(applyTtl).toContain("updateRedisKeyInfoMetadataByRaw(flatKeyByRaw, nextKeyInfo)");
- expect(applyTtl).toContain("recordKeyTtlObservedAt(nextKeyInfo)");
- expect(applyTtl).toContain("updateRedisKeyTreeLeafMetadata(treeIndex, nextKeyInfo)");
- expect(applyMetadata).toContain('policy.mode === "ttl" ? policy.ttl : -1');
- // EXPIREAT with a past timestamp deletes the key, so the row must not keep a stale TTL.
- expect(applyMetadata).toContain("onKeyDeleted(keyRaw)");
- // One reactive refresh per batch, not one per selected key.
- expect(applyMetadata.match(/noExpiryProjectionEpoch\.value\+\+/g) ?? []).toHaveLength(1);
- expect(applyMetadata.match(/keyMetadataEpoch\.value\+\+/g) ?? []).toHaveLength(1);
- expect(applyMetadata.match(/syncListTtlTimer\(\)/g) ?? []).toHaveLength(1);
- });
-
- it("ships the batch expiration copy in every supported locale", () => {
- for (const [locale, source] of Object.entries(localeSources)) {
- for (const key of ["batchExpiry:", "batchExpiryTitle:", "batchExpirySelected:", "batchExpiryApply:", "batchExpirySuccess:", "batchExpiryPartial:"]) {
- expect(source, `${locale} is missing redis.${key}`).toContain(` ${key}`);
- }
- }
- // The dialog must resolve its copy through i18n instead of hard-coded text.
- expect(browserSource).toContain('t("redis.batchExpiryTitle")');
- expect(browserSource).toContain('t("redis.batchExpirySelected", { count: batchExpiryKeyRaws.length })');
- expect(browserSource).toContain('t("redis.batchExpiryPartial", { success: summary.applied, failed: failed.size })');
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts b/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
index 8bb667a071..2558f11b20 100644
--- a/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
+++ b/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
@@ -1,13 +1,7 @@
-import { readFileSync } from "node:fs";
-import { parse } from "vue/compiler-sfc";
-import ts from "typescript";
import { describe, expect, it } from "vitest";
import { formatRedisMemberDetail, normalizeRedisJsonDraft } from "@/lib/redis/redisValuePresentation";
-const viewerSource = readFileSync(new URL("../../../components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
-const parsedViewer = parse(viewerSource, { filename: "RedisValueViewer.vue" });
-
/** Owner-review fixture: compact save must not drop the second "role" member. */
const DUPLICATE_MEMBER_COMPACT = '{"role":"reader","role":"writer"}';
const DUPLICATE_MEMBER_PRETTY = `{
@@ -15,175 +9,7 @@ const DUPLICATE_MEMBER_PRETTY = `{
"role": "writer"
}`;
-type TemplateElement = {
- type: number;
- tag: string;
- children?: TemplateNode[];
- props: Array<{
- type: number;
- name?: string;
- arg?: { content?: string };
- exp?: { content?: string };
- value?: { content?: string };
- }>;
-};
-
-type TemplateNode = {
- type: number;
- children?: TemplateNode[];
-};
-
-function directiveExpression(element: TemplateElement, name: string, arg?: string): string | undefined {
- return element.props.find((prop) => prop.type === 7 && prop.name === name && (arg == null || prop.arg?.content === arg))?.exp?.content;
-}
-
-function staticAttribute(element: TemplateElement, name: string): string | undefined {
- return element.props.find((prop) => prop.type === 6 && prop.name === name)?.value?.content;
-}
-
-function templateElements(node: TemplateNode): TemplateElement[] {
- const children = (node.children ?? []).flatMap(templateElements);
- return node.type === 1 ? [node as TemplateElement, ...children] : children;
-}
-
-function findTemplateElement(predicate: (element: TemplateElement) => boolean): TemplateElement {
- const template = parsedViewer.descriptor.template;
- expect(parsedViewer.errors).toEqual([]);
- expect(template).toBeDefined();
-
- const element = templateElements(template!.ast as unknown as TemplateElement).find(predicate);
- expect(element).toBeDefined();
- return element!;
-}
-
-function findFunction(name: string): ts.FunctionDeclaration {
- const script = parsedViewer.descriptor.scriptSetup;
- expect(script).toBeDefined();
-
- const source = ts.createSourceFile("RedisValueViewer.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
- const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
- expect(declaration).toBeDefined();
- return declaration!;
-}
-
-function findVariableInitializer(name: string): ts.Expression {
- const script = parsedViewer.descriptor.scriptSetup;
- expect(script).toBeDefined();
-
- const source = ts.createSourceFile("RedisValueViewer.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
- for (const statement of source.statements) {
- if (!ts.isVariableStatement(statement)) continue;
- const declaration = statement.declarationList.declarations.find((candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === name);
- if (declaration?.initializer) return declaration.initializer;
- }
-
- throw new Error(`Expected ${name} to have an initializer`);
-}
-
-function callsIn(node: ts.Node): ts.CallExpression[] {
- const calls: ts.CallExpression[] = [];
- const visit = (child: ts.Node) => {
- if (ts.isCallExpression(child)) calls.push(child);
- ts.forEachChild(child, visit);
- };
- visit(node);
- return calls;
-}
-
-function assignmentsIn(node: ts.Node): ts.BinaryExpression[] {
- const assignments: ts.BinaryExpression[] = [];
- const visit = (child: ts.Node) => {
- if (ts.isBinaryExpression(child) && child.operatorToken.kind === ts.SyntaxKind.EqualsToken) assignments.push(child);
- ts.forEachChild(child, visit);
- };
- visit(node);
- return assignments;
-}
-
-function calledName(call: ts.CallExpression): string | undefined {
- if (ts.isIdentifier(call.expression)) return call.expression.text;
- if (ts.isPropertyAccessExpression(call.expression)) return `${call.expression.expression.getText()}.${call.expression.name.text}`;
- return undefined;
-}
-
describe("native RedisJSON editor", () => {
- it("opens full member values in a centered dialog instead of an app-height side sheet", () => {
- const memberDialog = findTemplateElement((element) => element.tag === "Dialog" && directiveExpression(element, "bind", "open") === "showMemberDetail");
- const memberDetailTags = templateElements(memberDialog).map((element) => element.tag);
- const memberDetailFooter = templateElements(memberDialog).find((element) => element.tag === "DialogFooter");
-
- expect(memberDetailTags).toContain("DialogContent");
- expect(memberDetailTags).toContain("DialogHeader");
- expect(memberDetailTags).toContain("DialogFooter");
- expect(memberDetailTags).not.toContain("SheetContent");
- expect(staticAttribute(memberDetailFooter!, "class")).toContain("mx-0 mb-0");
- expect(viewerSource).not.toContain("memberDetailSheetWidth");
- expect(viewerSource).not.toContain("startResizeMemberSheet");
- });
-
- it("uses the same foldable source editor as JSON strings and hash fields", () => {
- const stringEditor = findTemplateElement((element) => element.tag === "RedisJsonEditor" && directiveExpression(element, "if") === "stringValueView === 'json' && stringValueDetail.json && stringValueCodec === 'none'");
- const nativeJsonBranch = findTemplateElement((element) => directiveExpression(element, "else-if") === "redisKind === 'json'");
- const hashEditor = findTemplateElement((element) => element.tag === "RedisJsonEditor" && directiveExpression(element, "if") === "isEditingHashJson");
- const nativeJsonEditors = templateElements(nativeJsonBranch).filter((element) => element.tag === "RedisJsonEditor");
-
- expect(stringEditor.tag).toBe("RedisJsonEditor");
- expect(hashEditor.tag).toBe("RedisJsonEditor");
- expect(nativeJsonEditors).toHaveLength(1);
-
- const [nativeJsonEditor] = nativeJsonEditors;
- expect(directiveExpression(nativeJsonEditor, "model")).toBe("editValue");
- expect(directiveExpression(nativeJsonEditor, "bind", "save-disabled")).toBe("savingJson || !redisJsonValueChanged");
- expect(directiveExpression(nativeJsonEditor, "bind", "read-only")).toBe("savingJson");
- expect(directiveExpression(nativeJsonEditor, "bind", "word-wrap")).toBe("redisJsonWordWrap");
- expect(directiveExpression(nativeJsonEditor, "on", "save")).toBe("saveJson");
- });
-
- it("does not leave a native RedisJSON tree or textarea rendering branch behind", () => {
- const nativeJsonBranch = findTemplateElement((element) => directiveExpression(element, "else-if") === "redisKind === 'json'");
- const nativeJsonTags = templateElements(nativeJsonBranch).map((element) => element.tag);
-
- expect(nativeJsonTags).not.toContain("JsonTree");
- expect(nativeJsonTags).not.toContain("textarea");
- });
-
- it("validates and compacts native RedisJSON before retaining JSON.SET save semantics", () => {
- const saveJson = findFunction("saveJson");
- const calls = callsIn(saveJson);
- const normalizeCall = calls.find((call) => calledName(call) === "normalizeRedisJsonDraft");
- const redisJsonSetCall = calls.find((call) => calledName(call) === "api.redisJsonSet");
-
- expect(normalizeCall?.arguments.map((argument) => argument.getText())).toEqual(["jsonDraftForSave(redisJsonRawBaseline.value, editValue.value)"]);
- expect(redisJsonSetCall?.arguments.map((argument) => argument.getText())).toEqual(["props.connectionId", "props.db", "props.keyRaw", "normalized.compactText"]);
- });
-
- it("routes string and hash JSON saves through the same source-preserving normalize helper", () => {
- const saveString = findFunction("saveString");
- const saveMemberEdit = findFunction("saveMemberEdit");
- const saveStringText = saveString.getText();
- const saveMemberText = saveMemberEdit.getText();
- const saveStringCalls = callsIn(saveString).map(calledName);
- const saveMemberCalls = callsIn(saveMemberEdit).map(calledName);
-
- // String JSON draft (current tab or retained draft format) compact-writes via SET.
- expect(saveStringText).toContain('stringValueView.value === "json" || stringDraftFormat.value === "json"');
- expect(saveStringCalls).toContain("normalizeRedisJsonDraft");
- expect(saveStringText).toContain("value = normalized.compactText");
- expect(saveStringCalls).toContain("api.redisSetString");
- expect(saveStringText).toMatch(/redisSetString\([\s\S]*\bvalue\b/);
-
- // Hash JSON draft (editor open or retained after leaving JSON tab) compact-writes via the atomic field update.
- expect(saveMemberText).toContain("savingHashJson");
- expect(saveMemberText).toContain('memberDraftFormat.value === "json"');
- expect(saveMemberCalls).toContain("normalizeRedisJsonDraft");
- expect(saveMemberText).toContain("writeValue = normalized.compactText");
- expect(saveMemberCalls).toContain("api.redisHashFieldUpdate");
- expect(saveMemberText).toMatch(/redisHashFieldUpdate\([\s\S]*\bwriteValue\b/);
-
- // Editor pretty baseline also uses the source-preserving formatter.
- expect(findFunction("formatJsonText").getText()).toContain("formatJsonSource");
- });
-
it("string JSON editor open+save keeps duplicate members end-to-end", () => {
// Open: string JSON view pretty baseline comes from formatRedisMemberDetail.
const opened = formatRedisMemberDetail(DUPLICATE_MEMBER_COMPACT, { allowJsonText: true });
@@ -192,11 +18,6 @@ describe("native RedisJSON editor", () => {
// Save: saveString always compact-writes through normalizeRedisJsonDraft.
const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT });
-
- // Wiring: that compact text is what redisSetString receives.
- const saveString = findFunction("saveString");
- expect(saveString.getText()).toContain("value = normalized.compactText");
- expect(callsIn(saveString).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisSetString"]));
});
it("hash JSON editor open+save keeps duplicate members end-to-end", () => {
@@ -207,145 +28,5 @@ describe("native RedisJSON editor", () => {
// Save: saveMemberEdit compact-writes hash JSON drafts through the same helper.
const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT });
-
- // Wiring: hash path only normalizes when savingHashJson, then atomically updates the field with writeValue.
- const saveMemberEdit = findFunction("saveMemberEdit");
- const text = saveMemberEdit.getText();
- expect(text).toContain("if (savingHashJson)");
- expect(text).toContain("writeValue = normalized.compactText");
- expect(callsIn(saveMemberEdit).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisHashFieldUpdate"]));
- });
-
- it("keeps the native editor and export paths on the RedisJSON value-text contract", () => {
- const load = findFunction("load");
- const discard = findFunction("discardRedisJsonEdit");
- const exportStatements = findFunction("generateInsertStatements");
- const valueTextCalls = (node: ts.Node) => callsIn(node).filter((call) => calledName(call) === "redisJsonValueText");
-
- expect(valueTextCalls(load).map((call) => call.arguments.map((argument) => argument.getText()))).toContainEqual(["loadedValue.data"]);
- expect(valueTextCalls(exportStatements).map((call) => call.arguments.map((argument) => argument.getText()))).toContainEqual(["data.value.data"]);
- expect(callsIn(load).map(calledName)).toContain("jsonDraftPairForEditor");
- expect(callsIn(load).map(calledName)).toContain("redisJsonValueText");
- expect(assignmentsIn(load).some((assignment) => assignment.left.getText() === "redisJsonRawBaseline.value" && assignment.right.getText() === "pair.rawBaseline")).toBe(true);
- expect(assignmentsIn(load).some((assignment) => assignment.left.getText() === "redisJsonDraftBaseline.value" && assignment.right.getText() === "pair.displayBaseline")).toBe(true);
- expect(assignmentsIn(discard).some((assignment) => assignment.left.getText() === "editValue.value" && assignment.right.getText() === "redisJsonDraftBaseline.value")).toBe(true);
-
- for (const node of [load, discard, exportStatements]) {
- expect(callsIn(node).map(calledName)).not.toContain("JSON.stringify");
- }
- expect(viewerSource).not.toContain("isRedisJsonDraftDirty");
- });
-
- it("keeps retained drafts out of background refresh and exposes word wrap for every JSON editor", () => {
- const refreshAutoValue = findFunction("refreshAutoValue");
- const collectionSearch = findFunction("onCollectionSearch");
- const viewMember = findFunction("viewMember");
- const setMemberValueFormat = findFunction("setMemberValueFormat");
- const selectMember = findFunction("selectMember");
- const startEditMember = findFunction("startEditMember");
- const saveMemberEdit = findFunction("saveMemberEdit");
- const memberValueChanged = findVariableInitializer("memberValueChanged");
- const memberFieldChanged = findVariableInitializer("memberFieldChanged");
- const unsavedDraft = findVariableInitializer("hasUnsavedRedisDraft");
- const textFormat = findFunction("isTextRedisFormat");
- const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement);
- const stringTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "editValue");
- const memberTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "memberEditValue");
- const refreshButton = findTemplateElement((element) => element.tag === "Button" && element.props.some((prop) => prop.type === 6 && prop.name === "data-redis-value-refresh"));
-
- expect(refreshAutoValue.getText().match(/hasUnsavedRedisDraft\.value/g)).toHaveLength(2);
- expect(collectionSearch.getText()).toContain("if (!hasRetainedMemberDraft.value) clearSelectedMember();");
- expect(viewMember.getText()).toContain("hasRetainedMemberDraft.value");
- // Clean JSON → other format must clear memberDraftFormat so rawText is not compared to the pretty baseline.
- expect(setMemberValueFormat.getText()).toContain("memberDraftFormat.value = null");
- expect(setMemberValueFormat.getText()).toContain('memberDraftFormat.value = "utf8"');
- expect(unsavedDraft.getText()).toContain("hasRetainedStringDraft.value");
- expect(unsavedDraft.getText()).toContain("hasRetainedMemberDraft.value");
- expect(unsavedDraft.getText()).toContain("memberFieldChanged.value");
- expect(memberFieldChanged.getText()).toContain("memberFieldDraftBaseline.value");
- expect(memberValueChanged.getText()).toContain("memberFieldChanged.value");
- expect(selectMember.getText()).toContain("memberFieldDraftBaseline.value");
- expect(startEditMember.getText()).toContain("!memberFieldChanged.value");
- expect(saveMemberEdit.getText()).toContain("memberFieldEditValue.value");
- expect(saveMemberEdit.getText()).not.toContain("memberFieldEditValue.value.trim()");
- expect(viewerSource).toContain(':disabled="savingMember || !memberValueChanged"');
- expect(textFormat.getText()).toContain('format === "json"');
- expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec)")).toBe(true);
- expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)")).toBe(true);
- expect(directiveExpression(stringTextarea, "bind", "readonly")).toBe("!canEditCurrentStringFormat || savingString");
- expect(directiveExpression(memberTextarea, "bind", "readonly")).toBe("savingMember");
- expect(directiveExpression(refreshButton, "bind", "disabled")).toBe("loading || refreshingValue || hasUnsavedRedisDraft");
- });
-
- it("passes the loaded ZSet score into both update entry points", () => {
- const inlineSave = findFunction("saveZsetInlineEdit").getText();
- const detailSave = findFunction("saveMemberEdit").getText();
-
- expect(inlineSave).toContain("originalMember, item.score, zsetInlineMember.value, scoreText");
- expect(detailSave).toContain("context.member, context.score, writeValue, context.score");
- });
-});
-
-describe("Redis JSON unicode display mode", () => {
- it("exposes a raw/decoded toggle on every JSON editor surface", () => {
- // String JSON, native RedisJSON, and member JSON edit surfaces each render
- // the same two-segment "原始 / 解码" control wired to setRedisJsonUnicodeMode.
- expect(viewerSource.match(/setRedisJsonUnicodeMode\('raw'\)/g)).toHaveLength(3);
- expect(viewerSource.match(/setRedisJsonUnicodeMode\('decoded'\)/g)).toHaveLength(3);
- expect(viewerSource.match(/t\("redis\.jsonViewRaw"\)/g)).toHaveLength(3);
- expect(viewerSource.match(/t\("redis\.jsonViewDecoded"\)/g)).toHaveLength(3);
- });
-
- it("defaults to decoded and persists the choice under its own storage key", () => {
- expect(findFunction("readRedisJsonUnicodeMode").getText()).toContain('=== "raw" ? "raw" : "decoded"');
- expect(findVariableInitializer("redisJsonUnicodeMode").getText()).toBe("ref(readRedisJsonUnicodeMode())");
- expect(viewerSource).toContain('const REDIS_JSON_UNICODE_MODE_STORAGE_KEY = "dbx-redis-json-unicode-mode"');
- });
-
- it("derives JSON editor baselines through the display-only unicode decode", () => {
- expect(findFunction("formatJsonText").getText()).toContain("decodeJsonUnicodeEscapes(formatted)");
- expect(findFunction("jsonDraftBaseline").getText()).toContain("decodeJsonUnicodeEscapes(formattedText)");
- expect(findFunction("jsonDraftPairForEditor").getText()).toContain("jsonDraftBaseline(rawBaseline, redisJsonDecoded.value)");
- expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("rememberRedisJsonUnicodeMode(mode)");
- expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("stringJsonDraftBaseline.value = jsonDraftBaseline(stringJsonRawBaseline.value, decoded)");
- expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("redisJsonDraftBaseline.value = jsonDraftBaseline(redisJsonRawBaseline.value, decoded)");
- expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("memberJsonDraftBaseline.value = jsonDraftBaseline(memberJsonRawBaseline.value, decoded)");
- });
-
- it("converts the active draft across a Raw/Decoded toggle instead of resetting it", () => {
- // Toggling must not drop unsaved edits: the draft goes through the mode
- // transform (decode when entering decoded, map back to raw when leaving it).
- expect(findFunction("convertJsonDraftAcrossMode").getText()).toContain("decoded ? decodeJsonUnicodeEscapes(draft) : mapDisplayToRaw(rawBaseline, draft)");
-
- const setMode = findFunction("setRedisJsonUnicodeMode").getText();
- expect(setMode).toContain("editValue.value = convertJsonDraftAcrossMode(editValue.value, stringJsonRawBaseline.value, decoded)");
- expect(setMode).toContain("editValue.value = convertJsonDraftAcrossMode(editValue.value, redisJsonRawBaseline.value, decoded)");
- expect(setMode).toContain("memberEditValue.value = convertJsonDraftAcrossMode(memberEditValue.value, memberJsonRawBaseline.value, decoded)");
- // The reset-to-baseline assignments must not reappear; they drop unsaved edits.
- expect(setMode).not.toContain("editValue.value = stringJsonDraftBaseline.value");
- expect(setMode).not.toContain("editValue.value = redisJsonDraftBaseline.value");
- expect(setMode).not.toContain("memberEditValue.value = memberJsonDraftBaseline.value");
- });
-
- it("routes every JSON editor save through the raw draft mapping so escapes are preserved", () => {
- // Save writes the mapped canonical raw draft, never the decoded display text:
- // opening {"name":"张"} in decoded mode and saving must store the escape.
- const jsonDraftForSave = findFunction("jsonDraftForSave");
- expect(jsonDraftForSave.getText()).toContain("mapDisplayToRaw(rawBaseline, displayValue)");
- expect(jsonDraftForSave.getText()).toContain("redisJsonDecoded.value ? mapDisplayToRaw(rawBaseline, displayValue) : displayValue");
-
- // String JSON draft, native RedisJSON, and hash member JSON draft all go
- // through jsonDraftForSave before the source-preserving normalize/compact.
- const saveString = findFunction("saveString").getText();
- const saveJson = findFunction("saveJson").getText();
- const saveMemberEdit = findFunction("saveMemberEdit").getText();
- expect(saveString).toContain("normalizeRedisJsonDraft(jsonDraftForSave(stringJsonRawBaseline.value, value))");
- expect(saveJson).toContain("normalizeRedisJsonDraft(jsonDraftForSave(redisJsonRawBaseline.value, editValue.value))");
- expect(saveMemberEdit).toContain("normalizeRedisJsonDraft(jsonDraftForSave(memberJsonRawBaseline.value, writeValue))");
-
- // Raw baselines (what saves write back to) are captured on load/select.
- expect(findFunction("load").getText()).toContain('stringJsonRawBaseline.value = detail.json?.formattedText ?? ""');
- expect(findFunction("load").getText()).toContain("const pair = jsonDraftPairForEditor(redisJsonValueText(loadedValue.data))");
- expect(findFunction("selectMember").getText()).toContain('memberJsonRawBaseline.value = detail.json?.formattedText ?? ""');
});
});
diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarFilterGuards.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarFilterGuards.spec.ts
index d9b048c29f..8fd7181339 100644
--- a/apps/desktop/src/lib/__tests__/sidebar/sidebarFilterGuards.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarFilterGuards.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveSidebarFilterGuards } from "@/lib/sidebar/sidebarSearchTree";
@@ -18,18 +17,4 @@ describe("sidebar filter guards", () => {
isRootListPartial: rootPartial,
});
});
-
- it("keeps descendant-local features separate from partial-root operations", () => {
- const source = readFileSync(new URL("../../../components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
-
- expect(source).toContain("sidebarTableSearchEnabled && !isTreeSearchFiltering.value");
- expect(source).toContain("!useVirtualTree.value || isTreeSearchFiltering.value");
- expect(source.match(/if \(isRootListPartial\.value\)/g)).toHaveLength(2);
- // Alphabetical sort only suppresses before/after position reordering (the manual
- // order it would act on is invisible while sorted); moving a connection into a
- // different group stays available so drag stays usable while sorted (#6669).
- expect(source.match(/:reorder-disabled="isRootListPartial"/g)).toHaveLength(2);
- expect(source.match(/:move-to-group-only="isConnectionListAlphabeticallySorted"/g)).toHaveLength(2);
- expect(source).not.toContain("isFiltering");
- });
});
diff --git a/apps/desktop/src/lib/__tests__/sql/dorisCatalogCompletion.spec.ts b/apps/desktop/src/lib/__tests__/sql/dorisCatalogCompletion.spec.ts
deleted file mode 100644
index b869e58ca8..0000000000
--- a/apps/desktop/src/lib/__tests__/sql/dorisCatalogCompletion.spec.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-const queryEditorPropsSource = readFileSync(new URL("../../../components/editor/queryEditorTypes.ts", import.meta.url), "utf8");
-const completionSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletion.ts", import.meta.url), "utf8");
-const metadataSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
-const sidebarRuntimeSource = readFileSync(new URL("../../../components/sidebar/SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
-const openTabsPersistenceSource = readFileSync(new URL("../../app/openTabsPersistence.ts", import.meta.url), "utf8");
-
-describe("Doris external catalog completion wiring", () => {
- it("preserves the selected catalog from the sidebar query action into QueryEditor", () => {
- expect(sidebarRuntimeSource).toContain('queryStore.createTab(node.connectionId, node.database, undefined, "query", node.schema, undefined, node.catalog)');
- expect(contentAreaSource).toContain(':catalog="activeTab.catalog"');
- expect(queryEditorSource).toContain("defineProps<QueryEditorProps>()");
- expect(queryEditorPropsSource).toContain("catalog?: string;");
- expect(openTabsPersistenceSource).toContain("catalog: tab.catalog");
- });
-
- it("includes catalog scope in table and column completion requests", () => {
- expect(completionSource).toMatch(/lookupLocalCompletionTables\([\s\S]*?props\.catalog/);
- expect(completionSource).toMatch(/listCompletionTables\([\s\S]*?props\.catalog/);
- expect(metadataSource).toMatch(/listCompletionColumns\([\s\S]*?catalog\)/);
- expect(queryEditorSource).toMatch(/watch\(\s*\(\) => props\.catalog,[\s\S]*?refreshCompletionCache\(\)/);
- expect(completionSource).toMatch(/function shouldLoadCompletionObjects[\s\S]*?if \(props\.catalog\) return false/);
- expect(completionSource).toMatch(/if \(!props\.catalog && props\.databaseType !== "oracle"[\s\S]*?listCompletionObjects/);
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/sql/oracleCompletionSession.spec.ts b/apps/desktop/src/lib/__tests__/sql/oracleCompletionSession.spec.ts
index 73c6508799..e06e567c84 100644
--- a/apps/desktop/src/lib/__tests__/sql/oracleCompletionSession.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/oracleCompletionSession.spec.ts
@@ -1,10 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { usesOracleSessionCompletionColumns } from "@/lib/sql/oracleCompletionSession";
-const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
-const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-
describe("Oracle session-scoped completion", () => {
it("uses the tab session only for unqualified references without a selected schema", () => {
expect(usesOracleSessionCompletionColumns({ databaseType: "oracle", clientSessionId: "tab-a" })).toBe(true);
@@ -16,10 +12,4 @@ describe("Oracle session-scoped completion", () => {
expect(usesOracleSessionCompletionColumns({ databaseType: "postgres", clientSessionId: "tab-a" })).toBe(false);
expect(usesOracleSessionCompletionColumns({ databaseType: "oracle" })).toBe(false);
});
-
- it("passes tab context into QueryEditor and clears local caches when the tab or context changes", () => {
- expect(contentAreaSource).toContain(':client-session-id="activeTab.id"');
- expect(contentAreaSource).toContain(':completion-context-version="activeTab.completionContextVersion"');
- expect(queryEditorSource).toMatch(/watch\(\s*\[\(\) => props\.clientSessionId, \(\) => props\.completionContextVersion\][\s\S]*?refreshCompletionCache\(\)/);
- });
});
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
index b04edee1d6..6f1f24e3c1 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
@@ -1,16 +1,8 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { canFormatSqlForDatabaseType, formatSqlForDisplay, formatSqlForEditing, formatSqlText, MAX_SQL_FORMAT_CHARS, sqlFormatDialectForDbType, UnsupportedStructuredInputError } from "@/lib/sql/sqlFormatter";
import { extractSqlParameters } from "@/lib/sql/sqlParameters";
-const sqlFormatterSource = readFileSync(new URL("../../sql/sqlFormatter.ts", import.meta.url), "utf8");
-
describe("sqlFormatter", () => {
- it("does not use lookbehind regular expressions in the startup path", () => {
- expect(sqlFormatterSource).not.toContain("(?<!");
- expect(sqlFormatterSource).not.toContain("(?<=");
- });
-
it("disables SQL formatting for Redis and VictoriaMetrics queries", () => {
expect(canFormatSqlForDatabaseType("redis")).toBe(false);
expect(canFormatSqlForDatabaseType("victoriametrics")).toBe(false);
diff --git a/apps/desktop/src/lib/__tests__/table/contentAreaObjectBrowserCatalog.spec.ts b/apps/desktop/src/lib/__tests__/table/contentAreaObjectBrowserCatalog.spec.ts
deleted file mode 100644
index ab03dfd83c..0000000000
--- a/apps/desktop/src/lib/__tests__/table/contentAreaObjectBrowserCatalog.spec.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-const connectionTreeSource = readFileSync(new URL("../../../components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
-const ddlViewDialogSource = readFileSync(new URL("../../../components/objects/DdlViewDialog.vue", import.meta.url), "utf8");
-const objectBrowserSource = readFileSync(new URL("../../../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
-const fetchTableDdlSource = objectBrowserSource.match(/async function fetchTableDdl(?:\([^)]*\))?[\s\S]*?(?=\nasync function fetchTableColumns\()/)?.[0] ?? "";
-const exportStructureSource = objectBrowserSource.match(/async function exportStructure\([\s\S]*?(?=\nasync function exportDataLegacy\()/)?.[0] ?? "";
-
-function openingTag(source: string, componentName: string): string {
- return source.match(new RegExp(`<${componentName}\\b[\\s\\S]*?>`))?.[0] ?? "";
-}
-
-describe("ContentArea external catalog wiring", () => {
- it("passes the object browser catalog to ObjectBrowser", () => {
- expect(openingTag(contentAreaSource, "ObjectBrowser")).toContain(':catalog="activeTab.objectBrowser?.catalog"');
- });
-
- it("does not attach object browser state to DataGrid", () => {
- expect(openingTag(contentAreaSource, "DataGrid")).not.toContain("activeTab.objectBrowser?.catalog");
- });
-
- it("passes the sidebar catalog to the DDL dialog", () => {
- expect(openingTag(connectionTreeSource, "SidebarDdlViewDialog")).toContain(':catalog="sidebarDdlTarget.catalog"');
- });
-
- it("forwards the DDL dialog catalog to the persistent DDL loader", () => {
- expect(ddlViewDialogSource).toMatch(/loadObjectDdl\([\s\S]*?objectType: props\.objectType,[\s\S]*?catalog: props\.catalog/);
- });
-});
-
-describe("ContentArea object browser refresh wiring", () => {
- it("routes content refresh through the ObjectBrowser handle", () => {
- expect(contentAreaSource).toContain('if (props.activeTab.mode === "objects") return objectBrowserRef.value?.refresh?.() ?? false;');
- });
-
- it("exposes object and active table-info reloads as refresh", () => {
- expect(objectBrowserSource).toMatch(/function refresh\(\): boolean \{\s+void reload\(\{ preserveExistingRows: true \}\);\s+void refreshActiveTableInfo\(\);\s+return true;\s+\}/);
- expect(objectBrowserSource).toContain("defineExpose({ focusSearch, refresh, matchesRefreshScope });");
- });
-
- it("shows the configured content refresh shortcut on the refresh button", () => {
- expect(objectBrowserSource).toContain("formatShortcut(settingsStore.editorSettings.shortcuts.refreshData)");
- expect(objectBrowserSource).toMatch(/<Button[^>]*:title="refreshTooltip"[^>]*@click="refresh">/);
- });
-});
-
-describe("ObjectBrowser DDL API boundaries", () => {
- it("uses the cached display DDL boundary for the table information panel", () => {
- expect(fetchTableDdlSource).toMatch(/loadObjectDdl\(tableMetadataRequest\(row\), \{ force \}\)/);
- expect(objectBrowserSource).toMatch(/function tableMetadataRequest\([\s\S]*?catalog: props\.catalog/);
- });
-
- it("keeps structure exports on the portable base DDL", () => {
- expect(exportStructureSource).toMatch(/api\.getTableDdl\([\s\S]*?props\.catalog, true\);/);
- expect(exportStructureSource).not.toContain("api.getTableDisplayDdl(");
- });
-});
diff --git a/apps/desktop/src/lib/__tests__/table/objectBrowserContextWatch.spec.ts b/apps/desktop/src/lib/__tests__/table/objectBrowserContextWatch.spec.ts
index fc84e6707f..3107278d29 100644
--- a/apps/desktop/src/lib/__tests__/table/objectBrowserContextWatch.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/objectBrowserContextWatch.spec.ts
@@ -1,29 +1,7 @@
-import { readFileSync } from "node:fs";
import { nextTick, ref, watch } from "vue";
import { describe, expect, it } from "vitest";
-const objectBrowserSource = readFileSync(new URL("../../../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
-
describe("ObjectBrowser context watcher", () => {
- it("watches context fields independently", () => {
- expect(objectBrowserSource).toContain("[() => props.connection.id, () => props.database, () => props.schema]");
- expect(objectBrowserSource).not.toContain("() => [props.connection.id, props.database, props.schema]");
- });
-
- it("invalidates object requests before waiting for the new connection", () => {
- const watcher = objectBrowserSource.match(/watch\(\s*\[\(\) => props\.connection\.id[\s\S]*?\{ immediate: true \},\s*\);/)?.[0] ?? "";
-
- expect(watcher).toContain("const contextEpoch = objectBrowserRowsLoadGuard.invalidate();");
- expect(watcher.indexOf("objectBrowserRowsLoadGuard.invalidate()")).toBeLessThan(watcher.indexOf("await connectionStore.ensureConnected"));
- expect(watcher).toContain("reload({ allowCachedObjects: true, contextEpoch })");
- });
-
- it("loads MongoDB collections through the existing objects view", () => {
- expect(objectBrowserSource).toContain("api.mongoListCollections");
- expect(objectBrowserSource).toContain("buildMongoObjectBrowserRows");
- expect(objectBrowserSource).toContain("objects.searchCollections");
- });
-
it("ignores connection object replacement when the context values stay unchanged", async () => {
const connection = ref({ id: "connection-1" });
const database = ref("database-1");
diff --git a/apps/desktop/src/lib/ai/__tests__/aiPromptSubmission.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiPromptSubmission.spec.ts
index 057c4db829..1888d62392 100644
--- a/apps/desktop/src/lib/ai/__tests__/aiPromptSubmission.spec.ts
+++ b/apps/desktop/src/lib/ai/__tests__/aiPromptSubmission.spec.ts
@@ -1,9 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { canSubmitAiPrompt } from "@/lib/ai/aiPromptKeyboard";
-const aiAssistantSource = readFileSync(new URL("../../../components/editor/AiAssistant.vue", import.meta.url), "utf8");
-
function submissionState(overrides: Partial<Parameters<typeof canSubmitAiPrompt>[0]> = {}) {
return {
prompt: "",
@@ -27,10 +24,4 @@ describe("AI prompt submission eligibility", () => {
expect(canSubmitAiPrompt(submissionState({ prompt: "ask", hasTab: false }))).toBe(false);
expect(canSubmitAiPrompt(submissionState({ prompt: "ask", hasConnection: false }))).toBe(false);
});
-
- it("wires the click button to the shared eligibility rule", () => {
- expect(aiAssistantSource).toContain("const canSubmitPrompt = computed(() =>");
- expect(aiAssistantSource).toContain(':disabled="!canSubmitPrompt"');
- expect(aiAssistantSource).not.toMatch(/:disabled=.*props\.tab\?\.database/);
- });
});
diff --git a/apps/desktop/src/lib/ai/__tests__/aiRedisConsoleRouting.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiRedisConsoleRouting.spec.ts
index a1eb7c081a..2c3a3f3888 100644
--- a/apps/desktop/src/lib/ai/__tests__/aiRedisConsoleRouting.spec.ts
+++ b/apps/desktop/src/lib/ai/__tests__/aiRedisConsoleRouting.spec.ts
@@ -2,45 +2,11 @@ import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";
-const aiAssistantSource = readFileSync(new URL("../../../components/editor/AiAssistant.vue", import.meta.url), "utf8");
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
const redisBrowserSource = readFileSync(new URL("../../../components/redis/RedisKeyBrowser.vue", import.meta.url), "utf8");
describe("AI Redis console routing", () => {
- it("routes Redis insert and execute actions to the active Redis console", () => {
- // Every action carries the conversation's bound connection (#9902); the
- // console refuses a target that is not the visible tab.
- expect(aiAssistantSource).toContain('emit("insertRedisCommand", code, conversationBinding.value)');
- expect(aiAssistantSource).toContain('emit("executeRedisCommand", code, conversationBinding.value)');
- expect(aiAssistantSource).toContain("seg.isSql || isRedisConnection");
- expect(appSource).toContain("if (routeAiRedisCommand(sql, false, target)) return;");
- expect(appSource).toContain("if (routeAiRedisCommand(sql, true, target)) return;");
- expect(contentAreaSource).toContain("if (!isRedisConsoleReady(target)) return false;");
- expect(contentAreaSource).toContain("redisKeyBrowserRef.value?.executeCommand?.(command)");
- });
-
- it("keeps the existing SQL editor and execution behavior for non-Redis connections", () => {
- expect(aiAssistantSource).toContain('emit("appendSql", code, conversationBinding.value)');
- expect(aiAssistantSource).toContain('emit("executeSql", code, conversationBinding.value)');
- expect(aiAssistantSource).toContain('emit("tempRunSql", code, conversationBinding.value)');
- // The target tab is resolved from the bound connection, never from the tab
- // that happens to be active (#9902).
- expect(appSource).toContain("const tabId = ensureQueryTabForConnection(target);");
- expect(appSource).not.toContain("function ensureQueryTab()");
- expect(appSource).toContain("buildDeduplicatedAppendedEditorSql(currentSql, sql)");
- expect(appSource).toContain("buildAppendedEditorSql(aiTargetTabSql(tabId), sql)");
- expect(appSource).toContain("const decision = classifyAiSqlExecution(sql, connection);");
- });
-
- it("deduplicates immediate-run editor writes without skipping execution", () => {
- const handler = appSource.match(/function onAiExecuteSql\(sql: string, target: AiConversationBinding\) \{[\s\S]*?\n\}/)?.[0] ?? "";
- expect(handler).toContain("buildDeduplicatedAppendedEditorSql(currentSql, sql)");
- expect(handler).toContain("if (appendedSql !== currentSql) queryStore.updateSql(tabId, appendedSql);");
- expect(handler).toContain("runAiGeneratedSql(sql, tabId);");
- expect(handler).not.toContain("buildAppendedEditorSql(");
- });
-
it("refuses a Redis command rather than moving the workspace to the bound console", () => {
// "An AI action never moves the workspace" is the point of #9902. The bound
// console is driven only when it is already the visible tab; otherwise the
@@ -57,39 +23,6 @@ describe("AI Redis console routing", () => {
expect(appSource).toContain('toast(t("ai.redisConsoleUnreachable"), 5000);');
});
- it("still drives the bound console when it is the visible tab", () => {
- // The refusal above must not disable the working case: readiness means the
- // on-screen console belongs to the bound connection.
- expect(contentAreaSource).toContain("isAiRedisConsoleTarget(props.activeTab, target)");
- const start = appSource.indexOf("async function deliverRedisAiCommand");
- const deliver = appSource.slice(start, appSource.indexOf("function aiTargetTabSql", start));
- expect(deliver).toContain("contentAreaRef.value?.executeRedisCommand(command, target)");
- expect(deliver).toContain("contentAreaRef.value?.insertRedisCommand(command, target)");
- });
-
- it("waits for the console to mount without re-issuing the command", () => {
- const start = appSource.indexOf("async function deliverRedisAiCommand");
- expect(start).toBeGreaterThanOrEqual(0);
- const deliver = appSource.slice(start, appSource.indexOf("\n}", start));
-
- // Readiness is polled through a side-effect-free probe...
- const probeIdx = deliver.indexOf("isRedisConsoleReady(target)");
- expect(probeIdx).toBeGreaterThanOrEqual(0);
- expect(deliver).toContain("REDIS_CONSOLE_READY_TIMEOUT_MS");
- // ...and the single route attempt happens only after the wait, so a command
- // that ran but reported false (e.g. awaiting confirmation) cannot run twice.
- const routeIdx = deliver.indexOf("executeRedisCommand(command, target)");
- expect(routeIdx).toBeGreaterThan(probeIdx);
-
- // The probe itself must not execute anything.
- const probeStart = contentAreaSource.indexOf("function isRedisConsoleReady");
- expect(probeStart).toBeGreaterThanOrEqual(0);
- const probe = contentAreaSource.slice(probeStart, contentAreaSource.indexOf("\n}", probeStart));
- expect(probe).toContain("isAiRedisConsoleTarget(props.activeTab, target) && !!redisKeyBrowserRef.value");
- expect(probe).not.toContain("executeCommand");
- expect(probe).not.toContain("insertCommand");
- });
-
it("uses the console safety path and rejects unavailable command input", () => {
expect(classifyRedisCommandSafety("CONFIG SET requirepass secret")).toBe("blocked");
expect(classifyRedisCommandSafety("FLUSHDB")).toBe("confirm");
@@ -117,16 +50,4 @@ describe("AI Redis console routing", () => {
expect(anyBlocked).toBe(true);
}
});
-
- it("tells the user when the bound Redis console cannot be reached", () => {
- // A console.warn is invisible in a desktop app, and the command the user
- // asked for is not going to run — silence is the worst outcome.
- // Sliced between two anchors: writing an escaped newline in a source anchor
- // is fragile, and this pair is unambiguous.
- const start = appSource.indexOf("async function deliverRedisAiCommand");
- const deliver = appSource.slice(start, appSource.indexOf("function aiTargetTabSql", start));
- expect(deliver).toContain('toast(t("ai.redisConsoleUnreachable"), 5000);');
- // Both failure paths (mount timeout, command rejected) report.
- expect(deliver.split('toast(t("ai.redisConsoleUnreachable")').length - 1).toBe(2);
- });
});
diff --git a/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts b/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts
index 2627469761..1b6914b3df 100644
--- a/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts
+++ b/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts
@@ -1,13 +1,9 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CODE_SNAPSHOT_CSS, materializeSnapshotCloneLineNumbers, renderCodeSnapshotHtml, savePngDataUrlToFile, snapshotElementToPng } from "@/lib/codeSnapshot/codeSnapshot";
import { LEGACY_WEBVIEW_CLASS } from "@/lib/ui/legacyWebView";
-const codeSnapshotDialogSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/codeSnapshot/CodeSnapshotDialog.vue"), "utf8");
-
const { createCodeHighlighter, highlightCode, toPng, isTauriRuntime, save, writeFile } = vi.hoisted(() => {
const highlightCode = vi.fn((content: string, _lang: string) => `<span class="line">${content}</span>`);
return {
@@ -199,12 +195,6 @@ describe("renderCodeSnapshotHtml", () => {
expect(html).toContain("padding:0 24px 24px");
});
- it("keeps the snapshot dialog responsive layout classes in source", () => {
- expect(codeSnapshotDialogSource).toContain("sm:max-w-[860px]");
- expect(codeSnapshotDialogSource).toContain("md:flex-row");
- expect(codeSnapshotDialogSource).toContain("md:w-52");
- });
-
it("materializes real line-number nodes in the export clone", () => {
document.body.innerHTML = '<div class="dbx-code-snapshot"><pre class="dbx-code-snapshot__pre dbx-code-snapshot__pre--numbered"><code><span class="line">SELECT 1</span><span class="line">FROM dual</span></code></pre></div>';
const root = document.body.firstElementChild as HTMLElement;
diff --git a/apps/desktop/src/lib/diagram/__tests__/fieldLineage.spec.ts b/apps/desktop/src/lib/diagram/__tests__/fieldLineage.spec.ts
index 64c0e9e57a..19db9a08ab 100644
--- a/apps/desktop/src/lib/diagram/__tests__/fieldLineage.spec.ts
+++ b/apps/desktop/src/lib/diagram/__tests__/fieldLineage.spec.ts
@@ -1,9 +1,6 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { identifierInSql } from "@/lib/diagram/fieldLineage";
-const fieldLineageSource = readFileSync(new URL("../fieldLineage.ts", import.meta.url), "utf8");
-
describe("identifierInSql", () => {
it("matches unquoted identifiers at the start or after punctuation", () => {
expect(identifierInSql("customer_id = 1", "customer_id")).toBe(true);
@@ -23,8 +20,4 @@ describe("identifierInSql", () => {
expect(identifierInSql("SELECT `customer_id`", "customer_id")).toBe(true);
expect(identifierInSql("SELECT [customer_id]", "customer_id")).toBe(true);
});
-
- it("does not use runtime lookbehind in the legacy WebView path", () => {
- expect(fieldLineageSource).not.toContain("(?<");
- });
});
diff --git a/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts b/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
index 92cfcbeb93..8a70766024 100644
--- a/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
EDITOR_SETTINGS_DRAFT_KEYS,
@@ -12,8 +11,6 @@ import {
} from "../editorSettingsDraft";
import type { EditorSettings } from "@/stores/settingsStore";
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
function makeSettings(overrides: Partial<EditorSettings> = {}): EditorSettings {
return {
autoCalculateTotalRows: false,
@@ -143,16 +140,6 @@ describe("EDITOR_SETTINGS_DRAFT_KEYS", () => {
});
});
-describe("cell detail button settings control", () => {
- it("binds the switch through apply and both reset paths", () => {
- expect(settingsDialogSource).toContain("const editDataGridCellDetailButtonVisible = ref(settingsStore.editorSettings.dataGridCellDetailButtonVisible)");
- expect(settingsDialogSource).toContain("dataGridCellDetailButtonVisible: editDataGridCellDetailButtonVisible.value");
- expect(settingsDialogSource).toContain("editDataGridCellDetailButtonVisible.value = settingsStore.editorSettings.dataGridCellDetailButtonVisible");
- expect(settingsDialogSource.match(/editDataGridCellDetailButtonVisible\.value = DEFAULT_EDITOR_SETTINGS\.dataGridCellDetailButtonVisible/g)).toHaveLength(2);
- expect(settingsDialogSource).toContain('id="data-grid-cell-detail-button-visible" v-model="editDataGridCellDetailButtonVisible"');
- });
-});
-
describe("editorSettingsDraftFromSettings", () => {
it("round-trips a hidden line-number preference through the draft patch", () => {
const settings = makeSettings({ showLineNumbers: true });
@@ -504,13 +491,4 @@ describe("editorSettingsDraftPatchFromSettings", () => {
const patch = editorSettingsDraftPatchFromSettings({ pageSize: 999999 } as Partial<EditorSettings>);
expect(patch.pageSize).toBe(normalizeTableOpenPageSizeDraft(999999));
});
-
- it("is the base for the settings import path in the dialog", () => {
- // The import must patch only imported keys into the edit refs; rebuilding
- // the whole draft would drop unsaved state the file does not cover (e.g. a
- // half-filled table-column template row, which serialization drops).
- expect(settingsDialogSource).toContain("const patch = editorSettingsDraftPatchFromSettings(imported);");
- expect(settingsDialogSource).toContain("applyEditorSettingsKeysToRefs(patch as EditorSettingsDraft, Object.keys(patch) as EditorSettingsDraftKey[]);");
- expect(settingsDialogSource).not.toContain("const merged = editorSettingsDraftFromSettings({");
- });
});
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts
deleted file mode 100644
index 73dbc60750..0000000000
--- a/apps/desktop/src/lib/settings/__tests__/settingsPageNavigation.spec.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
-describe("settings page navigation", () => {
- it("keeps query, settings, and driver-manager surfaces mutually exclusive", () => {
- expect(appSource).toContain('type MainContentSurface = "query" | "settings" | "driverStore" | "pluginCenter";');
- expect(appSource).toMatch(/function activateMainContentSurface\(surface: MainContentSurface\) \{\s*settingsStore\.settingsPageActive = surface === "settings";\s*driverStoreActive\.value = surface === "driverStore";\s*pluginCenterActive\.value = surface === "pluginCenter";/);
- expect(appSource).toMatch(/function activateSettingsPage\(\) \{\s*settingsPageTabOpen\.value = true;\s*activateMainContentSurface\("settings"\);/);
- expect(appSource).toMatch(/function activateQuerySurface\(\) \{\s*activateMainContentSurface\("query"\);/);
- expect(appSource).toMatch(/driverStoreTabOpen\.value = true;\s*activateMainContentSurface\("driverStore"\);/);
- });
-
- it("replays repeated navigation requests for the same tab", () => {
- expect(appSource).toContain("settingsNavigationRequestId.value += 1");
- expect(appSource).toContain(':navigation-request-id="settingsNavigationRequestId"');
- expect(settingsDialogSource).toContain("navigationRequestId?: number;");
- expect(settingsDialogSource).toMatch(/watch\(\s*\(\) => props\.navigationRequestId,/);
- });
-
- it("routes AI configuration drafts into the unsaved new-config form", () => {
- const handlerStart = settingsDialogSource.indexOf("async function applyPendingAiConfigDeepLinkDraft()");
- const handlerEnd = settingsDialogSource.indexOf("async function aiSaveConfig()", handlerStart);
- const handlerSource = settingsDialogSource.slice(handlerStart, handlerEnd);
-
- expect(appSource).toContain('openSettings("ai")');
- expect(appSource).toContain(':ai-config-draft="settingsAiConfigDraft"');
- expect(appSource).toContain(':ai-config-request-id="settingsAiConfigRequestId"');
- expect(settingsDialogSource).toContain("aiEnterEditMode();");
- expect(handlerSource).toContain("aiEditProviderPresetId.value = getAiProviderPresetId(draft.provider, draft.endpoint);");
- expect(settingsDialogSource).toContain('aiEditApiKey.value = "";');
- expect(settingsDialogSource).toContain("importClipboardApiKeyAfterConfirmation");
- expect(handlerStart).toBeGreaterThanOrEqual(0);
- expect(handlerEnd).toBeGreaterThan(handlerStart);
- expect(handlerSource).not.toContain("aiSaveConfig(");
- expect(handlerSource).not.toContain("aiTestConn(");
- });
-});
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
index b1e2153d00..2f45003825 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
SETTINGS_SEARCH_DEFINITIONS,
@@ -13,8 +12,6 @@ import {
type SettingsSearchDefinition,
} from "@/lib/settings/settingsSearch";
-const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
const categoryLabels = {
editor: "Editor",
formatter: "SQL Formatter",
@@ -94,9 +91,6 @@ describe("settings search", () => {
expect(withoutSqlServer.map((entry) => entry.id)).not.toContain("editor-sqlserver-space-completion");
expect(importedWithoutSqlServer.map((entry) => entry.id)).toContain("editor-sqlserver-space-completion");
expect(withSqlServer.map((entry) => entry.id)).toContain("editor-sqlserver-space-completion");
- expect(settingsDialogSource).toContain('const hasSqlServerConnection = computed(() => connectionStore.connections.some((connection) => effectiveDatabaseTypeForConnection(connection) === "sqlserver"));');
- expect(settingsDialogSource).toContain("const showSqlServerSpaceConfirmsCompletion = computed(");
- expect(settingsDialogSource).toContain('<div v-if="showSqlServerSpaceConfirmsCompletion" class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">');
});
it("does not index connection or query timeout under editor settings", () => {
@@ -112,8 +106,6 @@ describe("settings search", () => {
descriptionKey: "settings.multiStatementDefaultViewDescription",
targetId: "multi-statement-default-view",
});
- expect(settingsDialogSource).toContain('data-settings-search-id="multi-statement-default-view"');
- expect(settingsDialogSource).toContain('v-model="editMultiStatementDefaultView"');
});
it("places SQL file limits in their owning settings categories", () => {
@@ -138,17 +130,12 @@ describe("settings search", () => {
expect(desktopEntries.map((entry) => entry.id)).toContain("sql-file-editor-max-mb");
expect(desktopEntries.map((entry) => entry.id)).not.toContain("sql-file-web-upload-max-mb");
expect(webEntries.map((entry) => entry.id)).toEqual(expect.arrayContaining(["sql-file-editor-max-mb", "sql-file-web-upload-max-mb"]));
- expect(settingsDialogSource).toContain('data-settings-search-id="editor-sql-file"');
- expect(settingsDialogSource).toContain('data-settings-search-id="data-sql-file-upload"');
});
it("maps legacy SQL file settings navigation to the editor", () => {
expect(resolveSettingsCategory("sqlFile")).toBe("editor");
expect(resolveSettingsCategory()).toBe("appearance");
expect(resolveSettingsCategory("removed-category")).toBe("appearance");
- expect(settingsDialogSource).not.toContain('value: "sqlFile"');
- expect(settingsDialogSource).not.toContain("activeSettingsTab === 'sqlFile'");
- expect(settingsDialogSource).toMatch(/if \(tab === "data" && isWeb\) void loadWebSqlFileUploadMaxMbSetting\(\)/);
});
it("matches translated title, description, and category without changing declared order", () => {
@@ -168,16 +155,6 @@ describe("settings search", () => {
const webEntries = resolveSettingsSearchEntries(SETTINGS_SEARCH_DEFINITIONS, { isWeb: true, visibleCategories: new Set<SettingsCategory>(["sync"]) }, translate, categoryLabels);
expect(webEntries.map((entry) => entry.id)).toEqual(["sync-webdav", "sync-webdav-endpoint", "sync-webdav-username", "sync-webdav-password", "sync-webdav-remote-path", "sync-webdav-auto-upload", "sync-secrets", "sync-secrets-passphrase"]);
- expect(settingsDialogSource).toContain('{ value: "sync", label: t("settings.syncTab") }');
- expect(settingsDialogSource).not.toContain('...(isWeb ? [] : [{ value: "sync"');
- expect(settingsDialogSource).toContain('<TabsList v-if="!isWeb"');
- });
-
- it("defines the WebDAV Web-runtime notice in every supported locale", () => {
- for (const locale of ["zh-CN", "zh-TW", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "az"]) {
- const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- expect(source, locale).toContain("syncWebDavWebDescription:");
- }
});
it("matches Chinese text as a Unicode substring", () => {
@@ -208,13 +185,6 @@ describe("settings search", () => {
expect(entry).toMatchObject({ targetId: "sync-snippet", route: { syncMethodTab: "snippet" } });
});
- it("uses the open state for result visibility and applies nested routes before revealing targets", () => {
- expect(settingsDialogSource).toContain("const settingsSearchVisible = computed(() => settingsSearchOpen.value && settingsSearchActive.value)");
- expect(settingsDialogSource).toContain('v-if="settingsSearchVisible" id="settings-search-results"');
- expect(settingsDialogSource).toMatch(/function applySettingsSearchRoute[\s\S]*?syncMethodTab\.value = result\.route\.syncMethodTab/);
- expect(settingsDialogSource).toMatch(/async function selectSettingsSearchResult[\s\S]*?applySettingsSearchRoute\(result\)[\s\S]*?revealSettingsSearchTarget/);
- });
-
it("derives one search result for every built-in shortcut", () => {
expect(
createShortcutSettingsSearchDefinitions([
@@ -285,30 +255,6 @@ describe("settings search", () => {
);
});
- it("renders the metadata cache memory limit in a performance section after export", () => {
- const exportSectionStart = settingsDialogSource.indexOf('t("settings.exportSection")');
- const performanceSectionStart = settingsDialogSource.indexOf('data-settings-search-id="data-performance"');
- const tableStructureSectionStart = settingsDialogSource.indexOf('t("settings.tableStructureSection")');
- const metadataCacheControl = settingsDialogSource.indexOf('id="metadata-cache-memory-limit"');
-
- expect(exportSectionStart).toBeGreaterThan(-1);
- expect(performanceSectionStart).toBeGreaterThan(exportSectionStart);
- expect(tableStructureSectionStart).toBeGreaterThan(performanceSectionStart);
- expect(metadataCacheControl).toBeGreaterThan(performanceSectionStart);
- expect(metadataCacheControl).toBeLessThan(tableStructureSectionStart);
- });
-
- it("defines the performance section title in every supported locale", () => {
- for (const locale of ["zh-CN", "zh-TW", "en", "es", "it", "ja", "ko", "pt-BR", "tr", "az"]) {
- const source = readFileSync(new URL(`../../../i18n/locales/${locale}.ts`, import.meta.url), "utf8");
- expect(source, locale).toContain("performanceSection:");
- }
- });
-
- it("activates result buttons through click for keyboard and assistive technology", () => {
- expect(settingsDialogSource).toMatch(/role="option"[\s\S]*?@mousedown\.prevent[\s\S]*?@click="void selectSettingsSearchResult\(result\)"/);
- });
-
it("registers every fixed settings control that needs a dedicated search result", () => {
const expectedControls: ReadonlyArray<Pick<SettingsSearchDefinition, "titleKey" | "category" | "targetId">> = [
{ titleKey: "settings.savedSqlOpenTarget", category: "editor", targetId: "editor" },
diff --git a/apps/desktop/src/stores/__tests__/queryStore.resultViewGenerationSource.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.resultViewGenerationSource.spec.ts
deleted file mode 100644
index 842900cff6..0000000000
--- a/apps/desktop/src/stores/__tests__/queryStore.resultViewGenerationSource.spec.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const queryStoreSource = readFileSync(new URL("../queryStore.ts", import.meta.url), "utf8");
-
-/** Every direct assignment to the token, with its line number. */
-function directAssignments(): string[] {
- return queryStoreSource
- .split("\n")
- .map((line, index) => ({ line: line.trim(), number: index + 1 }))
- .filter((entry) => /^(current|tab|run)\.resultViewGeneration\s*=/.test(entry.line))
- .map((entry) => `${entry.number}: ${entry.line}`);
-}
-
-/** The body of executeTabSql, where every result publication must live. */
-function executeTabSqlBody(): string {
- const start = queryStoreSource.indexOf("async function executeTabSql(");
- const end = queryStoreSource.indexOf("\n }\n", start);
- expect(start).toBeGreaterThanOrEqual(0);
- expect(end).toBeGreaterThan(start);
- return queryStoreSource.slice(start, end);
-}
-
-describe("queryStore resultViewGeneration writer", () => {
- it("assigns the token in exactly the allowed places", () => {
- const assignments = directAssignments();
-
- // publishResultGeneration (the writer) plus the two identity-preserving
- // readers: disk restore inherits, run projection copies the run's value.
- expect(assignments).toHaveLength(3);
- expect(assignments.join("\n")).toContain("snapshot.resultViewGeneration");
- expect(assignments.join("\n")).toContain("run.resultViewGeneration");
- });
-
- it("defaults an unclassified publication to a new generation", () => {
- const start = queryStoreSource.indexOf("function publishResultGeneration(");
- const end = queryStoreSource.indexOf("function ", start + 10);
- const body = queryStoreSource.slice(start, end);
-
- expect(body).toContain('if (origin === "disk-restore") return;');
- expect(body).toContain('if (origin === "append") {');
- expect(body).toContain("tab.resultViewGeneration = uuid();");
- });
-
- it("publishes a generation for every replacement branch of executeTabSql", () => {
- const body = executeTabSqlBody();
-
- // Generic branch: append inherits, everything else replaces.
- expect(body).toContain('publishResultGeneration(current, shouldAppendResult ? "append" : (options?.publicationOrigin ?? "execute"));');
- // Redis, MongoDB, and Elasticsearch branches replace the visible result too;
- // Mongo's append variant must keep the current generation.
- expect(body).toContain('publishResultGeneration(current, shouldAppendResult ? "append" : "execute");');
- const publicationCount = body.match(/publishResultGeneration\(current/g)?.length ?? 0;
- expect(publicationCount).toBeGreaterThanOrEqual(5);
- });
-
- it("publishes outside executeTabSql where results are also replaced", () => {
- expect(queryStoreSource).toContain('publishResultGeneration(tab, "local-sort");');
- expect(queryStoreSource).toContain('publishResultGeneration(tab, "execute");');
- expect(queryStoreSource).toContain('publishResultGeneration(current, "execute");');
- });
-
- it("reserves the closing tombstone for tab closure, not ordinary execution", () => {
- // Ordinary execution clears the payload before running; the tombstone there
- // would block capturing the fresh result's view for five seconds.
- const clearResultPayloadStart = queryStoreSource.indexOf("function clearResultPayload(");
- const clearResultPayloadEnd = queryStoreSource.indexOf("\n }\n", clearResultPayloadStart);
- const clearResultPayloadBody = queryStoreSource.slice(clearResultPayloadStart, clearResultPayloadEnd);
- expect(clearResultPayloadBody).not.toContain("beginClosingDataGridViewSnapshotsForTab");
- expect(clearResultPayloadBody).toContain("clearDataGridViewSnapshotsForTab(tab.id);");
- // Tab closure keeps the tombstone so the teardown capture cannot resurrect.
- expect(queryStoreSource).toContain("beginClosingDataGridViewSnapshotsForTab(id);");
- expect(queryStoreSource.match(/beginClosingDataGridViewSnapshotsForTab\(tab\.id\)/g)?.length).toBe(2);
- });
-});
diff --git a/apps/desktop/src/stores/__tests__/queryStore.sqlserverTraceLifecycle.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.sqlserverTraceLifecycle.spec.ts
index 6aa1c377a0..e4111ad36b 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.sqlserverTraceLifecycle.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.sqlserverTraceLifecycle.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -12,8 +11,6 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/sqlserver/sqlServerActivityTraceRuntime", () => mocks);
-const connectionStoreSource = readFileSync(new URL("../connectionStore.ts", import.meta.url), "utf8");
-
describe("queryStore SQL Server trace lifecycle", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -36,8 +33,4 @@ describe("queryStore SQL Server trace lifecycle", () => {
store.closeTab(tabId);
expect(mocks.disposeSqlServerActivityTrace).toHaveBeenCalledWith(tabId);
});
-
- it("does not scan trace sessions on ordinary connection success", () => {
- expect(connectionStoreSource).not.toContain("cleanupStaleSqlServerTraceSessions");
- });
});
diff --git a/apps/desktop/src/stores/__tests__/queryStore.templateForceWordWrap.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.templateForceWordWrap.spec.ts
index 9967ff78c7..ef23af765e 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.templateForceWordWrap.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.templateForceWordWrap.spec.ts
@@ -1,4 +1,3 @@
-import { readFileSync } from "node:fs";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -34,16 +33,3 @@ describe("queryStore createTab forceWordWrap", () => {
expect(tab?.forceWordWrap).toBe(true);
});
});
-
-describe("Generate SQL template tabs wire forceWordWrap end to end (issue #6038)", () => {
- const sidebarSource = readFileSync(new URL("../../components/sidebar/SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
- const contentAreaSource = readFileSync(new URL("../../components/layout/ContentArea.vue", import.meta.url), "utf8");
-
- it("openSqlTemplateTab requests forceWordWrap when creating the tab", () => {
- expect(sidebarSource).toMatch(/function openSqlTemplateTab\([^)]*\)\s*{[\s\S]*?createTab\([^)]*forceWordWrap:\s*true[^)]*\)/);
- });
-
- it("ContentArea forwards the tab's forceWordWrap flag into QueryEditor", () => {
- expect(contentAreaSource).toMatch(/<QueryEditor[\s\S]*?:force-word-wrap="activeTab\.forceWordWrap"/);
- });
-});
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.typeColorScheme.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.typeColorScheme.spec.ts
index 7c6a898970..a6858a47dd 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.typeColorScheme.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.typeColorScheme.spec.ts
@@ -1,5 +1,4 @@
import { createPinia, setActivePinia } from "pinia";
-import { readFileSync } from "node:fs";
import { beforeEach, describe, expect, it, vi } from "vitest";
const saved: unknown[] = [];
@@ -68,15 +67,6 @@ describe("settings store type color scheme persistence", () => {
expect(last?.activeDataGridTypeColorSchemeId).toBe(SCHEME.id);
});
- it("stages scheme edits in the settings draft", () => {
- const dialogSource = readFileSync(new URL("../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
-
- expect(dialogSource).toContain("editDataGridTypeColorSchemes.value = cloneDataGridTypeColorSchemes(schemes)");
- expect(dialogSource).not.toContain("structuredClone(settingsStore.editorSettings.dataGridTypeColorSchemes)");
- expect(dialogSource).toContain("editActiveDataGridTypeColorSchemeId.value = activeId");
- expect(dialogSource).not.toMatch(/settingsStore\.updateEditorSettings\w*\(\{[^}]*DataGridTypeColorScheme/);
- });
-
it("restores a persisted scheme through normalization", async () => {
const { normalizeEditorSettings } = await import("@/stores/settingsStore");
diff --git a/crates/ARCHITECTURE.md b/crates/ARCHITECTURE.md
index 4908b2d735..31bb892a58 100644
--- a/crates/ARCHITECTURE.md
+++ b/crates/ARCHITECTURE.md
@@ -118,8 +118,7 @@ env -u DOCKER_CONTEXT \
--no-default-features --features dbx-core/sqlite-bundled --lib --no-fail-fast
cargo nextest run -p dbx-core --no-default-features --features sqlite-bundled \
- --test public_api_compatibility --test connection_url_compatibility \
- --test agent_recovery_contract --no-fail-fast
+ --test public_api_compatibility --test connection_url_compatibility --no-fail-fast
```
交付验证还应覆盖桌面/Web/CLI/MCP 消费者、合法 feature 组合、前端类型与源码契约、
diff --git a/crates/dbx-core/tests/agent_recovery_contract.rs b/crates/dbx-core/tests/agent_recovery_contract.rs
deleted file mode 100644
index c1f718baab..0000000000
--- a/crates/dbx-core/tests/agent_recovery_contract.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-#[cfg(test)]
-mod tests {
- #[test]
- fn business_modules_do_not_consume_legacy_marker_fields() {
- let business_sources = [
- ("query.rs", include_str!("../src/query/mod.rs")),
- ("schema.rs", include_str!("../src/schema/mod.rs")),
- ("connection.rs", include_str!("../src/connection/mod.rs")),
- ];
- let retired_consumers = ["agent_rpc_error_category", "agent_rpc_error_session_id", "agent_session_disposition"];
-
- for (name, source) in business_sources {
- for consumer in retired_consumers {
- assert!(!source.contains(consumer), "{name} still consumes {consumer}");
- }
- }
- }
-}
diff --git a/packages/app-tests/aiAgentEventSession.test.ts b/packages/app-tests/aiAgentEventSession.test.ts
deleted file mode 100644
index 3ad63e9763..0000000000
--- a/packages/app-tests/aiAgentEventSession.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-const tauriBackendSource = readFileSync("apps/desktop/src/lib/backend/tauri.ts", "utf8");
-const tauriAiCommandSource = readFileSync("src-tauri/src/commands/ai.rs", "utf8");
-
-test("Tauri AI agent stream events carry their session id", () => {
- assert.match(tauriAiCommandSource, /struct AiAgentEventPayload \{/);
- assert.match(tauriAiCommandSource, /session_id: String/);
- assert.match(tauriAiCommandSource, /#\[serde\(flatten\)\]\s*event: AgentEvent/);
- assert.match(
- tauriAiCommandSource,
- /AiAgentEventPayload \{ session_id: self\.session_id\.clone\(\), event \}/,
- );
- assert.match(tauriAiCommandSource, /app\.emit\("ai-agent-event", &payload\)/);
-});
-
-test("frontend ignores AI agent stream events from other sessions", () => {
- assert.match(tauriBackendSource, /type TauriAgentEvent = AgentEvent & \{\s*session_id\?: string;\s*\};/);
- assert.match(tauriBackendSource, /listen<TauriAgentEvent>\("ai-agent-event"/);
- assert.match(tauriBackendSource, /if \(payload\.session_id && payload\.session_id !== sessionId\) return;/);
- assert.match(tauriBackendSource, /onEvent\(payload\);/);
-});
diff --git a/packages/app-tests/aiAssistantComposerLayout.test.ts b/packages/app-tests/aiAssistantComposerLayout.test.ts
deleted file mode 100644
index 00228988e1..0000000000
--- a/packages/app-tests/aiAssistantComposerLayout.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { test } from "vitest";
-import { compileTemplate, parse } from "vue/compiler-sfc";
-
-const aiAssistantPath = fileURLToPath(new URL("../../apps/desktop/src/components/editor/AiAssistant.vue", import.meta.url));
-const zhCnLocalePath = fileURLToPath(new URL("../../apps/desktop/src/i18n/locales/zh-CN.ts", import.meta.url));
-const source = readFileSync(aiAssistantPath, "utf8");
-const zhCnLocaleSource = readFileSync(zhCnLocalePath, "utf8");
-
-test("AI composer keeps templates available without connections outside plugin conversations", () => {
- const contextRowStart = source.indexOf("data-ai-composer-context-row");
- const contextRowEnd = source.indexOf('v-if="mentionOpen"', contextRowStart);
- const contextRow = source.slice(contextRowStart, contextRowEnd);
-
- assert.notEqual(contextRowStart, -1, "the composer context row should exist");
- assert.notEqual(contextRowEnd, -1, "the connection context row should end before mention suggestions");
- assert.match(contextRow, /<details v-if="pluginContext"[\s\S]*?<template v-else-if="connectionStore\.connections\.length">/);
- assert.match(contextRow, /<Popover v-if="!pluginContext" v-model:open="showTemplateSelector">/);
- assert.match(contextRow, /max-w-\[40%\]/);
- assert.match(contextRow, /<span class="ai-template-selector-label truncate">\{\{ templateSelectorTriggerLabel \}\}<\/span>/);
- assert.match(contextRow, /:aria-label="templateSelectorTriggerLabel"/);
- assert.doesNotMatch(contextRow, /ai-prompt-context-break/);
- assert.match(source, /\.ai-prompt-context-row--schema \.ai-template-selector-trigger \{[\s\S]*?flex: 0 0 1\.5rem;[\s\S]*?max-width: 1\.5rem;/);
-});
-
-test("AI composer labels an empty template selection explicitly", () => {
- assert.match(source, /const templateSelectorTriggerLabel = computed\(\(\) => \{[\s\S]*?templateSelectorLabel.*templateSelectorLabel\.value/);
- assert.match(zhCnLocaleSource, /templateSelectorNone: "未选择"/);
-});
-
-test("AI composer exposes mode and action as one compact selector", () => {
- const footerStart = source.indexOf("<!-- Combined mode + action selector -->");
- const footerEnd = source.indexOf("<!-- Combined provider + model selector -->", footerStart);
- const footer = source.slice(footerStart, footerEnd);
-
- assert.notEqual(footerStart, -1, "the combined mode and action selector should exist");
- assert.notEqual(footerEnd, -1, "the model selector should follow the combined selector");
- assert.match(footer, /<span v-if="pluginContext"[\s\S]*?<Popover v-else v-model:open="modeActionOpen">/);
- assert.match(footer, /:aria-label="modeActionTriggerLabel"/);
- assert.match(footer, /switchModeActionTab\('ask'\)/);
- assert.match(footer, /switchModeActionTab\('agent'\)/);
- assert.match(footer, /selectModeActionItem\(button\.action\)/);
- assert.doesNotMatch(footer, /selectAction\(button\.action\)/);
- assert.match(footer, /<template v-if="showActionButtons">[\s\S]*?<div class="border-t my-1" \/>[\s\S]*?v-for="button in actionButtons"/);
- assert.match(source, /function selectModeActionItem\(action: AiActionSelection\) \{\s*\/\/ Vector databases[\s\S]*?if \(!showActionButtons\.value\) return;/);
-});
-
-test("AI effort control opens as a hoverable side submenu", () => {
- const selectorStart = source.indexOf("<!-- Combined provider + model selector -->");
- const selectorEnd = source.indexOf("</template>", source.indexOf("</Popover>", selectorStart));
- const selector = source.slice(selectorStart, selectorEnd);
-
- assert.notEqual(selectorStart, -1, "the combined provider and model selector should exist");
- assert.match(selector, /<Popover v-model:open="effortMenuOpen">/);
- assert.match(selector, /<PopoverAnchor as-child>/);
- assert.match(selector, /@mouseenter="openEffortMenu"/);
- assert.match(selector, /@mouseleave="scheduleEffortMenuClose"/);
- assert.match(selector, /<PopoverContent[\s\S]*?side="left"[\s\S]*?:side-offset="6"/);
- assert.doesNotMatch(selector, /v-if="effortPanelOpen"/);
-});
-
-test("AI model menu separates provider groups from model selections", () => {
- const selectorStart = source.indexOf("<!-- Combined provider + model selector -->");
- const selectorEnd = source.indexOf("</template>", source.indexOf("</Popover>", selectorStart));
- const selector = source.slice(selectorStart, selectorEnd);
-
- assert.match(selector, /<div v-for="\(config, configIndex\) in configuredProviders" :key="config\.id" class="relative">/);
- assert.match(selector, /class="sticky top-0 z-10 flex w-full items-center gap-2 rounded-sm bg-popover/);
- assert.match(selector, /class="ml-5 border-l border-border\/60 pl-1"/);
- assert.match(selector, /v-if="configIndex < configuredProviders\.length - 1" class="my-1 border-t"/);
- assert.doesNotMatch(selector, /bg-accent text-accent-foreground.*config\.id === settings\.activeModel/);
-});
-
-test("AI model and effort menu refreshes do not persist effort settings", () => {
- const loaderStart = source.indexOf("async function ensureModelEffort");
- const loaderEnd = source.indexOf("function handleModelSelect", loaderStart);
- const loader = source.slice(loaderStart, loaderEnd);
-
- assert.notEqual(loaderStart, -1, "the effort capability loader should exist");
- assert.notEqual(loaderEnd, -1, "the model selection handler should follow the effort loader");
- assert.match(loader, /await resolveEffort\(config, modelId, force\)/);
- assert.doesNotMatch(loader, /updateActiveEffort|persistAiChatSelection/);
-});
-
-test("AI composer template remains compilable", () => {
- const { descriptor, errors } = parse(source, { filename: aiAssistantPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.template);
-
- const result = compileTemplate({ id: aiAssistantPath, filename: aiAssistantPath, source: descriptor.template.content });
- assert.deepEqual(result.errors, []);
-});
diff --git a/packages/app-tests/aiAssistantSendGuard.test.ts b/packages/app-tests/aiAssistantSendGuard.test.ts
deleted file mode 100644
index 9ab42b4ad6..0000000000
--- a/packages/app-tests/aiAssistantSendGuard.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { parse } from "vue/compiler-sfc";
-
-// Regression guard for the F2 finding: AiAssistant.send() must acquire the
-// synchronous send guard (isGenerating.value = true) BEFORE its first await
-// (promptTemplateStore.ensureLoaded()). Otherwise two rapid submissions can
-// both pass the initial isGenerating check, await the deferred store load, and
-// resume into two concurrent agent runs.
-//
-// send() is an internal <script setup> function (not exported / not exposed),
-// and this repo has no component-mount test harness (@vue/test-utils is not a
-// dependency; zero specs call mount()). So — like aiMessageLayout.test.ts — we
-// assert the invariant against the SFC source: the guard is set synchronously
-// before any suspension point, which is exactly what makes the check-then-set
-// sequence atomic against a concurrent caller.
-
-const aiAssistantPath = "apps/desktop/src/components/editor/AiAssistant.vue";
-const source = readFileSync(aiAssistantPath, "utf8");
-
-function scriptSetupContent(): string {
- const { descriptor, errors } = parse(source, { filename: aiAssistantPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.scriptSetup, "AiAssistant.vue should use <script setup>");
- return descriptor.scriptSetup!.content;
-}
-
-// Extract a function body by brace-matching from a signature anchor, so the
-// assertions below are scoped to send() and immune to unrelated edits elsewhere
-// in the (very large) component.
-function functionBody(script: string, signature: string): string {
- const sigIndex = script.indexOf(signature);
- assert.notEqual(sigIndex, -1, `expected to find ${signature}`);
- assert.equal(script.indexOf(signature, sigIndex + signature.length), -1, `${signature} should be unique`);
- const openBrace = script.indexOf("{", sigIndex + signature.length);
- assert.notEqual(openBrace, -1, "function body should open with a brace");
-
- let depth = 0;
- for (let i = openBrace; i < script.length; i++) {
- const ch = script[i];
- if (ch === "{") depth++;
- else if (ch === "}") {
- depth--;
- if (depth === 0) return script.slice(openBrace + 1, i);
- }
- }
- throw new Error("unbalanced braces while extracting function body");
-}
-
-test("send() acquires the guard synchronously before the first await", () => {
- const body = functionBody(scriptSetupContent(), "async function send()");
-
- // Anchor on the condition, not on a one-line `return`: the branch may run a
- // synchronous cleanup first (a declined write-confirmation grant), so the
- // shape is a block now. The assertions below still require a return inside it.
- const entryCheck = body.search(/\|\|\s*isGenerating\.value\)\s*\{/);
- const guardSet = body.indexOf("isGenerating.value = true");
- // `await` as a whole word (not the substring inside e.g. the
- // `awaiting_write_confirmation` run status), so the first suspension point is
- // genuinely the first await statement.
- const firstAwait = body.search(/\bawait\b/);
-
- assert.notEqual(entryCheck, -1, "send() should early-return when isGenerating is already set");
- assert.notEqual(guardSet, -1, "send() should set the isGenerating guard");
- assert.notEqual(firstAwait, -1, "send() should contain an await");
- assert.ok(body.slice(entryCheck, guardSet).includes("return"), "the isGenerating branch must return before the guard set");
-
- // The entry check runs first, then the guard is set, then (and only then) the
- // first await suspends. Because nothing awaits between the check and the set,
- // a second concurrent send() cannot slip past the check before the guard flips.
- assert.ok(entryCheck < guardSet, "isGenerating check must precede the guard set");
- assert.ok(guardSet < firstAwait, "guard must be set before the first await (no await between check and set)");
-
- // The first suspension point is the send-time skill read or the prompt-template
- // load — both run after the guard and both are pipeline-entry awaits whose
- // failure paths release the guard state explicitly (see the early returns
- // after `aiGenerationGuard.begin()`).
- const ensureLoadedAwait = body.indexOf("await promptTemplateStore.ensureLoaded()");
- assert.notEqual(ensureLoadedAwait, -1, "send() should await promptTemplateStore.ensureLoaded()");
- const skillReadAwait = body.indexOf("await readUserSkills([...selectedSkillIds.value], skillRootSettings())");
- const pipelineEntryAwaits = [ensureLoadedAwait, skillReadAwait].filter((index) => index >= 0);
- assert.ok(pipelineEntryAwaits.includes(firstAwait), "the first await in send() must be the skill read or the prompt-template load");
-});
-
-test("send() never leaks the guard on an early return after acquiring it", () => {
- const body = functionBody(scriptSetupContent(), "async function send()");
- const guardSet = body.indexOf("isGenerating.value = true");
-
- // Every `return` that appears after the guard is acquired must first reset the
- // guard (there is one such path: the ensureLoaded() failure branch). A bare
- // `return` after the guard without a reset would strand isGenerating at true
- // and permanently block all future sends.
- const tail = body.slice(guardSet);
- const returnsAfterGuard = [...tail.matchAll(/\breturn\b/g)];
- assert.ok(returnsAfterGuard.length >= 1, "expected the ensureLoaded failure branch to early-return");
-
- for (const match of returnsAfterGuard) {
- const preceding = tail.slice(0, match.index);
- assert.ok(preceding.includes("isGenerating.value = false"), "any early return after the guard is acquired must reset isGenerating first");
- }
-});
-
-test("send() snapshots custom prompts before deferred AI context loading", () => {
- const body = functionBody(scriptSetupContent(), "async function send()");
- const ensureLoadedAwait = body.indexOf("await promptTemplateStore.ensureLoaded()");
- const snapshot = body.indexOf("const customPromptContext: CustomPromptContext");
- const sqlFileLoad = body.indexOf("await loadReferencedSqlFiles");
- const aiContextLoad = body.indexOf("await buildAiContext");
-
- assert.notEqual(snapshot, -1, "send() should snapshot the custom prompt context");
- assert.ok(ensureLoadedAwait < snapshot, "the snapshot must be taken after templates finish loading");
- assert.ok(snapshot < sqlFileLoad, "SQL file loading must not delay the custom prompt snapshot");
- assert.ok(snapshot < aiContextLoad, "AI context loading must not delay the custom prompt snapshot");
- assert.match(body.slice(snapshot, sqlFileLoad), /activeTemplates:\s*runPluginContext \? \[\] : \[\.\.\.activeTemplates\.value\]/);
-});
diff --git a/packages/app-tests/aiAssistantSkillEntry.test.ts b/packages/app-tests/aiAssistantSkillEntry.test.ts
deleted file mode 100644
index 3f7a96551d..0000000000
--- a/packages/app-tests/aiAssistantSkillEntry.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-// AiAssistant.vue has no mounted-DOM harness in this repo (no @vue/test-utils),
-// so this pins the /skill contract on the compiled SFC source, the same way
-// aiAssistantComposerLayout.test.ts pins the composer layout.
-const source = readFileSync(new URL("../../apps/desktop/src/components/editor/AiAssistant.vue", import.meta.url), "utf8");
-
-function section(startMarker: string, endMarker: string): string {
- const start = source.indexOf(startMarker);
- assert.notEqual(start, -1, `missing marker: ${startMarker}`);
- const end = source.indexOf(endMarker, start + startMarker.length);
- assert.notEqual(end, -1, `missing end marker: ${endMarker}`);
- return source.slice(start, end);
-}
-
-test("/skill rides its own command source instead of the action lists", () => {
- const commands = section("const filteredCommands = computed", "const AI_SQL_FILE_MENTION_CANDIDATE_LIMIT");
- assert.ok(commands.includes('{ type: "skills" }'), "filteredCommands must merge a dedicated skills entry");
- assert.ok(commands.includes('type: "action"'), "action entries must stay in the same command list");
-
- // The built-in action arrays must not gain a skill entry: they also feed the
- // mode+action picker, which would then offer /skill as a selectable action.
- for (const marker of ["/** Ask-mode actions: SQL-producing, never auto-run. */", "/** Agent-mode actions: task-oriented, drive tool use and real results. */"]) {
- const list = section(marker, "];");
- assert.ok(!/skill/i.test(list.replace(/AiActionButton/g, "")), `action list must not contain a skill entry: ${marker}`);
- }
-});
-
-test("selecting /skill never changes the built-in action", () => {
- const body = section("function selectCommand(command: AiSlashEntry)", "\nfunction insertMention");
- const skillsBranch = body.indexOf('command.type === "skills"');
- const actionAssign = body.indexOf("activeAction.value = command.button.action");
- assert.notEqual(skillsBranch, -1, "selectCommand must branch on the skills entry");
- assert.notEqual(actionAssign, -1, "selectCommand must still assign the chosen action");
- assert.ok(skillsBranch < actionAssign, "the skills branch must be evaluated before any action assignment");
-
- const branch = body.slice(skillsBranch, actionAssign);
- assert.ok(branch.includes("showSkillSelector.value = true"), "the skills branch must open the selector");
- assert.ok(branch.includes("return"), "the skills branch must return before the action assignment");
- assert.ok(!branch.includes("activeAction"), "the skills branch must not touch activeAction");
-});
-
-test("the skills selector only ever lists metadata", () => {
- const selector = section('<Popover v-model:open="showSkillSelector">', 'v-if="mentionOpen"');
- assert.ok(selector.length > 0);
- assert.ok(selector.includes("userSkillStore.groupedSkills"), "the selector renders the metadata catalog");
- assert.ok(!selector.includes("readUserSkills"), "the selector must never read skill bodies");
- assert.ok(selector.includes("refreshSkills"), "the selector exposes Refresh");
-});
diff --git a/packages/app-tests/aiMessageLayout.test.ts b/packages/app-tests/aiMessageLayout.test.ts
deleted file mode 100644
index 520824887e..0000000000
--- a/packages/app-tests/aiMessageLayout.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileTemplate, parse } from "vue/compiler-sfc";
-
-const aiAssistantPath = "apps/desktop/src/components/editor/AiAssistant.vue";
-const source = readFileSync(aiAssistantPath, "utf8");
-
-function userMessageTemplate(): string {
- const start = source.indexOf(`<div v-if="msg.role === 'user'"`);
- const end = source.indexOf(`<div v-else-if="msg.content || msg.reasoning || msg.isThinking"`, start);
-
- assert.notEqual(start, -1, "user message template should exist");
- assert.notEqual(end, -1, "assistant message template should follow user messages");
- return source.slice(start, end);
-}
-
-function assistantMessageTemplate(): string {
- const start = source.indexOf(`<div v-else-if="msg.content || msg.reasoning || msg.isThinking"`);
- const end = source.indexOf(`</template>`, start);
-
- assert.notEqual(start, -1, "assistant message template should exist");
- assert.notEqual(end, -1, "assistant message template should end before the message loop");
- return source.slice(start, end);
-}
-
-test("AI assistant template compiles", () => {
- const { descriptor, errors } = parse(source, { filename: aiAssistantPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.template);
-
- const result = compileTemplate({ id: aiAssistantPath, filename: aiAssistantPath, source: descriptor.template.content });
- assert.deepEqual(result.errors, []);
-});
-
-test("user message edit action does not change short or wrapped message layout", () => {
- const template = userMessageTemplate();
-
- assert.match(template, /class="relative min-w-0 max-w-\[85%\]"/);
- assert.match(template, /class="min-w-0"/);
- assert.match(template, /absolute right-full top-1 mr-1 flex h-5 w-5/);
- assert.match(template, /class="whitespace-pre-wrap"/);
- assert.doesNotMatch(template, /\bhidden\b[^\n>]*group-hover:flex/);
-});
-
-test("user message edit action remains available by pointer and keyboard", () => {
- const template = userMessageTemplate();
-
- assert.match(template, /group-hover:pointer-events-auto group-hover:opacity-100/);
- assert.match(template, /focus:pointer-events-auto focus:opacity-100/);
- assert.match(template, /:title="t\('ai\.editMessage'\)"[\s\S]*?@click="startEditMessage\(i\)"/);
- assert.match(template, /v-if="!isGenerating"/);
-});
-
-test("assistant messages keep metadata aligned with the bubble and wrap long text", () => {
- const template = assistantMessageTemplate();
-
- assert.match(template, /class="flex w-full max-w-\[95%\] min-w-0 flex-col"/);
- assert.match(template, /class="w-full[^"\n]*\[overflow-wrap:anywhere\]"/);
-});
-
-test("AI request failures use localized backend diagnostics", () => {
- // The lookup is guarded (matching the `finally` block right below it) so that if
- // clearMessages()/selectConversation() already replaced the transcript while this
- // request was still in flight, writing the failure text doesn't throw and silently
- // swallow the real error. See issue #5941. (`runMessages` is the send pipeline's
- // array — `messages.value` for a visible conversation, the run's own array for a
- // detached/background run.) The failure flag rides along with the prefix text
- // (#6467 PR3): the export derives its failure marker from this state.
- assert.match(source, /const msg = runMessages\[assistantIdx\];\s*\n\s*if \(msg\) \{/);
- assert.match(source, /msg\.content = `\$\{t\("ai\.requestFailed"\)\}\\n\\n\$\{translateBackendError\(t, message\)\}`;/);
- assert.match(source, /msg\.failed = true;/);
-});
-
-test("AI analysis export keeps the connection that produced each assistant response", () => {
- assert.match(source, /sourceConnectionName\?: string/);
- assert.match(source, /const runSourceName = runPluginContext\?\.pluginName \?\? connection\?\.name \?\? ""/);
- // The assistant placeholder must record the connection that produced it. The
- // literal also carries per-run fields (the frozen `sourceBinding` target,
- // #9902), so pin the pair instead of the closing brace.
- assert.match(source, /runMessages\.push\(\{ role: "assistant", content: "", sourceConnectionName: runSourceName,/);
- assert.match(source, /sourceBinding: runBinding \}\);/);
- // The fallback for a message that predates `sourceConnectionName` is the
- // conversation's own bound connection, not whatever tab is visible (#9902).
- assert.match(source, /connectionName: msg\.sourceConnectionName \?\? boundConnection\.value\?\.name/);
- assert.match(source, /sourceConnectionName: m\.role === "assistant" \? conv\.connectionName : undefined/);
-});
diff --git a/packages/app-tests/binaryCellDownload.test.ts b/packages/app-tests/binaryCellDownload.test.ts
index c73b30b759..c0143ec736 100644
--- a/packages/app-tests/binaryCellDownload.test.ts
+++ b/packages/app-tests/binaryCellDownload.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import {
@@ -68,13 +67,6 @@ test("binary cell download menu closes when hover moves to another cell", () =>
assert.equal(retainBinaryCellDownloadMenuForHover(openCell, { rowIndex: 2, col: 4 }), openCell);
});
-test("transpose cell hover also clears a different binary download menu", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const handler = source.match(/function onTransposeCellMouseenter\([^]*?\n\}/)?.[0] ?? "";
-
- assert.match(handler, /retainBinaryCellDownloadMenuForHover\(quickDownloadMenuCell\.value, \{ rowIndex, col: actualColIdx \}\)/);
-});
-
test("canDownloadBinaryCellValue allows displayed binary hex strings", () => {
assert.equal(canDownloadBinaryCellValue("0x89504e47", "BLOB"), true);
assert.equal(canDownloadBinaryCellValue("0x89504e47"), true);
@@ -284,13 +276,6 @@ test("binaryCellDownloadPayload builds raw and decoded payloads", () => {
assert.deepEqual(Array.from(emptyBinary.data as Uint8Array), []);
});
-test("DataGrid binary preview prefers ResultSet column types when table metadata is unavailable", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const formatter = source.match(/function formatCell\([^]*?\n\}/)?.[0] ?? "";
-
- assert.match(formatter, /binaryCellDisplayText\(value, columnIndex === undefined \? undefined : allColumnTypes\.value\[columnIndex\], originalBytes, resolvedDatabaseType\.value\)/);
-});
-
test("binaryCellDownloadPayload decodes GBK text bytes", () => {
const payload = binaryCellDownloadPayload("0xd6d0cec4", "gbk");
assert.equal(payload.data, "中文");
@@ -319,14 +304,3 @@ test("formatBinaryCellByteSize formats human-readable sizes for the import toast
// bytes >= 10 MB 时按整数 MB 显示(对齐 binaryCellDisplayText 既有格式)。
assert.equal(formatBinaryCellByteSize(20 * 1024 * 1024), "20 MB");
});
-
-test("DataGrid import handler surfaces a dedicated too-large toast instead of the generic failure", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const handler = source.match(/async function importDetailBinaryValue\([^]*?\n\}/)?.[0] ?? "";
-
- // 闸门错误必须走专门的文案,而非通用 binaryImportFailed。
- assert.match(handler, /e instanceof BinaryCellImportTooLargeError/);
- assert.match(handler, /grid\.binaryImportTooLarge/);
- assert.match(handler, /formatBinaryCellByteSize\(e\.bytes\)/);
- assert.match(handler, /formatBinaryCellByteSize\(e\.limit\)/);
-});
diff --git a/packages/app-tests/canvasDataGridRenderer.test.ts b/packages/app-tests/canvasDataGridRenderer.test.ts
index 572925b546..01b41ee828 100644
--- a/packages/app-tests/canvasDataGridRenderer.test.ts
+++ b/packages/app-tests/canvasDataGridRenderer.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { canvasDataGridActionReservedWidth, fitCanvasText, resolveCanvasCellTextLayout, resolveCanvasDataGridRowFill } from "../../apps/desktop/src/lib/dataGrid/canvasDataGridRenderer.ts";
import { DATA_GRID_DARK_STRIPED_ROW_BG, DATA_GRID_LIGHT_STRIPED_ROW_BG, resolveDataGridPaintTheme } from "../../apps/desktop/src/lib/dataGrid/dataGridPaintTheme.ts";
@@ -43,14 +42,6 @@ test("canvas text layout reserves hover actions only for right-aligned cells", (
assert.equal(canvasDataGridActionReservedWidth(true), 50);
});
-test("DataGrid forwards hover action reservation only for right-aligned canvas cells", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
-
- assert.match(source, /columnAligns\.value\[cell\.visibleColIdx\] !== "right"/);
- assert.match(source, /reservedWidth: canvasDataGridActionReservedWidth\(cell\.canQuickDownload, !!cell\.foreignKey, cellDetailButtonEnabled\.value, !!cell\.externalUrl\)/);
- assert.match(source, /rightAlignedActionCell: canvasRightAlignedActionCell\.value/);
-});
-
test("canvas row fill keeps frozen and scrolling regions on the same selection surface", () => {
const theme = { cellActive: "active-blue", cellSelected: "selected-blue" };
diff --git a/packages/app-tests/codemirrorSqlDialect.test.ts b/packages/app-tests/codemirrorSqlDialect.test.ts
index 20069552b9..b371c8c78a 100644
--- a/packages/app-tests/codemirrorSqlDialect.test.ts
+++ b/packages/app-tests/codemirrorSqlDialect.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import * as langSql from "@codemirror/lang-sql";
import { createDbxCodeMirrorSqlDialect } from "../../apps/desktop/src/lib/editor/codemirrorSqlDialect.ts";
@@ -141,15 +140,3 @@ test("keeps MySQL-compatible double-dash whitespace rules", () => {
assert.equal(countParsedNodes(dialect, "-- SELECT 1", "LineComment", "-- SELECT 1"), 1, databaseType);
}
});
-
-test("propagates database type to every DDL viewer entrypoint", () => {
- const ddlViewDialog = readFileSync("apps/desktop/src/components/objects/DdlViewDialog.vue", "utf8");
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
- const app = readFileSync("apps/desktop/src/App.vue", "utf8");
-
- assert.match(ddlViewDialog, /createDbxCodeMirrorSqlDialect\(langSql, props\.dialect, props\.databaseType\)/);
- assert.match(connectionTree, /<SidebarDdlViewDialog/);
- assert.match(connectionTree, /:database-type="sidebarDdlDatabaseType"/);
- assert.match(connectionTree, /v-model:open="sidebarDdlOpen"/);
- assert.match(app, /<QueryEditorDdlViewDialog[^>]*:database-type="queryEditorDdlDatabaseType"[^>]*\/>/);
-});
diff --git a/packages/app-tests/dataGridBooleanColumn.test.ts b/packages/app-tests/dataGridBooleanColumn.test.ts
index 5d60dd006a..aa755110a4 100644
--- a/packages/app-tests/dataGridBooleanColumn.test.ts
+++ b/packages/app-tests/dataGridBooleanColumn.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { BOOLEAN_CELL_EDITOR_VALUES, booleanCellEditorValue, isBooleanCellValue, isBooleanColumnType, normalizeBooleanCellValue, parseBooleanCellEditorValue } from "../../apps/desktop/src/lib/dataGrid/dataGridBooleanColumn.ts";
import { resolveDataGridColumnNullability, resolveDataGridColumnsByResultIndex } from "../../apps/desktop/src/lib/dataGrid/dataGridColumnMetadata.ts";
@@ -108,39 +107,3 @@ test("shows nullability only for query results with resolved column metadata", (
assert.equal(resolveDataGridColumnNullability("table-data", nullable), undefined);
assert.equal(resolveDataGridColumnNullability(undefined, nullable), undefined);
});
-
-test("keeps the enum editor as the default boolean edit path and gates checkbox interaction behind the checkbox display mode", () => {
- const gridSource = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const rendererSource = readFileSync("apps/desktop/src/lib/dataGrid/canvasDataGridRenderer.ts", "utf8");
-
- assert.match(gridSource, /v-else-if="isBooleanGridCell\([^\n]+"[\s\S]*?v-model="booleanEditorModelValue"[\s\S]*?:values="BOOLEAN_CELL_EDITOR_VALUES"/);
- assert.match(gridSource, /@commit="commitBooleanGridEdit"/);
- // The editor-side cycle helper the old checkbox implementation depended on stays removed.
- assert.doesNotMatch(gridSource, /cycleBooleanCellValue/);
- // Checkbox rendering and click cycling only exist behind the checkbox display mode.
- assert.match(gridSource, /booleanCellsUseCheckbox\.value/);
- assert.match(rendererSource, /booleanDisplayMode === "checkbox"/);
-});
-
-test("DOM checkbox mode renders a clickable placeholder for null boolean cells so they can be cycled like canvas", () => {
- const gridSource = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- // Canvas surfaces null booleans via booleanNullTextHitFromCanvasEvent (click the NULL text to cycle).
- // The DOM path must offer the same affordance: a null boolean cell in checkbox mode renders its NULL
- // text with a click handler that triggers cycleBooleanGridCell, instead of falling through to the
- // static v-else text (which cannot be cycled and is short-circuited by onDomCellDblClick).
- const domCellBranch = gridSource.match(/<template v-else-if="booleanCellsUseCheckbox && isBooleanGridCell\([^\n]+=== null[\s\S]*?cycleBooleanGridCell/);
- assert.ok(domCellBranch, "DOM checkbox mode must render a clickable cycle placeholder for null boolean cells");
- assert.match(domCellBranch![0], /@click\.stop="cycleBooleanGridCell/);
- assert.match(domCellBranch![0], /text-muted-foreground/);
-});
-
-test("uses the indexed metadata lookup in grid hot paths", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const start = source.indexOf("function tableColumnForGridColumn");
- const end = source.indexOf("function resultColumnInfoForGridColumn", start);
- const lookup = source.slice(start, end);
-
- assert.ok(start >= 0 && end > start);
- assert.match(lookup, /tableColumnsByResultIndex\.value\[columnIndex\]/);
- assert.doesNotMatch(lookup, /\.find\(/);
-});
diff --git a/packages/app-tests/dataGridContextMenu.test.ts b/packages/app-tests/dataGridContextMenu.test.ts
index 819817a165..2c12c1d3ca 100644
--- a/packages/app-tests/dataGridContextMenu.test.ts
+++ b/packages/app-tests/dataGridContextMenu.test.ts
@@ -1,20 +1,11 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "vitest";
-import { compileScript, parse } from "vue/compiler-sfc";
import { createDataGridCellContextMenuItems } from "../../apps/desktop/src/lib/dataGrid/dataGridContextMenu";
const dataGridPath = "apps/desktop/src/components/grid/DataGrid.vue";
const dataGridSource = readFileSync(dataGridPath, "utf8");
-test("DataGrid context menu script compiles", () => {
- const { descriptor, errors } = parse(dataGridSource, { filename: dataGridPath });
-
- assert.deepEqual(errors, []);
- assert.ok(descriptor.scriptSetup);
- compileScript(descriptor, { id: "data-grid-context-menu-test" });
-});
-
test("set NULL applies a real null value only to editable selections", () => {
const handler = dataGridSource.match(/function setSelectionNull\(\) \{[^]*?\n\}/)?.[0] ?? "";
@@ -23,69 +14,6 @@ test("set NULL applies a real null value only to editable selections", () => {
assert.doesNotMatch(handler, /fillSelectionWithValue\(["'](?:NULL)?["']\)/);
});
-test("generated selection values restore grid focus for keyboard shortcuts", () => {
- const applyHandler = dataGridSource.match(/function applyGeneratedSelectionValue\([^]*?\n\}/)?.[0] ?? "";
-
- assert.match(applyHandler, /if \(applied\)[^]*nextTick\(\(\) => window\.requestAnimationFrame\(\(\) => gridRef\.value\?\.focus\(\{ preventScroll: true \}\)\)\)/);
-});
-
-test("column-header context menus defer copy statement generation", () => {
- const handler = dataGridSource.match(/function onHeaderContext\([^]*?\n\}/)?.[0] ?? "";
-
- assert.doesNotMatch(handler, /prefetchCopyStatements/);
-});
-
-test("context-menu invalidation clears cell and header targets together", () => {
- const handler = dataGridSource.match(/function invalidateContextMenuTarget\(\) \{[^]*?\n\}/)?.[0] ?? "";
-
- assert.match(handler, /contextSelectionIsSynthetic\.value = false;/);
- assert.match(handler, /contextCell\.value = null;/);
- assert.match(handler, /contextHeaderColumn\.value = null;/);
- assert.match(handler, /contextHeaderColumnIndex\.value = null;/);
- assert.match(handler, /contextHeaderVisibleColIdx\.value = null;/);
-});
-
-test("header context menu wires batch hide and show-all to the column layout pipeline", () => {
- assert.match(dataGridSource, /hideColumn: hideContextColumn,/);
- assert.match(dataGridSource, /hideSelectedColumns,/);
- assert.match(dataGridSource, /showAllColumnsMenu: showAllColumns,/);
- assert.match(dataGridSource, /hiddenColumnCount: hiddenColumnCount\.value,/);
-
- const hideWrapper = dataGridSource.match(/function hideColumns\(columnIndexes: number\[\]\) \{[^]*?\n\}/)?.[0] ?? "";
-
- assert.match(hideWrapper, /applyColumnOrderChange\(\(\) => hideColumnsInLayout\(columnIndexes\)\)/);
- assert.match(hideWrapper, /clearCellSelection\(\);/);
- assert.match(hideWrapper, /clampGridHorizontalScroll\(\)/);
-
- // 显示全部列也走 applyColumnOrderChange,隐藏期间产生的可见索引偏移会被重新对齐。
- const showAllWrapper = dataGridSource.match(/function showAllColumns\(\) \{[^]*?\n\}/)?.[0] ?? "";
-
- assert.match(showAllWrapper, /applyColumnOrderChange\(showAllColumnsInLayout\)/);
-});
-
-test("select-all context menus invalidate a stale specialized target", () => {
- const header = dataGridSource.match(/<div\s+class="data-grid-header-cell shrink-0 px-2 py-1\.5[^]*?@click="selectAllCells"[^]*?>/u)?.[0] ?? "";
-
- assert.match(header, /@contextmenu="invalidateContextMenuTarget"/);
-});
-
-test("right-clicking outside the old cell or column selection resets it before selecting the target", () => {
- const handler = dataGridSource.match(/function onCellContext\([^]*?\n\}/)?.[0] ?? "";
- const clear = handler.indexOf("clearCellSelection();");
- const select = handler.indexOf("selectSingleCell(rowIndex, visibleColIdx);");
-
- assert.ok(clear >= 0);
- assert.ok(clear < select);
-});
-
-test("menu-close invalidation is deferred and guarded from a newer open", () => {
- const handler = dataGridSource.match(/function onGridContextMenuClose\(\) \{[^]*?\n\}/)?.[0] ?? "";
-
- assert.match(handler, /queueMicrotask\(\(\) => \{/);
- assert.match(handler, /if \(lifecycle !== contextMenuLifecycle\) return;/);
- assert.match(handler, /invalidateContextMenuTarget\(\);/);
-});
-
test("editable cell selections expose generation after bulk edit", () => {
const icon = {};
const action = () => {};
diff --git a/packages/app-tests/dataGridDefaultPlaceholder.test.ts b/packages/app-tests/dataGridDefaultPlaceholder.test.ts
index ef5e2d2df4..e43a724ed3 100644
--- a/packages/app-tests/dataGridDefaultPlaceholder.test.ts
+++ b/packages/app-tests/dataGridDefaultPlaceholder.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { resolveDataGridColumnsByResultIndex } from "../../apps/desktop/src/lib/dataGrid/dataGridColumnMetadata.ts";
import { resolveDataGridNewRowCellPlaceholder } from "../../apps/desktop/src/lib/dataGrid/dataGridDefaultPlaceholder.ts";
@@ -50,15 +49,3 @@ test("existing nulls, explicit values, and unmapped new columns do not show sche
assert.equal(resolveDataGridNewRowCellPlaceholder({ row: { data: [null], isNew: true }, columnIndex: 0, column: undefined, draftFallback: "New" }), null);
assert.equal(resolveDataGridNewRowCellPlaceholder({ row: { data: [null], isNew: false, isDraft: true }, columnIndex: 0, column: undefined, draftFallback: "New" }), "New");
});
-
-test("DOM and canvas paths consume the same per-cell placeholder resolver", () => {
- const dataGridSource = readFileSync(new URL("../../apps/desktop/src/components/grid/DataGrid.vue", import.meta.url), "utf8");
- const canvasSource = readFileSync(new URL("../../apps/desktop/src/lib/dataGrid/canvasDataGridRenderer.ts", import.meta.url), "utf8");
-
- assert.match(dataGridSource, /function newRowCellPlaceholder\(item: RowItem \| undefined, columnIndex: number\)/);
- assert.match(dataGridSource, /newRowCellPlaceholder,\n\s+isRowActive/);
- assert.match(dataGridSource, /newRowCellPlaceholder\(displayItems\[cell\.recordIndex\], cell\.valueIndex\)/);
- assert.match(dataGridSource, /newRowCellPlaceholder\(item, col\.actualColIdx\)/);
- assert.match(canvasSource, /newRowCellPlaceholder\?: \(row: CanvasDataGridRow, columnIndex: number\) => string \| null/);
- assert.match(canvasSource, /newRowCellPlaceholder\?\.\(item, actualColIdx\)/);
-});
diff --git a/packages/app-tests/dataGridHeaderBackground.test.ts b/packages/app-tests/dataGridHeaderBackground.test.ts
deleted file mode 100644
index ef9b553338..0000000000
--- a/packages/app-tests/dataGridHeaderBackground.test.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { parse } from "vue/compiler-sfc";
-
-test("unused header width keeps the result background", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const { descriptor } = parse(source, { filename: "DataGrid.vue" });
- const style = descriptor.styles.map((block) => block.content).join("\n");
-
- assert.match(style, /\.data-grid-header-shell\s*\{[^}]*background-color:\s*var\(--background\)/s);
- assert.match(style, /\.data-grid-header-cell\s*\{[^}]*background-color:\s*rgb\(239,\s*239,\s*239\)/s);
- assert.doesNotMatch(style, /\.data-grid-header-shell\s*,\s*\.data-grid-header-cell/);
- assert.doesNotMatch(style, /data-grid--dark\s+\.data-grid-header-shell/);
-});
diff --git a/packages/app-tests/dataGridInfiniteScroll.test.ts b/packages/app-tests/dataGridInfiniteScroll.test.ts
index 582df59de3..853ea204e6 100644
--- a/packages/app-tests/dataGridInfiniteScroll.test.ts
+++ b/packages/app-tests/dataGridInfiniteScroll.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { dataGridScrollPosition, isDataGridNearScrollBottom, isDataGridPrefixAppend, shouldCheckInfiniteScrollAfterScroll } from "../../apps/desktop/src/lib/dataGrid/dataGridInfiniteScroll.ts";
@@ -39,12 +38,3 @@ test("append marker does not preserve state when an existing row was replaced",
assert.equal(isDataGridPrefixAppend(previous, { rows: [first, [...second], [3, "Grace"]], appended_from_row_count: 2 }), false);
assert.equal(isDataGridPrefixAppend(previous, { rows: [first, second, [3, "Grace"]] }), false);
});
-
-test("infinite scroll requests only the next bounded segment", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /function infiniteScrollNextPage\(\) \{[\s\S]*?if \(!canFetchNextInfiniteScrollSegment\.value\) \{[\s\S]*?infiniteScrollAllLoaded = true;[\s\S]*?return;[\s\S]*?\}/);
- assert.match(source, /const nextOffset = props\.result\.rows\.length/);
- assert.match(source, /Math\.min\(pageSize\.value, remainingRows\)/);
- assert.doesNotMatch(source, /emit\("paginate", 0, cumulativeLimit/);
- assert.match(source, /props\.result\.appended_from_row_count !== requestedOffset/);
-});
diff --git a/packages/app-tests/dataGridPagination.test.ts b/packages/app-tests/dataGridPagination.test.ts
index 40b85ecf47..1fec3cd0b3 100644
--- a/packages/app-tests/dataGridPagination.test.ts
+++ b/packages/app-tests/dataGridPagination.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { canFetchNextDataGridSegment, canGoNextDataGridPage, hasCompleteLocalDataGridResult, resolveDataGridPaginationTotal } from "../../apps/desktop/src/lib/dataGrid/dataGridPagination.ts";
@@ -235,84 +234,3 @@ test("auto-redirect: total is undefined — guard prevents redirect attempt", ()
const total = undefined;
assert.equal(!total || (total as any) <= 0, true, "guard should prevent redirect when total is unknown");
});
-
-test("explicit loads, last-page COUNTs, and page jumps block the grid surface; background counts do not", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /const totalRowCountBusy = computed\(\(\) => props\.totalRowCountLoading === true \|\| manualTotalRowCountLoading\.value\)/);
- assert.match(source, /const gridSurfaceBusy = computed\(\(\) => isRefreshingData\.value \|\| props\.loading === true \|\| manualTotalRowCountLoading\.value \|\| pageJumpBusy\.value\)/);
- assert.match(source, /const pageJumpBusy = computed\(\(\) => !!props\.pageJumpProgress && props\.pageJumpProgress\.totalRequests > 1\)/);
- // totalRowCountBusy must stay out of gridSurfaceBusy so background counts keep the grid interactive (#5967)
- const busyLine = source.match(/const gridSurfaceBusy = computed\([^\n]*/)?.[0] ?? "";
- assert.ok(!busyLine.includes("totalRowCountBusy"), "background counts must not block the grid surface");
- assert.match(source, /const gridPaginationBusy = computed\(\(\) => gridSurfaceBusy\.value \|\| totalRowCountBusy\.value\)/);
- assert.match(source, /v-if="gridSurfaceBusy"/);
- assert.match(source, /:loading="gridPaginationBusy"/);
- assert.match(source, /async function beginManualTotalRowCount/);
- assert.match(source, /await nextTick\(\);/);
- const lastPageFn = source.match(/async function lastPage\(\) \{[\s\S]*?\n\}/)?.[0] ?? "";
- assert.match(lastPageFn, /beginManualTotalRowCount\(\)/);
- assert.match(lastPageFn, /buildCurrentCountTarget\(\)/);
- assert.ok(lastPageFn.indexOf("beginManualTotalRowCount") < lastPageFn.indexOf("buildCurrentCountTarget"), "busy UI must start before COUNT SQL is built");
-});
-
-test("last page always re-counts when a count path is available", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const lastPageFn = source.match(/async function lastPage\(\) \{[\s\S]*?\n\}/)?.[0] ?? "";
- const knownTotalIdx = lastPageFn.indexOf("hasKnownPaginationTotalRowCount");
- const countCallbackIdx = lastPageFn.indexOf("props.countTotalRows");
- const countSqlIdx = lastPageFn.indexOf("buildCurrentCountTarget");
- assert.ok(countCallbackIdx >= 0 && countSqlIdx >= 0, "last page must keep count paths");
- assert.ok(knownTotalIdx < 0 || knownTotalIdx > countSqlIdx, "known totals are only a fallback after re-COUNT");
-});
-
-test("jumping to last page does not rewrite indexes before the new page loads", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const jumpFn = source.match(/function jumpToCountedLastPage\(total: number\) \{[\s\S]*?\n\}/)?.[0] ?? "";
- assert.match(jumpFn, /resolveDataGridPaginationTotal/);
- assert.match(jumpFn, /maxRows: paginationMaxRows\.value/);
- // Last-page jumps delegate to requestServerPageJump (ES deep-jump confirm) which still emits "paginate" without bumping currentPage
- assert.match(jumpFn, /requestServerPageJump\(lastPageNum\)/);
- const executeJumpFn = source.match(/function executeServerPageJump[\s\S]*?\n\}/)?.[0] ?? "";
- assert.match(executeJumpFn, /emit\("paginate"/);
- assert.doesNotMatch(jumpFn, /currentPage\.value\s*=/);
- assert.match(source, /function rowNumberPageOffset/);
-});
-
-test("query result caps do not limit table-data pagination", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /const paginationMaxRows = computed\(\(\) => \(isResultsContext\.value \? queryResultMaxRows\.value : undefined\)\)/);
- assert.equal(source.match(/maxRows: paginationMaxRows\.value/g)?.length, 2);
-});
-
-test("row number gutter width tracks the largest visible row index", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /dataGridRowNumberColumnWidth/);
- assert.match(source, /resolveDataGridMaxRowNumber/);
- assert.match(source, /rowNumberWidth,/);
-});
-
-test("rerun total-count visibility comes from the shared rule and triggers the manual count", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const rerunComputed = source.match(/const showRerunTotalCountAction = computed\(\(\) =>[\s\S]*?\n\);/)?.[0] ?? "";
- assert.match(rerunComputed, /showDataGridRerunTotalCountAction\(\{/);
- assert.match(rerunComputed, /canCalculateTotalRowCount: canCalculateTotalRowCount\.value/);
- assert.match(rerunComputed, /displayedTotalRowCount: displayedTotalRowCount\.value/);
- assert.match(rerunComputed, /totalRowCountIsExact: totalRowCountIsExact\.value/);
- const rerunButton = source.match(/<i18n-t v-if="showRerunTotalCountAction[\s\S]*?<template #button>[\s\S]*?<button[\s\S]*?<\/button>/)?.[0] ?? "";
- assert.match(rerunButton, /@click="calculateTotalRowCount"/);
-});
-
-test("manual rerun counts through props.countSql and resets when the query context changes", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /if \(props\.countSql\) return \{ sql: props\.countSql, schema: props\.schema \};/);
- assert.match(source, /const serverKnownTotalRowCount = computed\(\(\) => \(typeof manualTotalRowCount\.value === "number" \? manualTotalRowCount\.value : props\.totalRowCount\)\)/);
- assert.match(source, /watch\(\s*\(\) => \[props\.countSql \?\? ""/);
-});
-
-test("executed plans refresh the count SQL shared with the background count", () => {
- const source = readFileSync("apps/desktop/src/stores/queryStore.ts", "utf8");
- assert.ok((source.match(/current\.resultCountSql = countSql;/g)?.length ?? 0) >= 2, "every executed-plan path must refresh the tab count SQL");
- assert.match(source, /countSql = sqlServerUseScript && plan\.countSql \? replaceSqlServerLeadingUseQuery\(queryBaseSql, sqlServerUseScript, plan\.countSql\) : plan\.countSql;/);
- const backgroundCount = source.match(/countQueryTotalRowsInBackground\(\{[\s\S]*?\}\);/)?.[0] ?? "";
- assert.match(backgroundCount, /\n\s+countSql,/);
-});
diff --git a/packages/app-tests/dataGridProps.test.ts b/packages/app-tests/dataGridProps.test.ts
deleted file mode 100644
index 83a2746b56..0000000000
--- a/packages/app-tests/dataGridProps.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileScript, parse } from "vue/compiler-sfc";
-
-function compiledDataGridScript(): string {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const { descriptor } = parse(source, { filename: "DataGrid.vue" });
- return compileScript(descriptor, { id: "data-grid-props-test" }).content;
-}
-
-test("DataGrid template components have local or documented global bindings", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const { descriptor } = parse(source, { filename: "DataGrid.vue" });
- const bindings = compileScript(descriptor, { id: "data-grid-component-bindings" }).bindings;
- assert.ok(descriptor.template);
-
- const globalComponents = new Set(["RecycleScroller"]);
- const componentTags = new Set(Array.from(descriptor.template.content.matchAll(/<([A-Z][A-Za-z0-9]*)\b/g), (match) => match[1]));
- for (const tag of componentTags) {
- assert.ok(bindings[tag] || globalComponents.has(tag), `DataGrid template component ${tag} must be imported or explicitly registered globally`);
- }
-});
-
-test("row action limit props default to undefined when omitted", () => {
- const compiled = compiledDataGridScript();
-
- // Vue Boolean props normally cast an absent prop to false. DataGrid callers
- // omit these props to mean "not restricted", so the runtime default matters.
- assert.match(compiled, /allowInsertRows:\s*\{\s*type:\s*Boolean,\s*required:\s*false,\s*default:\s*undefined\s*\}/);
- assert.match(compiled, /allowDeleteRows:\s*\{\s*type:\s*Boolean,\s*required:\s*false,\s*default:\s*undefined\s*\}/);
-});
diff --git a/packages/app-tests/dataGridSearchStateRestore.test.ts b/packages/app-tests/dataGridSearchStateRestore.test.ts
deleted file mode 100644
index 502af4c432..0000000000
--- a/packages/app-tests/dataGridSearchStateRestore.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-/**
- * The Ctrl+F overlay was the only grid search/filter surface without tab-keyed
- * persistence (structured filters and column widths already had it), so switching
- * data tabs dropped the query along with the scroll position (#8524).
- */
-function readSource(relativePath: string): string {
- return readFileSync(path.resolve(relativePath), "utf8");
-}
-
-test("DataGrid keys search persistence the same way as its pending-edit snapshot", () => {
- const source = readSource("apps/desktop/src/components/grid/DataGrid.vue");
- assert.match(source, /persistenceKey: \(\) => props\.pendingStateKey \?\? props\.cacheKey,/);
- assert.match(source, /persistenceScopeKey: \(\) => createDataGridSearchScopeKey\(props\.result\.columns\),/);
-});
-
-test("search state is restored from onMounted, not the setup body", () => {
- const source = readSource("apps/desktop/src/components/grid/DataGrid.vue");
- // watch(matchKeys) evaluates its source eagerly, and a non-empty restored query
- // would push matchState past its empty-query early return into `displayItems`,
- // which is declared thousands of lines later in this same setup.
- assert.match(source, /onMounted\(\(\) => dataGridSearch\.restorePersistedState\(\)\);/);
- const restoreIndex = source.indexOf("onMounted(() => dataGridSearch.restorePersistedState());");
- const displayItemsIndex = source.indexOf("const displayItems");
- assert.notEqual(restoreIndex, -1);
- assert.notEqual(displayItemsIndex, -1);
- assert.ok(restoreIndex < displayItemsIndex, "the restore hook is registered before displayItems is declared, so it must run in onMounted");
-});
-
-test("restoring a query does not steal the viewport from the scroll restore", () => {
- const source = readSource("apps/desktop/src/composables/useDataGridSearch.ts");
- const start = source.indexOf("watch(matchKeys");
- assert.notEqual(start, -1);
- const body = source.slice(start, source.indexOf("\n });", start));
- assert.match(body, /const restored = restoreToken;\s*\n\s*restoreToken = null;/, "the token must be consumed exactly once");
- assert.match(body, /if \(restored\) \{[\s\S]*?Math\.min\(Math\.max\(restored\.matchIndex, 0\), value\.length - 1\)[\s\S]*?return;/, "a restored match index is clamped and must not auto-navigate");
-});
-
-test("closed tabs release their persisted search state", () => {
- const source = readSource("apps/desktop/src/stores/queryStore.ts");
- const filterCalls = source.match(/clearDataGridStructuredFilterStatesForTab\(/g) ?? [];
- const searchCalls = source.match(/clearDataGridSearchStatesForTab\(/g) ?? [];
- assert.ok(filterCalls.length > 1, "expected the structured-filter cleanup call sites");
- // One import plus one call per cleanup site, mirroring the filter cache.
- assert.equal(searchCalls.length, filterCalls.length, "every structured-filter cleanup site must also clear the search cache");
-});
diff --git a/packages/app-tests/dataGridTabSwitchScrollRestore.test.ts b/packages/app-tests/dataGridTabSwitchScrollRestore.test.ts
deleted file mode 100644
index b4e25b7b9e..0000000000
--- a/packages/app-tests/dataGridTabSwitchScrollRestore.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-function readSource(relativePath: string): string {
- return readFileSync(path.resolve(relativePath), "utf8");
-}
-
-function editorSource(): string {
- return readSource("apps/desktop/src/composables/useDataGridEditor.ts");
-}
-
-test("the restore gate honours a tab-switch scroll snapshot", () => {
- assert.match(editorSource(), /pendingScrollRestore = snapshotHasEditState \|\| cached\.scrollFromTabSwitch === true \? cached\.scroll : undefined;/, "the scroll-only gate must accept snapshots carrying tab-switch provenance");
-});
-
-test("the tab-switch listener only claims its own tab", () => {
- const source = editorSource();
- const start = source.indexOf("function onBeforeTabSwitch");
- assert.notEqual(start, -1, "expected onBeforeTabSwitch in useDataGridEditor.ts");
- const body = source.slice(start, source.indexOf("\n }", start));
- assert.match(body, /detail\?\.fromTabId/, "must read fromTabId off the event detail");
- assert.match(body, /cacheKeyBelongsToTab\(key, detail\.fromTabId\)/, "must validate fromTabId against this grid's cache key");
- assert.match(body, /scrollSnapshotFromTabSwitch = true/);
-});
-
-test("the snapshot records the tab-switch provenance", () => {
- assert.match(editorSource(), /scrollFromTabSwitch: scroll \? scrollSnapshotFromTabSwitch : false,/);
-});
-
-test("an explicit scroll-to-top intent drops the provenance", () => {
- const source = editorSource();
- assert.match(source, /function clearTabSwitchScrollProvenance\(\)/);
- const reset = source.slice(source.indexOf("function resetGridVerticalScroll"));
- assert.match(reset.slice(0, reset.indexOf("\n }")), /clearTabSwitchScrollProvenance\(\);/, "resetGridVerticalScroll must clear the provenance");
- // The rows-identity watcher already clears pendingScrollRestore; it must clear
- // the cached provenance too, or a reload would inherit the old offset.
- assert.match(source, /pendingScrollRestore = undefined;\s*\n\s*clearTabSwitchScrollProvenance\(\);/);
-});
-
-test("data tab panes bound hot surface caching without adding nested caches", () => {
- const editorGroup = readSource("apps/desktop/src/components/layout/EditorGroup.vue");
- assert.match(editorGroup, /const HOT_TAB_SURFACE_CACHE_SIZE = 3;/);
- assert.match(editorGroup, /<KeepAlive\b[^>]*:max="HOT_TAB_SURFACE_CACHE_SIZE"/);
- assert.doesNotMatch(readSource("apps/desktop/src/components/layout/ContentArea.vue"), /<KeepAlive|<keep-alive/);
-});
diff --git a/packages/app-tests/dataGridTransposeLifecycle.test.ts b/packages/app-tests/dataGridTransposeLifecycle.test.ts
index 1fe146189f..d56a37b2ec 100644
--- a/packages/app-tests/dataGridTransposeLifecycle.test.ts
+++ b/packages/app-tests/dataGridTransposeLifecycle.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { useDataGridCanvasRuntime, type DataGridAnimationFrameDriver } from "../../apps/desktop/src/composables/useDataGridCanvasRuntime.ts";
import { useDataGridScrollbars } from "../../apps/desktop/src/composables/useDataGridScrollbars.ts";
@@ -159,20 +158,3 @@ test("restores the vertical grid position after a keyboard transpose round trip"
assert.equal(viewport.scrollTop, 2280, "restored position should stay within the remounted grid bounds");
});
-
-test("error result recovery participates in canvas observer remounts", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- assert.match(source, /watch\(\s*\[useCanvasGridRows, hasVisibleRows, isErrorResult\]/);
-});
-
-test("column navigation scrolls visible transpose fields before looking for the normal grid", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
- const navigation = source.slice(source.indexOf("function scrollToColumnIndex("), source.indexOf("// --- Column resize composable ---"));
- assert.match(navigation, /showColumn\(columnIndex\)/);
- assert.match(navigation, /visibleColumnIndexes\.value\.indexOf\(columnIndex\)/);
- assert.match(navigation, /if \(isTransposeMode\.value\) \{\s*scrollTransposeFieldIntoView\(visibleColIdx\);\s*return;/);
- assert.ok(navigation.indexOf("scrollTransposeFieldIntoView") < navigation.indexOf('".data-grid-scroller"'));
- assert.match(source, /scrollToItem\?\.\(visibleFieldIndex\)/);
- assert.match(source, /scroller\.scrollTop = visibleFieldIndex \* transposeRowHeight\.value/);
- assert.match(source, /'ring-2 ring-inset ring-primary': highlightedColumnIndex === visibleColumnIndexes\[index\]/);
-});
diff --git a/packages/app-tests/dataTabHeaderConnection.test.ts b/packages/app-tests/dataTabHeaderConnection.test.ts
deleted file mode 100644
index 8799881e08..0000000000
--- a/packages/app-tests/dataTabHeaderConnection.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileTemplate, parse } from "vue/compiler-sfc";
-
-const contentAreaPath = "apps/desktop/src/components/layout/ContentArea.vue";
-
-function dataModeTemplate(): string {
- const source = readFileSync(contentAreaPath, "utf8");
- const { descriptor, errors } = parse(source, { filename: contentAreaPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.template);
- const result = compileTemplate({ id: contentAreaPath, filename: contentAreaPath, source: descriptor.template.content });
- assert.deepEqual(result.errors, []);
-
- const start = descriptor.template.content.indexOf("activeTab.mode === 'data'");
- const end = descriptor.template.content.indexOf("activeTab.mode === 'redis'", start);
- assert.ok(start >= 0 && end > start, "ContentArea should keep a bounded data-mode template");
- return descriptor.template.content.slice(start, end);
-}
-
-test("data tab header shows the active connection before the table context", () => {
- const template = dataModeTemplate();
- const connectionIndex = template.indexOf("data-data-header-connection");
- const tableIndex = template.indexOf("activeDataTabTableMeta?.tableName");
-
- assert.ok(connectionIndex >= 0 && connectionIndex < tableIndex);
- assert.match(template, /v-if="activeConnection\?\.name\?\.trim\(\)"/);
- assert.match(template, /:title="activeConnection\.name"/);
- assert.doesNotMatch(template, /data-data-header-connection class="[^"]*(?:max-w-4[89]|max-w-5[0-9])/);
- // min-w floor keeps scrollWidth reporting real overflow for the measured
- // condensation tiers; chips still flex and only truncate under pressure.
- assert.match(template, /data-data-header-connection class="[^"]*min-w-12[^"]*truncate/);
-});
diff --git a/packages/app-tests/databaseExportSnapshot.test.ts b/packages/app-tests/databaseExportSnapshot.test.ts
index dd62c48719..66899b13bf 100644
--- a/packages/app-tests/databaseExportSnapshot.test.ts
+++ b/packages/app-tests/databaseExportSnapshot.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { beforeEach, test, vi } from "vitest";
const { beginDatabaseBackupSnapshot, exportDatabaseSql, rollbackManualTransaction } = vi.hoisted(() => ({
@@ -55,14 +54,6 @@ test("database export waits for terminal progress before releasing its snapshot"
assert.equal((await operation).status, "Done");
});
-test("single database export holds its snapshot until terminal progress", () => {
- const source = readFileSync("apps/desktop/src/components/export/DatabaseExportDialog.vue", "utf8");
- const singleExport = source.slice(source.indexOf("async function startExport()"), source.indexOf("async function startAllDatabasesExport()"));
-
- assert.match(singleExport, /return runDatabaseExportUntilTerminal\(request,/);
- assert.doesNotMatch(singleExport, /await api\.exportDatabaseSql\(request,/);
-});
-
test("database export snapshot is released after success", async () => {
const operation = vi.fn(async (sessionId: string | undefined) => `done:${sessionId}`);
diff --git a/packages/app-tests/databaseSearchDialog.test.ts b/packages/app-tests/databaseSearchDialog.test.ts
deleted file mode 100644
index 3f0130657b..0000000000
--- a/packages/app-tests/databaseSearchDialog.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";
-
-const dialogPath = "apps/desktop/src/components/search/DatabaseSearchDialog.vue";
-const dialogSource = readFileSync(dialogPath, "utf8");
-
-test("database search dialog compiles", () => {
- const { descriptor, errors } = parse(dialogSource, { filename: dialogPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.scriptSetup);
- compileScript(descriptor, { id: dialogPath });
- assert.ok(descriptor.template);
- const template = compileTemplate({ id: dialogPath, filename: dialogPath, source: descriptor.template!.content });
- assert.deepEqual(template.errors, []);
-});
-
-test("database search continues after each table batch without retaining a hard cap", () => {
- assert.doesNotMatch(dialogSource, /MAX_TABLES|tasks\.slice\(0/);
- assert.match(dialogSource, /progressTotal\.value = tableTasks\.value\.length/);
- assert.match(dialogSource, /await scanTableRange\(currentRun, false\)/);
- assert.match(dialogSource, /@click="continueSearch\(false\)"/);
- assert.match(dialogSource, /@click="continueSearch\(true\)"/);
- assert.match(dialogSource, /activeKeyword\.value/);
- assert.match(dialogSource, /activePerTableLimit\.value/);
- assert.match(dialogSource, /const tableResults: SearchResultItem\[\] = \[\]/);
- assert.match(dialogSource, /currentRun === runId && !cancelled\.value/);
-});
diff --git a/packages/app-tests/driverDownloadSource.test.ts b/packages/app-tests/driverDownloadSource.test.ts
deleted file mode 100644
index d4f38b653e..0000000000
--- a/packages/app-tests/driverDownloadSource.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-function source(relativePath: string): string {
- return readFileSync(path.resolve(relativePath), "utf8");
-}
-
-test("shares the configured download source with agent driver management", () => {
- const app = source("apps/desktop/src/App.vue");
- const driverStore = source("apps/desktop/src/components/config/DriverStoreDialog.vue");
- const backendApi = source("apps/desktop/src/lib/backend/api.ts");
-
- assert.match(driverStore, /driverStoreTab === 'agent' && !isWeb/);
- assert.match(driverStore, /:model-value="settingsStore\.editorSettings\.updateDownloadSource"/);
- assert.match(driverStore, /settingsStore\.updateEditorSettings\(\{ updateDownloadSource: value \}\)/);
- assert.match(driverStore, /void forceRefresh\(\)\.catch\(\(\) => undefined\)/);
-
- assert.match(backendApi, /backend\.listInstalledAgents\(useSettingsStore\(\)\.editorSettings\.updateDownloadSource\)/);
- assert.match(backendApi, /backend\.installAgent\(dbType, useSettingsStore\(\)\.editorSettings\.updateDownloadSource(?:, operationId)?\)/);
- assert.match(backendApi, /backend\.upgradeAllAgents\(useSettingsStore\(\)\.editorSettings\.updateDownloadSource(?:, operationId)?\)/);
- assert.match(backendApi, /backend\.reinstallJre\(jreKey, useSettingsStore\(\)\.editorSettings\.updateDownloadSource(?:, operationId)?\)/);
- assert.match(app, /const drivers = await api\.listInstalledAgents\(\)/);
- assert.doesNotMatch(app, /invoke<[^>]+>\("list_installed_agents"\)/);
-});
diff --git a/packages/app-tests/driverStoreInstallStatus.test.ts b/packages/app-tests/driverStoreInstallStatus.test.ts
deleted file mode 100644
index 34e5c0a9e4..0000000000
--- a/packages/app-tests/driverStoreInstallStatus.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-function source(relativePath: string): string {
- return readFileSync(path.resolve(relativePath), "utf8");
-}
-
-test("Driver Manager exposes an install-status filter next to search", () => {
- const driverStore = source("apps/desktop/src/components/config/DriverStoreDialog.vue");
-
- assert.match(driverStore, /data-driver-status-filter/);
- assert.match(driverStore, /driverStatusFilter = ref<DriverInstallStatusFilter>\("all"\)/);
- assert.match(driverStore, /partitionDriversByInstallStatus\(builtinDriverRows\.value, driverStatusFilter\.value\)/);
- assert.match(driverStore, /upgradeAllDriverTypes\(builtinDriverRows\.value, driverStatusFilter\.value\)/);
- assert.match(driverStore, /if \(!upgradeAllMatchesFullUpdateSet\(builtinDriverRows\.value, driverStatusFilter\.value\)\) return/);
- assert.match(driverStore, /upgradeAllMatchesFullUpdateSet\(builtinDriverRows\.value, driverStatusFilter\.value\)/);
- assert.match(driverStore, /driverStatusFilter\.value = "all"/);
- assert.match(driverStore, /shouldApplyDriverStoreFocus\(lastAppliedFocusKey\.value, key, focusChanged\)/);
- assert.match(driverStore, /driverStoreFocusRowIsRenderable\(focus, drivers\.value\.length, builtinDriverRows\.value\)/);
- const applyIdx = driverStore.indexOf("if (!shouldApplyDriverStoreFocus");
- const tabIdx = driverStore.indexOf('driverStoreTab.value = "agent"');
- assert.ok(applyIdx >= 0, "focus apply guard");
- assert.ok(tabIdx > applyIdx, "Agent tab switch must sit behind the one-shot focus guard");
- assert.match(driverStore, /showInstalledEmptyState/);
- assert.match(driverStore, /showAvailableEmptyState/);
- assert.match(driverStore, /driverStore\.noAvailableDrivers/);
- assert.doesNotMatch(driverStore, /selectStableDrivers\(categoryFilteredDrivers/);
- assert.doesNotMatch(driverStore, /selectUpdatableDrivers\(builtinDriverRows/);
- assert.equal([...driverStore.matchAll(/<DriverStoreAgentRow/g)].length, 3);
-});
-
-test("driver rows show a text Installed badge beside the name", () => {
- const row = source("apps/desktop/src/components/config/DriverStoreAgentRow.vue");
-
- assert.match(row, /driverStore\.installedBadge/);
- assert.match(row, /driver-store-installed-badge/);
- assert.match(row, /driver-store-agent-row--installed/);
- assert.match(row, /data-driver-store-focus/);
- assert.match(row, /driver-store-local-import-button/);
-});
diff --git a/packages/app-tests/editorTabSwitchViewportRestore.test.ts b/packages/app-tests/editorTabSwitchViewportRestore.test.ts
deleted file mode 100644
index 75265e811e..0000000000
--- a/packages/app-tests/editorTabSwitchViewportRestore.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-/**
- * The shared editor swaps documents on tab switches (per-tab EditorState cache
- * since the undo-isolation fix). Both branches of that swap — the cached
- * `setState` path AND the uncached `swapEditorDocument` path (first activation
- * in this editor instance, or a tab evicted from the state cache) — must
- * restore the incoming tab's saved cursor and scroll position. Skipping the
- * restore on the uncached branch is what made switching back to a tab land on
- * line 1 instead of the previous viewport (#8374).
- */
-function activateTabDocumentSource(): string {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- const start = source.indexOf("function activateTabDocument");
- assert.notEqual(start, -1, "expected activateTabDocument in useQueryEditorDocumentState.ts");
- const end = source.indexOf("\n }", start);
- assert.notEqual(end, -1, "expected activateTabDocument closing brace");
- return source.slice(start, end);
-}
-
-test("uncached tab activation restores the saved cursor and scroll position", () => {
- const source = activateTabDocumentSource();
- assert.match(source, /if \(!cached\) \{[\s\S]*?swapEditorDocument\(doc\);[\s\S]*?restoreEditorSelection\([^;]*\);[\s\S]*?restoreEditorViewport\([^;]*\);[\s\S]*?return;/, "the swapEditorDocument branch must restore selection and viewport before returning");
-});
-
-test("uncached tabs without saved state do not inherit the previous tab position", () => {
- const source = activateTabDocumentSource();
- assert.match(source, /restoreEditorSelection\(props\.initialSelection \?\? \{ anchor: 0, head: 0 \}, !props\.initialViewport\);/);
- assert.match(source, /restoreEditorViewport\(props\.initialViewport \?\? \{ scrollTop: 0, scrollLeft: 0 \}\);/);
-});
-
-test("cached tab activation keeps restoring selection and viewport", () => {
- const source = activateTabDocumentSource();
- assert.match(source, /currentView\.setState\(cached\);/);
- assert.match(source, /currentView\.setState\(cached\);[\s\S]*?restoreEditorSelection\(undefined, !props\.initialViewport\);\s*restoreEditorViewport\(\);/);
-});
-
-test("viewport restore prefers the per-tab saved viewport", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- assert.match(source, /function restoreEditorViewport\(viewport = props\.initialViewport \?\? latestViewport\) \{/);
-});
-
-test("captures the outgoing editor viewport before KeepAlive deactivation", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- assert.match(source, /function captureEditorStateBeforeTabSwitch\(event: Event\) \{/);
- assert.match(source, /fromTabId !== props\.tabId/);
- assert.match(source, /captureEditorStateBeforeTabSwitch[\s\S]*?flushEditorViewport\(\);[\s\S]*?flushEditorSelection\(\);[\s\S]*?emit\("editorStateFlushed"\);/);
- assert.match(source, /window\.addEventListener\(BEFORE_TAB_SWITCH_EVENT, captureEditorStateBeforeTabSwitch\)/);
- assert.match(source, /window\.removeEventListener\(BEFORE_TAB_SWITCH_EVENT, captureEditorStateBeforeTabSwitch\)/);
-});
-
-test("does not flush a reset viewport after a tab-switch capture", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- assert.match(source, /let tabSwitchStateCaptured = false;/);
- assert.match(source, /tabSwitchStateCaptured = true;/);
- assert.match(source, /const stateWasCapturedBeforeTabSwitch = tabSwitchStateCaptured;[\s\S]*?tabSwitchStateCaptured = false;[\s\S]*?if \(runtime\.editorIsActive && !stateWasCapturedBeforeTabSwitch\) \{[\s\S]*?flushEditorViewport\(\);/);
- assert.match(source, /if \(!tabSwitchStateCaptured\) flushEditorViewport\(\);/);
-});
-
-test("does not flush an editor again when KeepAlive evicts it after deactivation", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- assert.match(source, /if \(runtime\.editorIsActive && !stateWasCapturedBeforeTabSwitch\) \{[\s\S]*?flushEditorViewport\(\);/);
-});
-
-test("restores a saved cursor into view when no viewport was persisted", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- const editorSource = readFileSync(path.resolve("apps/desktop/src/components/editor/QueryEditor.vue"), "utf8");
- assert.match(editorSource, /restoreEditorSelection\(props\.initialSelection, !props\.initialViewport\);/);
- assert.match(source, /function restoreEditorSelection\(selection = props\.initialSelection \?\? latestSelection, scrollIntoView = false\)/);
- assert.match(source, /view\.value\.dispatch\(\{ selection: normalizedSelection, scrollIntoView \}\);/);
-});
-
-test("re-applies the viewport when saved SQL content hydrates after mount", () => {
- const source = readFileSync(path.resolve("apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
- assert.match(source, /watch\(\s*\(\) => props\.initialViewport,[\s\S]*?previousViewport[\s\S]*?latestViewport = \{ \.\.\.viewport \};[\s\S]*?restoreEditorViewport\(viewport\);/);
- assert.match(source, /watch\(\s*\(\) => props\.initialSelection,[\s\S]*?previousSelection[\s\S]*?restoreEditorSelection\(selection, !props\.initialViewport\);/);
- assert.match(source, /if \(attempts >= 32\)/);
-});
diff --git a/packages/app-tests/editorToolbarContextSwitching.test.ts b/packages/app-tests/editorToolbarContextSwitching.test.ts
deleted file mode 100644
index 2bb585735b..0000000000
--- a/packages/app-tests/editorToolbarContextSwitching.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-const appPath = "apps/desktop/src/App.vue";
-const contractPath = "apps/desktop/src/components/layout/editorToolbarActions.ts";
-
-// App.vue 是根组件,测试无法挂载;而这族回归(#8218,同 #8216)恰恰是
-// 「契约 tabId-first、实现 value-first」的 string/string 参数错位,结构化
-// 类型检查对此不可见,所以这里用源码钉住契约两侧的参数顺序。
-function functionSource(name: string): string {
- const source = readFileSync(appPath, "utf8");
- const start = source.indexOf(`function ${name}`);
- assert.ok(start >= 0, `App.vue should define ${name}`);
- const relativeEnd = source.slice(start).search(/\n(?:async\s+)?function\s+[A-Za-z]/);
- return source.slice(start, relativeEnd > 0 ? start + relativeEnd : undefined);
-}
-
-test("toolbar context switchers resolve the acting tab from their first parameter (#8218)", () => {
- const signatures: Array<[name: string, expected: RegExp]> = [
- ["changeActiveConnection", /^function changeActiveConnection\(tabId: string, connectionId: string\)/],
- ["changeActiveDatabase", /^function changeActiveDatabase\(tabId: string, database: string\)/],
- ["changeActiveCatalog", /^function changeActiveCatalog\(tabId: string, catalog: string \| undefined, database: string\)/],
- ["changeActiveSchema", /^function changeActiveSchema\(tabId: string, schema: string \| undefined\)/],
- ];
- for (const [name, expected] of signatures) {
- const body = functionSource(name);
- assert.match(body, expected);
- assert.match(body, /resolveToolbarTab\(tabId\)/);
- }
-});
-
-test("App provides the switchers directly so the injected contract order reaches them", () => {
- const appSource = readFileSync(appPath, "utf8");
- for (const name of ["changeConnection", "changeCatalog", "changeDatabase", "changeSchema"]) {
- assert.match(appSource, new RegExp(`${name}: changeActive[A-Za-z]+,`));
- }
-});
-
-test("the injected toolbar action contract keeps tab id as the first parameter", () => {
- const contract = readFileSync(contractPath, "utf8");
- assert.match(contract, /changeConnection\(tabId: string, connectionId: string\)/);
- assert.match(contract, /changeCatalog\(tabId: string, catalog: string \| undefined, database: string\)/);
- assert.match(contract, /changeDatabase\(tabId: string, database: string\)/);
- assert.match(contract, /changeSchema\(tabId: string, schema: string \| undefined\)/);
-});
diff --git a/packages/app-tests/elasticsearchJsonResponse.test.ts b/packages/app-tests/elasticsearchJsonResponse.test.ts
index 06755e7e4f..162ffb5c47 100644
--- a/packages/app-tests/elasticsearchJsonResponse.test.ts
+++ b/packages/app-tests/elasticsearchJsonResponse.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { elasticsearchJsonResponseForResult } from "../../apps/desktop/src/lib/elasticsearch/elasticsearchJsonResponse.ts";
import type { QueryResult } from "../../apps/desktop/src/types/database.ts";
@@ -96,12 +95,3 @@ test("uses the supplied result source statement to classify the response", () =>
assert.equal(elasticsearchJsonResponseForResult("elasticsearch", "SELECT * FROM products", result), undefined);
assert.equal(elasticsearchJsonResponseForResult("elasticsearch", undefined, result), undefined);
});
-
-test("routes focused find shortcuts to both Elasticsearch response-panel entry points", () => {
- const contentArea = readFileSync(new URL("../../apps/desktop/src/components/layout/ContentArea.vue", import.meta.url), "utf8");
- const focusSearch = contentArea.slice(contentArea.indexOf("function focusSearch("), contentArea.indexOf("function refreshData()"));
-
- assert.match(focusSearch, /elasticsearchJsonResponsePanelRef\.value\?\.focusSearch\(\)/);
- assert.match(contentArea, /<ElasticsearchJsonResponsePanel v-if="activeElasticsearchJsonResponse" ref="elasticsearchJsonResponsePanelRef"/);
- assert.match(contentArea, /<ElasticsearchJsonResponsePanel v-else-if="showElasticsearchRawJson && activeElasticsearchRawBody" ref="elasticsearchJsonResponsePanelRef"/);
-});
diff --git a/packages/app-tests/externalSqlFileStartup.test.ts b/packages/app-tests/externalSqlFileStartup.test.ts
index 2f400fa88f..6a3b44dd6f 100644
--- a/packages/app-tests/externalSqlFileStartup.test.ts
+++ b/packages/app-tests/externalSqlFileStartup.test.ts
@@ -120,33 +120,3 @@ test("desktop SQL file opening is released when persisted tab restoration reject
assert.deepEqual(events, ["restore-tabs", "open-file"]);
});
-
-test("cold-start SQL files wait for restored tabs before opening", () => {
- const openPathStart = appSource.indexOf("async function openSqlFilePath");
- const openPathEnd = appSource.indexOf("async function openPendingSqlFiles", openPathStart);
- assert.ok(openPathStart >= 0 && openPathEnd > openPathStart);
-
- const openPathSource = appSource.slice(openPathStart, openPathEnd);
- const initializationWait = openPathSource.indexOf("await desktopOpenTabsRestorationBarrier?.settled");
- const fileRead = openPathSource.indexOf("api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb))");
- const tabOpen = openPathSource.indexOf("queryStore.openExternalSqlFile");
- assert.ok(initializationWait >= 0);
- assert.ok(initializationWait < fileRead);
- assert.ok(fileRead < tabOpen);
-
- const mountedStart = appSource.indexOf("onMounted(async () =>");
- const mountedEnd = appSource.indexOf("onUnmounted(", mountedStart);
- assert.ok(mountedStart >= 0 && mountedEnd > mountedStart);
-
- const mountedSource = appSource.slice(mountedStart, mountedEnd);
- const barrierCreation = mountedSource.indexOf("desktopOpenTabsRestorationBarrier = createOpenTabsRestorationBarrier()");
- const initializationStart = mountedSource.indexOf("void initApp()", barrierCreation);
- const listenerSetup = mountedSource.indexOf("setupTauriListeners()", initializationStart);
- const pendingFileOpen = mountedSource.indexOf("openPendingSqlFiles()");
- assert.ok(barrierCreation >= 0);
- assert.ok(initializationStart >= 0);
- assert.ok(barrierCreation < initializationStart);
- assert.ok(initializationStart < listenerSetup);
- assert.ok(listenerSetup < pendingFileOpen);
- assert.ok(initializationStart < pendingFileOpen);
-});
diff --git a/packages/app-tests/gridfsBrowserPagination.test.ts b/packages/app-tests/gridfsBrowserPagination.test.ts
index b7c3cf449c..fc48a84fdc 100644
--- a/packages/app-tests/gridfsBrowserPagination.test.ts
+++ b/packages/app-tests/gridfsBrowserPagination.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { clampGridFsPage, gridFsTotalPages, paginateGridFsItems } from "../../apps/desktop/src/lib/document/gridfsPagination.ts";
@@ -12,20 +11,3 @@ test("paginates GridFS files with a clamped page index", () => {
assert.deepEqual(paginateGridFsItems(files, 1, 2).map((file) => file.id), ["f3", "f4"]);
assert.deepEqual(paginateGridFsItems(files, 9, 2).map((file) => file.id), ["f5"]);
});
-
-test("GridFS browsers keep a scrollable flex layout", () => {
- const bucketBrowser = readFileSync("apps/desktop/src/components/document/MongoBucketBrowser.vue", "utf8");
- const gridfsBrowser = readFileSync("apps/desktop/src/components/document/MongoGridFsBrowser.vue", "utf8");
-
- assert.match(bucketBrowser, /class="flex h-full min-h-0 flex-col overflow-hidden"/);
- assert.match(bucketBrowser, /v-else class="min-h-0 flex flex-1 flex-col overflow-hidden xl:flex-row/);
- assert.match(gridfsBrowser, /class="flex h-full min-h-0 flex-col overflow-hidden"/);
- assert.match(gridfsBrowser, /v-else class="min-h-0 flex flex-1 flex-col overflow-hidden xl:flex-row/);
-});
-
-test("GridFS file browser keeps metadata columns compact on a single line", () => {
- const bucketBrowser = readFileSync("apps/desktop/src/components/document/MongoBucketBrowser.vue", "utf8");
-
- assert.match(bucketBrowser, /<table class="min-w-full border-collapse text-\[13px\]">/);
- assert.match(bucketBrowser, /whitespace-nowrap tabular-nums/);
-});
diff --git a/packages/app-tests/hbaseBrowserRefresh.test.ts b/packages/app-tests/hbaseBrowserRefresh.test.ts
index 53e28342c8..5034bd6d73 100644
--- a/packages/app-tests/hbaseBrowserRefresh.test.ts
+++ b/packages/app-tests/hbaseBrowserRefresh.test.ts
@@ -1,50 +1,7 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { DEFAULT_HBASE_ROW_LIMIT, HBASE_ROW_LIMIT_STORAGE_KEY, loadHBaseRowLimit, normalizeHBaseRowLimit, saveHBaseRowLimit } from "../../apps/desktop/src/lib/hbase/hbaseBrowserPreferences.ts";
-function functionBody(source: string, name: string): string {
- const signatureIndex = source.indexOf(`async function ${name}(`);
- assert.notEqual(signatureIndex, -1, `Could not find function ${name}`);
- const bodyStart = source.indexOf("{", signatureIndex);
- let depth = 0;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- if (source[index] === "}") {
- depth -= 1;
- if (depth === 0) return source.slice(bodyStart + 1, index);
- }
- }
- throw new Error(`Could not parse function ${name}`);
-}
-
-test("HBase table DDL refreshes the visible object list instead of reusing loaded children", () => {
- const source = readFileSync("apps/desktop/src/components/hbase/HBaseBrowser.vue", "utf8");
-
- for (const name of ["createTable", "deleteTable"]) {
- const body = functionBody(source, name);
- assert.match(body, /await connectionStore\.refreshObjectListTreeNode\(props\.connectionId, props\.namespace\)/);
- assert.doesNotMatch(body, /connectionStore\.loadTables/);
- }
-});
-
-test("HBase grid disables unsupported offset and infinite-scroll pagination", () => {
- const source = readFileSync("apps/desktop/src/components/hbase/HBaseBrowser.vue", "utf8");
- assert.match(source, /<DataGrid[\s\S]*:pagination-enabled="false"/);
-});
-
-test("HBase table context menu exposes its REST-backed delete action", () => {
- const source = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const menuStart = source.indexOf('if (currentDatabaseType() === "hbase" && node.type === "table")');
- const menuEnd = source.indexOf("return true;", menuStart);
- const menu = source.slice(menuStart, menuEnd);
-
- assert.match(menu, /label: t\("hbase\.deleteTable"\)/);
- assert.match(menu, /action: requestDeleteHBaseTable/);
- assert.match(source, /await api\.hbaseDeleteTable\(node\.connectionId, node\.database, node\.label\)/);
- assert.match(source, /await connectionStore\.refreshObjectListTreeNode\(node\.connectionId, node\.database\)/);
-});
-
test("HBase row scan limit is normalized and persisted", () => {
const previousDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const values = new Map<string, string>();
diff --git a/packages/app-tests/mongoSyntaxDiagnostics.test.ts b/packages/app-tests/mongoSyntaxDiagnostics.test.ts
index 0bc22893a6..ef0b899865 100644
--- a/packages/app-tests/mongoSyntaxDiagnostics.test.ts
+++ b/packages/app-tests/mongoSyntaxDiagnostics.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { buildMongoSyntaxDiagnostics, shouldRunMongoDiagnostics } from "../../apps/desktop/src/lib/mongo/mongoSyntaxDiagnostics";
@@ -122,9 +121,4 @@ test("keeps completed diagnostics while the cursor is in an unfinished command",
const unfinished = underlined(source, 0).find((diagnostic) => diagnostic.severity === "error");
assert.match(unfinished!.message, /unclosed/i);
-
- const diagnosticsSource = readFileSync("apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts", "utf8");
- const mongoBranch = diagnosticsSource.slice(diagnosticsSource.indexOf('if (props.databaseType === "mongodb")'), diagnosticsSource.indexOf('if (props.databaseType === "redis")'));
- assert.doesNotMatch(mongoBranch, /shouldRunMongoDiagnostics/);
- assert.match(mongoBranch, /setSemanticDiagnostics\(buildMongoSyntaxDiagnostics\(sql, cursor\)\)/);
});
diff --git a/packages/app-tests/mqttPayloadCodec.test.ts b/packages/app-tests/mqttPayloadCodec.test.ts
index b0bd594ace..d74f6fd77e 100644
--- a/packages/app-tests/mqttPayloadCodec.test.ts
+++ b/packages/app-tests/mqttPayloadCodec.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { decodePayload, encodePayload } from "@/lib/mqtt/mqttPayloadCodec";
@@ -49,18 +48,7 @@ test("MQTT empty payloads remain empty", () => {
assert.equal(decodePayload("", "plaintext"), "");
});
-test("MQTT JSON publishing sends canonical bytes instead of the original text", () => {
- const source = readFileSync("apps/desktop/src/components/mqtt/MqttPublishDialog.vue", "utf8");
- assert.match(source, /payloadText:\s*encoding\.value === "plaintext" \? payloadText\.value : null/);
- assert.doesNotMatch(source, /encoding\.value === "plaintext" \|\| encoding\.value === "json"/);
-});
-
test("MQTT 中文 JSON Payload 保留 UTF-8 文本且不添加换行符", () => {
const encoded = encodePayload('{\n "消息": "温度正常",\n "设备": "客厅传感器"\n}', "json");
assert.equal(decodePayload(encoded, "plaintext"), '{"消息":"温度正常","设备":"客厅传感器"}');
});
-test("MQTT JSON placeholder uses a named interpolation for literal braces", () => {
- const source = readFileSync("apps/desktop/src/components/mqtt/MqttPublishDialog.vue", "utf8");
- assert.match(source, /mqttPayloadPlaceholderJson", \{ example:/);
- assert.doesNotMatch(source, /mqttPayloadPlaceholderJson"\);/);
-});
diff --git a/packages/app-tests/objectBrowserTableInfo.test.ts b/packages/app-tests/objectBrowserTableInfo.test.ts
index 5fc22f0981..7063ba3f83 100644
--- a/packages/app-tests/objectBrowserTableInfo.test.ts
+++ b/packages/app-tests/objectBrowserTableInfo.test.ts
@@ -1,5 +1,4 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { filterObjectBrowserTableColumns } from "../../apps/desktop/src/lib/table/objectBrowserTableInfo.ts";
@@ -47,20 +46,3 @@ test("returns every column for empty searches and preserves match order", () =>
["note", "empty_note"],
);
});
-
-test("keeps the data-grid table properties search on the shared column filter", () => {
- const source = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
-
- assert.match(source, /filterObjectBrowserTableColumns\(tableInfoColumns\.value, searchQuery\.value\)/);
-});
-
-test("both table DDL surfaces use the persisted wrapping preference", () => {
- const sources = ["apps/desktop/src/components/grid/DataGrid.vue", "apps/desktop/src/components/objects/ObjectBrowser.vue"].map((path) => readFileSync(path, "utf8"));
-
- for (const source of sources) {
- assert.doesNotMatch(source, /const (?:ddlWrap|tableInfoWrap) = ref\(true\)/);
- assert.match(source, /:class="\{ 'bg-accent': settingsStore\.editorSettings\.tableDdlWordWrap \}"/);
- assert.match(source, /:class="settingsStore\.editorSettings\.tableDdlWordWrap \? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"/);
- assert.match(source, /settingsStore\.updateEditorSettings\(\{\s*tableDdlWordWrap: !settingsStore\.editorSettings\.tableDdlWordWrap,?\s*\}\)/);
- }
-});
diff --git a/packages/app-tests/objectSourceOpenFeedback.test.ts b/packages/app-tests/objectSourceOpenFeedback.test.ts
deleted file mode 100644
index d4f5410e81..0000000000
--- a/packages/app-tests/objectSourceOpenFeedback.test.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-function read(relativePath: string): string {
- return readFileSync(relativePath, "utf8");
-}
-
-function functionBody(source: string, name: string): string {
- const signature = `function ${name}(`;
- const asyncSignature = `async ${signature}`;
- const signatureIndex = source.indexOf(asyncSignature) >= 0 ? source.indexOf(asyncSignature) : source.indexOf(signature);
- assert.notEqual(signatureIndex, -1, `Could not find function ${name}`);
- const bodyStart = source.indexOf("{", signatureIndex);
- assert.notEqual(bodyStart, -1, `Could not find body for ${name}`);
-
- let depth = 0;
- for (let index = bodyStart; index < source.length; index += 1) {
- const char = source[index];
- if (char === "{") depth += 1;
- if (char === "}") {
- depth -= 1;
- if (depth === 0) return source.slice(bodyStart + 1, index);
- }
- }
- throw new Error(`Could not parse body for ${name}`);
-}
-
-// issue #9035:打开对象源码必须「先出 UI 再加载」。加载态要有可见落点
-// (tab 栏 + tab 内容区)、失败要能就地重试、连接建立也要罩在弹窗的加载态之内。
-test("object source loading feedback is visible in the tab bar and the tab body", () => {
- const contentArea = read("apps/desktop/src/components/layout/ContentArea.vue");
- const tabStatus = read("apps/desktop/src/components/layout/TabExecutionStatus.vue");
-
- assert.match(contentArea, /activeTab\.sourceLoad && !activeTab\.sourceLoad\.error/);
- assert.match(contentArea, /:elapsed-seconds="sourceLoadElapsedSeconds"/);
- assert.match(contentArea, /data-object-source-load-error/);
- assert.match(contentArea, /queryStore\.retryObjectSourceTab\(activeTab\.id\)/);
-
- assert.match(tabStatus, /props\.tab\.sourceLoad && !props\.tab\.sourceLoad\.error/);
- // 失败态由内容区的错误 + Retry 表达,tab 栏不应继续转圈
- assert.match(tabStatus, /labelKey/);
-});
-
-test("the object source dialog owns the connection it waits for", () => {
- const dialog = read("apps/desktop/src/components/objects/ObjectSourceDialog.vue");
- const loadBody = functionBody(dialog, "loadSource");
-
- // 调用方不再先 await ensureConnected 才开弹窗,连接必须发生在弹窗的 loading 之内
- const connectIndex = loadBody.indexOf("ensureConnected");
- const fetchIndex = loadBody.indexOf("loadObjectSourceWithRoutineFallback");
- assert.ok(connectIndex >= 0, "ObjectSourceDialog.loadSource must own ensureConnected");
- assert.ok(fetchIndex >= 0, "ObjectSourceDialog.loadSource must fetch the source");
- assert.ok(connectIndex < fetchIndex, "connect must happen before the source fetch");
-});
-
-test("query-tab entry no longer blocks the sidebar on connect", () => {
- const connectionTree = read("apps/desktop/src/components/sidebar/ConnectionTree.vue");
- const openBody = functionBody(connectionTree, "openSidebarObjectSource");
-
- // 弹窗立即挂载;此前的 await ensureConnected 制造了没有反馈的死等窗口
- // (断言调用形态,注释里提到这个名字不算)
- assert.doesNotMatch(openBody, /ensureConnected\(/);
- assert.match(openBody, /sidebarObjectSourceOpen\.value = true/);
-});
-
-test("query-editor object source entry uses the same visible loading path", () => {
- const app = read("apps/desktop/src/App.vue");
- const openBody = functionBody(app, "onOpenObjectSource");
-
- assert.match(openBody, /queryStore\.openObjectSourceTabPending\(\{/);
- assert.match(openBody, /queryEditorObjectSourceTarget\.value =/);
- assert.match(openBody, /showQueryEditorObjectSourceDialog\.value = true/);
- assert.doesNotMatch(openBody, /ensureConnected\(/);
- assert.doesNotMatch(openBody, /api\.getObjectSource\(/);
-});
-
-test("object source load state is runtime-only and never restored from disk", () => {
- const persistence = read("apps/desktop/src/lib/app/openTabsPersistence.ts");
- const types = read("apps/desktop/src/types/database.ts");
- const serializeBody = functionBody(persistence, "serializeOpenTabs");
-
- // tab 类型上带着重试所需的请求身份
- assert.match(types, /sourceLoad\?: \{/);
- assert.match(types, /request: \{\n\s+name: string;\n\s+objectType: ObjectSourceKind;/);
- // 不落盘:否则重启后 tab 会永久停在「加载中」
- assert.doesNotMatch(serializeBody, /sourceLoad/);
- assert.match(persistence, /sourceLoad: undefined/);
-});
diff --git a/packages/app-tests/phoenixConnection.test.ts b/packages/app-tests/phoenixConnection.test.ts
index 62c5371e9e..e31cbe3978 100644
--- a/packages/app-tests/phoenixConnection.test.ts
+++ b/packages/app-tests/phoenixConnection.test.ts
@@ -1,6 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
import { test, vi } from "vitest";
import {
isPhoenixRuntimePath,
@@ -245,14 +243,3 @@ test("does not provision Phoenix runtimes for another JDBC profile", async () =>
assert.equal(runtime.jdbcPluginStatus.mock.calls.length, 0);
assert.equal(runtime.listJdbcMavenBundles.mock.calls.length, 0);
});
-
-test("registers Apache Phoenix as a declarative JDBC picker profile with both modes", () => {
- const profileSource = readFileSync(path.resolve("apps/desktop/src/lib/database/phoenixConnection.ts"), "utf8");
- const registrySource = readFileSync(path.resolve("apps/desktop/src/lib/database/jdbcProductProfiles.ts"), "utf8");
-
- assert.match(profileSource, /id:\s*PHOENIX_DRIVER_PROFILE/);
- assert.match(profileSource, /match:\s*\{\s*dbType:\s*"jdbc",\s*driverProfile:\s*PHOENIX_DRIVER_PROFILE\s*\}/);
- assert.match(profileSource, /id:\s*"direct"/);
- assert.match(profileSource, /id:\s*"query-server"/);
- assert.match(registrySource, /JDBC_PRODUCT_PROFILES\s*=\s*\[PHOENIX_JDBC_PRODUCT_PROFILE\]/);
-});
diff --git a/packages/app-tests/phoenixDriverStore.test.ts b/packages/app-tests/phoenixDriverStore.test.ts
deleted file mode 100644
index 20c1042008..0000000000
--- a/packages/app-tests/phoenixDriverStore.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "vitest";
-
-function source(relativePath: string): string {
- return readFileSync(path.resolve(relativePath), "utf8");
-}
-
-test("renders registered managed JDBC rows in Driver Manager", () => {
- const driverStore = source("apps/desktop/src/components/config/DriverStoreDialog.vue");
-
- assert.match(driverStore, /managedJdbcDriverRows\(jdbcMavenBundles\.value, jdbcPluginStatus\.value\)/);
- assert.match(driverStore, /isManagedJdbcBuiltinDriver\(dbType: string\)/);
- assert.match(driverStore, /isManagedJdbcDriver\(dbType\)/);
-});
-
-test("dispatches install and uninstall through the shared managed JDBC lifecycle", () => {
- const driverStore = source("apps/desktop/src/components/config/DriverStoreDialog.vue");
-
- assert.match(driverStore, /installRegisteredManagedJdbcDriver\(dbType, jdbcMavenBundles\.value, jdbcPluginStatus\.value, api\)/);
- assert.match(driverStore, /uninstallRegisteredManagedJdbcDriver\(dbType, jdbcMavenBundles\.value, api\)/);
-});
-
-test("routes managed product runtime failures back to the registered Driver Manager row", () => {
- const connectionDialog = source("apps/desktop/src/components/connection/ConnectionDialog.vue");
-
- assert.match(connectionDialog, /connectionErrorRawDetail\.value = message/);
- assert.match(connectionDialog, /isRegisteredJdbcProductRuntimeInstallError\(form\.value, connectionErrorRawDetail\.value\)/);
- assert.match(connectionDialog, /isJdbcProductConnection\.value \? agentDriverFocus\.value : \{ target: "tab", tab: "jdbc" \}/);
- assert.match(connectionDialog, /emit\('openDriverStore', agentDriverFocus\)/);
-});
-
-test("treats each registered product mode as one complete runtime in the connection selector", () => {
- const connectionDialog = source("apps/desktop/src/components/connection/ConnectionDialog.vue");
-
- assert.match(connectionDialog, /jdbcProductManagedRuntimePaths\(productProfile, jdbcMavenBundles\.value, productMode\.id\)/);
- assert.match(connectionDialog, /label: t\(productProfile\.runtimeLabelKey/);
- assert.match(connectionDialog, /!isJdbcProductManagedMavenPath\(activeJdbcProductProfile\.value!, path\)/);
- assert.doesNotMatch(connectionDialog, /async function loadJdbcDrivers\(\) \{\s*if \(!isDesktop\) return;/);
-});
-
-test("keeps product-specific branches out of generic integration files", () => {
- for (const file of ["apps/desktop/src/components/connection/ConnectionDialog.vue", "apps/desktop/src/components/config/DriverStoreDialog.vue", "apps/desktop/src/App.vue"]) {
- const contents = source(file);
- assert.doesNotMatch(contents, /from ["']@\/lib\/database\/phoenix/);
- assert.doesNotMatch(contents, /PHOENIX_DRIVER_PROFILE/);
- assert.doesNotMatch(contents, /isPhoenix|ensurePhoenix|phoenixConnectionMode/);
- }
-});
diff --git a/packages/app-tests/postgresLegacyTlsI18n.test.ts b/packages/app-tests/postgresLegacyTlsI18n.test.ts
deleted file mode 100644
index 59ec7eecd2..0000000000
--- a/packages/app-tests/postgresLegacyTlsI18n.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { strict as assert } from "node:assert";
-import { test } from "vitest";
-import az from "../../apps/desktop/src/i18n/locales/az.ts";
-import en from "../../apps/desktop/src/i18n/locales/en.ts";
-import es from "../../apps/desktop/src/i18n/locales/es.ts";
-import it from "../../apps/desktop/src/i18n/locales/it.ts";
-import ja from "../../apps/desktop/src/i18n/locales/ja.ts";
-import ko from "../../apps/desktop/src/i18n/locales/ko.ts";
-import tr from "../../apps/desktop/src/i18n/locales/tr.ts";
-import ptBR from "../../apps/desktop/src/i18n/locales/pt-BR.ts";
-import zhCN from "../../apps/desktop/src/i18n/locales/zh-CN.ts";
-import zhTW from "../../apps/desktop/src/i18n/locales/zh-TW.ts";
-
-test("every locale defines the PostgreSQL legacy TLS labels", () => {
- const locales = { az, en, es, it, ja, ko, ptBR, tr, zhCN, zhTW } as const;
-
- for (const [localeName, locale] of Object.entries(locales)) {
- assert.ok(locale.connection.postgresLegacyTls.length > 0, `${localeName}: connection.postgresLegacyTls`);
- assert.ok(locale.connection.postgresLegacyTlsHint.length > 0, `${localeName}: connection.postgresLegacyTlsHint`);
- }
-});
diff --git a/packages/app-tests/queryMessagesView.test.ts b/packages/app-tests/queryMessagesView.test.ts
index 1e4a802914..4446063f93 100644
--- a/packages/app-tests/queryMessagesView.test.ts
+++ b/packages/app-tests/queryMessagesView.test.ts
@@ -1,7 +1,5 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
-import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";
import az from "../../apps/desktop/src/i18n/locales/az.ts";
import en from "../../apps/desktop/src/i18n/locales/en.ts";
import es from "../../apps/desktop/src/i18n/locales/es.ts";
@@ -13,80 +11,6 @@ import ptBR from "../../apps/desktop/src/i18n/locales/pt-BR.ts";
import zhCN from "../../apps/desktop/src/i18n/locales/zh-CN.ts";
import zhTW from "../../apps/desktop/src/i18n/locales/zh-TW.ts";
-const messagesViewPath = "apps/desktop/src/components/layout/QueryMessagesView.vue";
-const viewSwitcherPath = "apps/desktop/src/components/layout/QueryResultViewSwitcher.vue";
-const contentAreaPath = "apps/desktop/src/components/layout/ContentArea.vue";
-
-function source(path: string): string {
- return readFileSync(path, "utf8");
-}
-
-test("QueryMessagesView SFC compiles", () => {
- const { descriptor, errors } = parse(source(messagesViewPath), { filename: messagesViewPath });
- assert.deepEqual(errors, [], `${messagesViewPath} should parse without SFC errors`);
- assert.ok(descriptor.scriptSetup, `${messagesViewPath} should have a script setup block`);
- compileScript(descriptor, { id: messagesViewPath });
- assert.ok(descriptor.template);
- const result = compileTemplate({ id: messagesViewPath, filename: messagesViewPath, source: descriptor.template!.content });
- assert.deepEqual(result.errors, [], `${messagesViewPath} template should compile`);
-});
-
-test("QueryMessagesView maps severities to badge tones", () => {
- const view = source(messagesViewPath);
-
- // error/fatal/panic are errors, anything containing "warn" is a warning,
- // everything else (NOTICE, INFO, Note, ...) stays muted.
- assert.match(view, /normalized === "error" \|\| normalized === "fatal" \|\| normalized === "panic"\) return "error"/);
- assert.match(view, /normalized\.includes\("warn"\)\) return "warning"/);
- assert.match(view, /return "muted"/);
- for (const tone of ["muted", "warning", "error"] as const) {
- assert.match(view, new RegExp(`${tone}: "`));
- }
-});
-
-test("QueryMessagesView renders message text, extras, and the empty state", () => {
- const view = source(messagesViewPath);
-
- assert.match(view, /t\("queryMessages\.empty"\)/);
- assert.match(view, /\{\{ message\.severity \}\}/);
- assert.match(view, /\{\{ message\.message \}\}/);
- assert.match(view, /v-if="message\.detail"/);
- assert.match(view, /v-if="message\.hint"/);
- assert.match(view, /v-if="message\.code"[\s\S]*t\("queryMessages\.code", \{ code: message\.code \}\)/);
-});
-
-test("view switcher exposes a messages button with a count badge", () => {
- const switcher = source(viewSwitcherPath);
-
- assert.match(switcher, /canShowMessages: boolean/);
- assert.match(switcher, /messageCount\?: number/);
- assert.match(switcher, /<MessageSquareText class="block h-3\.5 w-3\.5 self-center" \/>/);
- assert.match(switcher, /:disabled="!canShowMessages"/);
- assert.match(switcher, /@click="selectView\('messages'\)"/);
- assert.match(switcher, /v-if="!compact && messageCount > 0"[\s\S]*?\{\{ messageCount \}\}/);
- // The tooltip/aria label carries the count when messages exist.
- assert.match(switcher, /messagesTooltip = computed\(\(\) => \(props\.messageCount > 0/);
-});
-
-test("ContentArea wires server messages into the switcher and the messages view", () => {
- const contentArea = source(contentAreaPath);
-
- // Messages are aggregated across every statement result of the run so a
- // message-only statement (e.g. a PostgreSQL DO block) keeps its notices even
- // when a later statement owns the active result.
- assert.match(contentArea, /const resultMessages = computed<QueryMessage\[\]>\(\(\) => \{/);
- assert.match(contentArea, /props\.activeTab\.results\?\.length \? props\.activeTab\.results : props\.activeTab\.result \? \[props\.activeTab\.result\] : \[\]/);
- assert.match(contentArea, /results\.flatMap\(queryResultMessages\)/);
- assert.match(contentArea, /resultMessageCount = computed\(\(\) => resultMessages\.value\.length\)/);
- assert.match(contentArea, /canShowMessagesOutput = computed\(\(\) => resultMessageCount\.value > 0\)/);
- assert.equal((contentArea.match(/:can-show-messages="canShowMessagesOutput"/g) ?? []).length, 2);
- assert.equal((contentArea.match(/:message-count="resultMessageCount"/g) ?? []).length, 2);
- assert.match(contentArea, /<QueryMessagesView v-else-if="activeOutputView === 'messages'"[\s\S]*:messages="resultMessages"/);
- // Results with no result set auto-switch via the shared default-view helper.
- assert.match(contentArea, /import \{ defaultViewForResult \} from "@\/lib\/query\/queryResultDefaultView"/);
- assert.match(contentArea, /emit\("update:activeOutputView", props\.activeTab\.id, result \? defaultViewForResult\(result\) : "summary"\)/);
-});
-
test("every locale defines the query message strings", () => {
const locales = { az, en, es, it, ja, ko, "pt-BR": ptBR, tr, "zh-CN": zhCN, "zh-TW": zhTW };
diff --git a/packages/app-tests/queryResultToolbar.test.ts b/packages/app-tests/queryResultToolbar.test.ts
index b3691b177b..adf0c7ca54 100644
--- a/packages/app-tests/queryResultToolbar.test.ts
+++ b/packages/app-tests/queryResultToolbar.test.ts
@@ -1,269 +1,16 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "vitest";
-import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";
const contentAreaPath = "apps/desktop/src/components/layout/ContentArea.vue";
-const resultSetNavigatorPath = "apps/desktop/src/components/layout/ResultSetNavigator.vue";
-const appPath = "apps/desktop/src/App.vue";
-const dataGridPath = "apps/desktop/src/components/grid/DataGrid.vue";
-const dataGridExportMenuPath = "apps/desktop/src/components/grid/DataGridExportMenu.vue";
-const dataGridToolbarPath = "apps/desktop/src/components/grid/DataGridToolbar.vue";
-const editorToolbarPath = "apps/desktop/src/components/layout/EditorToolbar.vue";
-const viewSwitcherPath = "apps/desktop/src/components/layout/QueryResultViewSwitcher.vue";
-const toolbarActionsPath = "apps/desktop/src/components/layout/QueryResultToolbarActions.vue";
function source(path: string): string {
return readFileSync(path, "utf8");
}
-function assertSfcCompiles(path: string): void {
- const { descriptor, errors } = parse(source(path), { filename: path });
- assert.deepEqual(errors, [], `${path} should parse without SFC errors`);
- assert.ok(descriptor.scriptSetup, `${path} should have a script setup block`);
- compileScript(descriptor, { id: path });
- if (descriptor.template) {
- const result = compileTemplate({ id: path, filename: path, source: descriptor.template.content });
- assert.deepEqual(result.errors, [], `${path} template should compile`);
- }
-}
-
-test("query result toolbar SFCs compile", () => {
- for (const path of [contentAreaPath, dataGridPath, dataGridExportMenuPath, dataGridToolbarPath, editorToolbarPath, viewSwitcherPath, toolbarActionsPath]) assertSfcCompiles(path);
-});
-
test("ContentArea keeps query-result insert and delete capabilities separate", () => {
const contentArea = source(contentAreaPath);
assert.match(contentArea, /:allow-insert-rows="activeTab\.queryAnalysis\?\.allowInsert \?\? activeTab\.queryAnalysis\?\.allowInsertDelete !== false"/);
assert.match(contentArea, /:allow-delete-rows="activeTab\.queryAnalysis\?\.allowDelete \?\? activeTab\.queryAnalysis\?\.allowInsertDelete !== false"/);
});
-
-test("query result toolbar reuses the production icon contract", () => {
- const contentArea = source(contentAreaPath);
- const dataGrid = source(dataGridPath);
- const dataGridExportMenu = source(dataGridExportMenuPath);
- const dataGridToolbar = source(dataGridToolbarPath);
- const editorToolbar = source(editorToolbarPath);
- const viewSwitcher = source(viewSwitcherPath);
- const toolbarActions = source(toolbarActionsPath);
-
- assert.match(contentArea, /<Pin class="h-3\.5 w-3\.5"/);
- assert.match(contentArea, /<Wrench class="h-4 w-4"/);
- assert.match(contentArea, /<ChevronDown class="h-3\.5 w-3\.5"/);
- assert.match(viewSwitcher, /import \{ BarChart3, ListChecks, MessageSquareText \} from "@lucide\/vue"/);
- assert.match(toolbarActions, /import \{ GitBranch, Gauge, Loader2, PlugZap, Upload \} from "@lucide\/vue"/);
- assert.match(editorToolbar, /@click="emit\('importResultArchive'\)"[\s\S]{0,100}<Download/);
- assert.match(toolbarActions, /@click="emit\('exportArchive'\)"[\s\S]{0,200}<Upload v-else/);
- assert.match(dataGrid, /return \{ label: t\("grid\.export"\), icon: Upload, children: items \};/);
- assert.match(dataGridExportMenu, /:trigger-icon="Upload"/);
- assert.match(dataGridToolbar, /<Upload class="data-grid-topbar-action-icon h-3 w-3"/);
- assert.match(viewSwitcher, /inline-flex h-4 items-center leading-none/);
- assert.match(toolbarActions, /block h-3\.5 w-3\.5 self-center/);
- assert.doesNotMatch(viewSwitcher + toolbarActions, /<svg\b|<symbol\b|<use\b/);
-});
-
-test("ContentArea exposes retained result runs as switchable tabs or a compact list", () => {
- const contentArea = source(contentAreaPath);
- const runScrollerStart = contentArea.indexOf('ref="resultTabsScrollerRef"');
- const listSelectorStart = contentArea.indexOf('<div v-else-if="showResultRunSelector"', runScrollerStart);
- const fixedResultSetStart = contentArea.indexOf("<ResultSetNavigator", listSelectorStart);
-
- assert.match(contentArea, /showResultRunTabs = computed\(\(\) => resultRuns\.value\.length > 0 && resultRunDisplayMode\.value === "tabs"\)/);
- assert.match(contentArea, /showResultRunSelector = computed\(\(\) => resultRuns\.value\.length > 0 && resultRunDisplayMode\.value === "list"\)/);
- assert.match(contentArea, /ref="resultTabsScrollerRef"[\s\S]*v-for="\(run, runIndex\) in resultRuns"/);
- assert.match(contentArea, /role="tablist" :aria-label="t\('tabs\.resultRuns'\)"/);
- assert.match(contentArea, /data-result-run-tab/);
- assert.match(contentArea, /@keydown="onResultRunTabKeydown\(\$event, runIndex\)"/);
- assert.match(contentArea, /@click\.stop\.prevent="removeResultRun\(run\.id\)"/);
- assert.match(contentArea, /const canCloseQueryResult = computed\([\s\S]*!props\.activeTab\.activeResultRunId/);
- assert.match(contentArea, /v-if="canCloseQueryResult"[\s\S]*@click="closeCurrentQueryResult"/);
- assert.match(contentArea, /queryStore\.closeQueryResult\(props\.activeTab\.id\)/);
- assert.match(contentArea, /t\('tabs\.closeResult'\)/);
- assert.match(contentArea, /<DropdownMenuContent align="start" class="w-48">[\s\S]*v-for="run in resultRuns"/);
- assert.match(contentArea, /setResultRunDisplayMode\('list'\)/);
- assert.match(contentArea, /setResultRunDisplayMode\('tabs'\)/);
- assert.ok(runScrollerStart >= 0);
- assert.ok(listSelectorStart > runScrollerStart);
- assert.ok(fixedResultSetStart > listSelectorStart);
- assert.match(source(resultSetNavigatorPath), /data-result-set-tabs-region/);
- assert.doesNotMatch(contentArea.slice(runScrollerStart, listSelectorStart), /visibleResultItems/);
- assert.match(contentArea, /resultAutoSave \? 'bg-primary\/10 text-primary[\s\S]*: 'text-muted-foreground hover:bg-accent hover:text-foreground'/);
- assert.doesNotMatch(contentArea, /queryResultAutoRefresh|QUERY_RESULT_AUTO_REFRESH|nextResultToolbarLayout/);
- assert.equal((contentArea.match(/<QueryResultViewSwitcher\b/g) ?? []).length, 2);
- assert.equal((contentArea.match(/<QueryResultToolbarActions\b/g) ?? []).length, 2);
-});
-
-test("appending a result run preserves the tab-strip scroll position", () => {
- const contentArea = source(contentAreaPath);
- const resultRunWatcherStart = contentArea.indexOf("function resultRunIdsWereAppended");
- const resultRunWatcherEnd = contentArea.indexOf("const summaryItems", resultRunWatcherStart);
- const resultRunWatcher = contentArea.slice(resultRunWatcherStart, resultRunWatcherEnd);
-
- assert.ok(resultRunWatcherStart >= 0);
- assert.match(resultRunWatcher, /current\.length > previous\.length/);
- assert.match(resultRunWatcher, /activeRunId: props\.activeTab\.activeResultRunId/);
- assert.match(resultRunWatcher, /activeRunChanged && !resultRunIdsWereAppended\(previous\.runIds, current\.runIds\)/);
- assert.match(resultRunWatcher, /updateResultTabsAfterRender/);
- assert.match(resultRunWatcher, /revealActiveResultRunAfterRender/);
- assert.match(contentArea, /function focusResultRunByIndex[\s\S]*scrollIntoView/);
- assert.match(contentArea, /async function removeResultRun[\s\S]*scrollIntoView/);
-});
-
-test("the close-tab shortcut clears query results before closing the tab", () => {
- const app = source(appPath);
- const closeSurfaceStart = app.indexOf("async function closeActiveSurface()");
- const closeSurfaceEnd = app.indexOf("function activateMainContentSurface", closeSurfaceStart);
- const closeSurface = app.slice(closeSurfaceStart, closeSurfaceEnd);
-
- assert.ok(closeSurfaceStart >= 0);
- assert.ok(closeSurface.indexOf("await queryStore.clearQueryResults(queryStore.activeTabId)") < closeSurface.indexOf("queryStore.closeTab(queryStore.activeTabId)"));
-});
-
-test("the configurable results pane shortcut only toggles existing output", () => {
- const contentArea = source(contentAreaPath);
- const app = source(appPath);
- const toggleStart = contentArea.indexOf("function toggleResultsPane()");
- const toggleEnd = contentArea.indexOf("function onResultsResized", toggleStart);
- const toggle = contentArea.slice(toggleStart, toggleEnd);
- const shortcutStart = app.indexOf("if (isToggleResultsPaneShortcut(e, shortcuts)");
- const shortcutEnd = app.indexOf("if (isNewQueryShortcut", shortcutStart);
- const shortcut = app.slice(shortcutStart, shortcutEnd);
-
- assert.ok(toggleStart >= 0);
- assert.match(toggle, /if \(props\.activeTab\.mode !== "query" \|\| !hasQueryOutput\.value\) return false/);
- assert.match(toggle, /resultsPaneOpen\.value = !resultsPaneOpen\.value/);
- assert.match(toggle, /return true/);
- assert.doesNotMatch(toggle, /closeQueryResult|clearQueryResults|closeResultSession/);
- assert.match(contentArea, /defineExpose\(\{[\s\S]*toggleResultsPane/);
- assert.ok(shortcutStart >= 0);
- assert.match(shortcut, /contentAreaRef\.value\?\.toggleResultsPane\(\)/);
- assert.match(shortcut, /e\.preventDefault\(\)/);
- assert.match(shortcut, /e\.stopPropagation\(\)/);
-});
-
-test("ContentArea keeps MySQL standard explain results available in the shared toolbar", () => {
- const contentArea = source(contentAreaPath);
-
- assert.match(contentArea, /canShowExplainOutput = computed\([\s\S]*explainTableResult[\s\S]*explainTableError/);
- assert.match(contentArea, /:table-result="activeTab\.explainTableResult"/);
- assert.match(contentArea, /:table-error="activeTab\.explainTableError"/);
-});
-
-test("DataGrid exposes persistent result toolbar slots", () => {
- const dataGrid = source(dataGridPath);
-
- assert.match(dataGrid, /slots\["result-toolbar-leading"\]/);
- assert.match(dataGrid, /slots\["result-toolbar-actions"\]/);
- assert.match(dataGrid, /<slot name="result-toolbar-leading" :compact="compactDataGridToolbar"/);
- assert.match(dataGrid, /<slot v-if="hasResultToolbarActionsSlot" name="result-toolbar-actions" :compact="compactDataGridToolbar"/);
- assert.match(dataGrid, /hasResultToolbarLeadingSlot\.value \|\|[\s\S]*hasResultToolbarActionsSlot\.value/);
-});
-
-test("table-data toolbar refresh keeps page size independent from SQL editor settings", () => {
- const dataGrid = source(dataGridPath);
-
- // Table-data grids resolve page size through the table-open preference
- // (pageLimit ?? tableOpenPageLimit(tableOpenPageSize)) instead of the SQL editor pageSize.
- assert.match(dataGrid, /pageSizePreference = computed\(\(\) => resolveDataGridPageSizePreference\(props\.context, props\.pageSizePreference\)\)/);
- assert.match(dataGrid, /pageSize = ref\(preferredDataGridPageSize\(settingsStore\.editorSettings, pageSizePreference\.value, props\.pageLimit\)\)/);
- assert.match(dataGrid, /watch\([\s\S]*\(\) => settingsStore\.editorSettings\.pageSize,[\s\S]*if \(pageSizePreference\.value !== "results"\) return;[\s\S]*pageSize\.value = normalizeResultPageSize\(value, pageSize\.value\)/);
- // Changing the page size in the grid is temporary; only the explicit
- // set-as-default action persists it back into editor settings.
- const changePageSizeStart = dataGrid.indexOf("function changePageSize(size: number) {");
- assert.ok(changePageSizeStart >= 0);
- const changePageSizeEnd = dataGrid.indexOf("function setDefaultPageSize", changePageSizeStart);
- assert.ok(changePageSizeEnd > changePageSizeStart);
- const changePageSize = dataGrid.slice(changePageSizeStart, changePageSizeEnd);
- assert.doesNotMatch(changePageSize, /updateEditorSettings/);
- assert.match(dataGrid, /function setDefaultPageSize\(\) \{[\s\S]*?settingsStore\.updateEditorSettings\(dataGridPageSizeSettingsPatch\(pageSizePreference\.value, pageSize\.value\)\)/);
- assert.match(dataGrid, /const resetToFirstPage = hasPendingConditionInputs\(\);/);
- assert.match(dataGrid, /emit\("reload", props\.sql, searchText\.value, currentWhereInput\(\), currentOrderBy\(\), pageSize\.value, resetToFirstPage \? 0 : \(currentPage\.value - 1\) \* pageSize\.value, intent\)/);
-});
-
-test("standalone result views use the same compact toolbar breakpoint", () => {
- const contentArea = source(contentAreaPath);
- const dataGrid = source(dataGridPath);
-
- assert.match(contentArea, /ref="standaloneResultToolbarRef"/);
- assert.match(contentArea, /isDataGridToolbarCompact\(standaloneResultToolbarWidth\.value, standaloneResultToolbarViewportWidth\.value\)/);
- assert.equal((contentArea.match(/:compact="standaloneResultToolbarCompact"/g) ?? []).length, 2);
- assert.match(dataGrid, /isDataGridToolbarCompact\(dataGridTopbarWidth\.value, dataGridViewportWidth\.value, DATA_GRID_CONDITION_TOOLBAR_MIN_WIDTH\)/);
-});
-
-test("embedded result toolbar progressively compacts when editing actions overflow its available width", () => {
- const dataGrid = source(dataGridPath);
- const toolbar = source(dataGridToolbarPath);
-
- assert.match(dataGrid, /dataGridTopbarMutationObserver = new MutationObserver\(updateDataGridTopbarWidth\)/);
- assert.match(dataGrid, /dataGridTopbarMutationObserver\.observe\(topbar, \{ childList: true, characterData: true, subtree: true \}\)/);
- const measurementStart = dataGrid.indexOf("function updateDataGridTopbarWidth()");
- const measurementEnd = dataGrid.indexOf("function resetDataGridTopbarOverflowCompact()", measurementStart);
- assert.ok(measurementStart >= 0 && measurementEnd > measurementStart);
- assert.match(dataGrid.slice(measurementStart, measurementEnd), /(\w+)\.scrollWidth > \1\.clientWidth \+ 1/);
- assert.match(dataGrid, /dataGridTopbarOverflowCompact\.value = true/);
- assert.match(dataGrid, /dataGridTopbarOverflowActionCount\.value = compactDataGridToolbarActionCount\.value \+ 1/);
- assert.match(dataGrid, /dataGridTopbarWidth\.value >= dataGridTopbarExpandedRequiredWidth\.value/);
- assert.match(dataGrid, /:compact-action-count="compactDataGridToolbarActionCount"/);
- assert.match(toolbar, /DATA_GRID_TOOLBAR_ACTION_COLLAPSE_ORDER\.filter/);
- assert.match(toolbar, /<slot name="navigation" :compact="actionIsCompact\('navigation'\)"/);
-});
-
-test("embedded result toolbar remeasures after the SQL preview action is removed", () => {
- const dataGrid = source(dataGridPath);
-
- assert.match(dataGrid, /if \(previousVisible && !visible\) resetDataGridTopbarOverflowCompact\(\)/);
- assert.match(dataGrid, /dataGridTopbarOverflowCompact\.value = false/);
- assert.match(dataGrid, /dataGridTopbarOverflowActionCount\.value = 0/);
- assert.match(dataGrid, /function scheduleDataGridTopbarRecheck\(\)/);
- assert.match(dataGrid, /clearDataGridTopbarRecheckTimer\(\)/);
-});
-
-test("embedded result toolbar remeasures after save and rollback actions are removed", () => {
- const dataGrid = source(dataGridPath);
-
- assert.match(dataGrid, /\(\) => saveToolbarState\.value\.showActions,/);
- assert.match(dataGrid, /if \(previousShowActions && !showActions\) resetDataGridTopbarOverflowCompact\(\)/);
-});
-
-test("embedded and standalone result toolbars share the same fixed height", () => {
- const contentArea = source(contentAreaPath);
- const dataGrid = source(dataGridPath);
- const standaloneClasses = contentArea.match(/ref="standaloneResultToolbarRef" class="([^"]+)"/)?.[1].split(/\s+/) ?? [];
- // The embedded topbar picks its height from the toolbar layout toggle; the
- // default single-row branch must match the standalone toolbar's fixed row.
- const embeddedLayoutClasses = dataGrid.match(/ref="dataGridTopbarRef"[\s\S]{0,300}?:class="([^"]+)"/)?.[1] ?? "";
-
- assert.ok(standaloneClasses.includes("h-8"));
- assert.ok(embeddedLayoutClasses.includes("h-8"));
- assert.ok(standaloneClasses.includes("items-center"));
- assert.ok(embeddedLayoutClasses.includes("items-center"));
- assert.ok(!standaloneClasses.includes("h-7"));
- assert.ok(!embeddedLayoutClasses.includes("h-7"));
- assert.ok(!standaloneClasses.includes("min-h-7"));
- assert.ok(!embeddedLayoutClasses.includes("min-h-7"));
-});
-
-test("embedded result toolbar cannot scroll vertically", () => {
- const dataGrid = source(dataGridPath);
- const scrollClasses = dataGrid.match(/class="data-grid-topbar-scroll ([^"]+)"/)?.[1].split(/\s+/) ?? [];
-
- assert.ok(scrollClasses.includes("overflow-clip"));
- assert.ok(!scrollClasses.some((className) => className.startsWith("overflow-x-")));
- assert.ok(!scrollClasses.some((className) => className.startsWith("overflow-y-")));
-});
-
-test("DataGrid marks toolbar refresh separately from current-result reloads", () => {
- const dataGrid = source(dataGridPath);
-
- assert.match(dataGrid, /async function onToolbarRefresh\(\)\s*\{\s*await reloadTableData\("refresh"\);/);
- assert.match(dataGrid, /refresh: \(\) => reloadTableData\("auto-refresh"\)/);
- assert.match(dataGrid, /async function reloadTableData\(intent: DataGridReloadIntent\)[\s\S]*?emit\("reload", props\.sql,[^;]+intent\);/);
- assert.match(dataGrid, /function onToolbarRollback\(\)[\s\S]*?emit\("reload", props\.sql,[^;]+\);/);
-});
-
-test("Elasticsearch JSON refresh preserves multi-result query groups", () => {
- const contentArea = source(contentAreaPath);
-
- assert.match(contentArea, /if \(activeElasticsearchJsonResponse\.value\) \{[\s\S]*?emit\("reload", props\.activeTab\.id, activeResultSql\.value, undefined, undefined, undefined, undefined, undefined, "refresh"\);/);
-});
diff --git a/packages/app-tests/recentConnections.test.ts b/packages/app-tests/recentConnections.test.ts
index 4fb3f4754f..8a4b13f38e 100644
--- a/packages/app-tests/recentConnections.test.ts
+++ b/packages/app-tests/recentConnections.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { MAX_RECENT_CONNECTION_IDS, parseRecentConnectionIds, rankRecentConnections, recordRecentConnection } from "../../apps/desktop/src/lib/connection/recentConnections.ts";
@@ -81,12 +80,3 @@ test("empty history preserves saved order and recency follows stable IDs after r
["Renamed", "Connection one", "Connection three"],
);
});
-
-test("App wires active connection changes and Quick Start opens into the MRU history", () => {
- const source = readFileSync("apps/desktop/src/App.vue", "utf8");
-
- assert.ok(source.includes("rankRecentConnections(connectionStore.connections, recentConnectionIds.value)"));
- assert.ok(source.includes("if (nextIds === recentConnectionIds.value) return;"));
- assert.match(source, /watch\(\s*\(\) => connectionStore\.activeConnectionId,\s*rememberRecentConnection,?\s*\);/);
- assert.match(source, /async function openConnectionQuery\(connectionId: string\)[\s\S]*?rememberRecentConnection\(connectionId\);/);
-});
diff --git a/packages/app-tests/redisValueSearch.test.ts b/packages/app-tests/redisValueSearch.test.ts
index 6244dce4a4..910ba3654a 100644
--- a/packages/app-tests/redisValueSearch.test.ts
+++ b/packages/app-tests/redisValueSearch.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import {
@@ -55,56 +54,3 @@ test("drag source allows grip button, blocks input", () => {
assert.equal(isTextContentSearchDragSource(fake(["[data-drag-handle]", "button"])), true);
assert.equal(isTextContentSearchDragSource(fake(["input"])), false);
});
-
-test("content find is for STRING + RedisJSON + member detail; hash toolbar search stays; no list filter", () => {
- const viewer = readFileSync(new URL("../../apps/desktop/src/components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
- const jsonEditor = readFileSync(new URL("../../apps/desktop/src/components/redis/RedisJsonEditor.vue", import.meta.url), "utf8");
- const browser = readFileSync(new URL("../../apps/desktop/src/components/redis/RedisKeyBrowser.vue", import.meta.url), "utf8");
- const documentBrowser = readFileSync(new URL("../../apps/desktop/src/components/document/DocumentBrowser.vue", import.meta.url), "utf8");
-
- assert.match(viewer, /valueSearchSupported/);
- // STRING, RedisJSON, or member detail.
- assert.match(viewer, /showMemberDetail\.value \|\| isStringLikeKind\.value \|\| redisKind\.value === "json"/);
- assert.match(viewer, /function openValueSearch/);
- assert.match(viewer, /function onCollectionSearch/);
- assert.match(viewer, /v-model="collectionSearchQuery"/);
- assert.match(viewer, /data-redis-member-detail/);
- assert.match(viewer, /v-if="valueSearchOpen && showMemberDetail"/);
- assert.match(viewer, /ref="redisJsonEditorRef"/);
- assert.doesNotMatch(viewer, /filterRedisCollectionByQuery/);
- assert.doesNotMatch(viewer, /valueSearchIsCollectionMode/);
- // Builtin find is a prop defaulting to true; only value-viewer owned editors disable it.
- assert.match(jsonEditor, /enableBuiltinFind\?:/);
- assert.match(jsonEditor, /enableBuiltinFind:\s*true/);
- assert.match(viewer, /:enable-builtin-find="false"/);
- // DocumentBrowser must not pass enable-builtin-find=false (keeps CM find).
- assert.doesNotMatch(documentBrowser, /enable-builtin-find/);
- assert.match(browser, /valueViewerRef\.value\?\.focusSearch\(\)/);
-});
-
-test("find panel uses absolute positioning (dialog-safe, typeable)", () => {
- const bar = readFileSync(new URL("../../apps/desktop/src/components/common/TextContentSearchBar.vue", import.meta.url), "utf8");
- assert.doesNotMatch(bar, /<Teleport/);
- assert.doesNotMatch(bar, /class="[^"]*\bfixed\b/);
- assert.match(bar, /absolute right-3 top-3/);
- assert.match(bar, /data-draggable-search-panel/);
- // Input must stop propagation so panel drag handler never captures typing clicks.
- assert.match(bar, /@pointerdown\.stop/);
- assert.match(bar, /@mousedown\.stop/);
- // Esc must not bubble to Dialog (would close member detail).
- assert.match(bar, /@keydown\.escape\.prevent\.stop/);
-});
-
-test("find input must keep focus while typing (no focus:true on body scroll)", () => {
- const viewer = readFileSync(new URL("../../apps/desktop/src/components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
- // Navigation/scroll must not steal focus into the value body.
- assert.match(viewer, /focus:\s*false/);
- assert.doesNotMatch(viewer, /scrollContentSearchMatchIntoView\(\{\s*focus:\s*true/);
- assert.doesNotMatch(viewer, /textarea\.focus\(/);
-});
-
-test("focusSearch works for open member detail without prior pointer activation", () => {
- const viewer = readFileSync(new URL("../../apps/desktop/src/components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
- assert.match(viewer, /!showMemberDetail\.value\) return false/);
- assert.match(viewer, /function focusSearch/);
-});
diff --git a/packages/app-tests/scheduledDatabaseBackup.test.ts b/packages/app-tests/scheduledDatabaseBackup.test.ts
index daf09427f1..785788f8a8 100644
--- a/packages/app-tests/scheduledDatabaseBackup.test.ts
+++ b/packages/app-tests/scheduledDatabaseBackup.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import {
DatabaseBackupConnectionQueue,
@@ -338,15 +337,3 @@ test("retention never selects failed backup runs", () => {
["old"],
);
});
-
-test("scheduled backup history translates stable backend errors inline", () => {
- const source = readFileSync("apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue", "utf8");
-
- assert.match(source, /\{\{ translateBackendError\(t, run\.error\) \}\}/);
- assert.doesNotMatch(source, /\{\{ run\.error \}\}/);
-});
-
-test("database exports keep the backup snapshot alive", () => {
- const exportCore = readFileSync("crates/dbx-core/src/data/database_export.rs", "utf8");
- assert.match(exportCore, /keep_manual_transaction_alive\(state, snapshot_session_id\)\.await/);
-});
diff --git a/packages/app-tests/settingsStore.test.ts b/packages/app-tests/settingsStore.test.ts
index f758506ab8..dbc312a34d 100644
--- a/packages/app-tests/settingsStore.test.ts
+++ b/packages/app-tests/settingsStore.test.ts
@@ -1,6 +1,5 @@
import { beforeEach, test, vi } from "vitest";
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { createPinia, setActivePinia } from "pinia";
import { DEFAULT_SQL_FORMATTER_SETTINGS } from "../../apps/desktop/src/lib/sql/sqlFormatterConfig.ts";
import { DEFAULT_TABLE_COLUMN_TEMPLATE_FIELDS } from "../../apps/desktop/src/lib/table/tableColumnTemplates.ts";
@@ -238,17 +237,6 @@ test("migrates legacy execute-all settings to current once and preserves later e
});
});
-test("shows the table-open page size control in the Data settings tab", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
- const dataSectionStart = source.indexOf("activeSettingsTab === 'data'");
- const nextSectionStart = source.indexOf("activeSettingsTab === 'shortcuts'", dataSectionStart);
- const control = source.indexOf('id="table-open-page-size"');
-
- assert.ok(dataSectionStart >= 0);
- assert.ok(nextSectionStart > dataSectionStart);
- assert.ok(control > dataSectionStart && control < nextSectionStart);
-});
-
test("defaults export batch size to 2000 rows", () => {
assert.equal(DEFAULT_EDITOR_SETTINGS.exportBatchSize, 2000);
assert.equal(normalizeEditorSettings({}).exportBatchSize, 2000);
@@ -376,14 +364,6 @@ test("defaults saved SQL to its saved target and normalizes persisted target mod
assert.equal(normalizeEditorSettings({ savedSqlOpenTargetMode: "invalid" as any }).savedSqlOpenTargetMode, "saved");
});
-test("shows the saved SQL target selector in Editor settings", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
-
- assert.match(source, /id="editor-saved-sql-open-target"/);
- assert.match(source, /<SelectItem value="saved">/);
- assert.match(source, /<SelectItem value="current">/);
-});
-
test("defaults Vim mode to off and preserves saved booleans", () => {
assert.equal(DEFAULT_EDITOR_SETTINGS.vimModeEnabled, false);
assert.equal(normalizeEditorSettings({}).vimModeEnabled, false);
@@ -1024,27 +1004,6 @@ test("AI partner presets reuse a supported runtime adapter", () => {
assert.equal(getAiProviderPreset("openai-compatible", "https://api.example.com/v1").label, "OpenAI Compatible");
});
-test("API AI provider settings expose and persist a default model ID", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
- const modelControl = source.indexOf('<Input v-model="aiEditModel"');
-
- assert.ok(modelControl >= 0);
- assert.match(source.slice(modelControl - 300, modelControl + 300), /v-if="!aiIsCliProvider"[\s\S]*t\("ai\.defaultModel"\)[\s\S]*t\('ai\.manualModelPlaceholder'\)/);
- assert.match(source, /model:\s*aiEditModel\.value/);
-});
-
-test("AI connection test uses the model currently entered in the config form", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
- const testConnectionStart = source.indexOf("async function aiTestConn()");
- const testConnectionEnd = source.indexOf("async function copyAiTestError()", testConnectionStart);
- const testConnection = source.slice(testConnectionStart, testConnectionEnd);
-
- assert.notEqual(testConnectionStart, -1);
- assert.notEqual(testConnectionEnd, -1);
- assert.match(testConnection, /const config = currentAiEditConfig\(\);[\s\S]*aiTestConnection\(config\)/);
- assert.doesNotMatch(testConnection, /activeModel|config\.model\s*=/);
-});
-
test("normalizes legacy AI config and fills provider defaults", () => {
const legacy = normalizeAiConfig({
provider: "openai",
@@ -1172,22 +1131,6 @@ test("normalizeEditorSettings keeps valid UI scales with two-decimal precision",
assert.equal(normalizeEditorSettings({ uiScale: 1.125 }).uiScale, 1.13);
});
-test("shows persisted UI scales that are not available as presets", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
-
- assert.match(source, /<SelectValue>\{\{ Math\.round\(editUiScale \* 100\) \}\}%<\/SelectValue>/);
-});
-
-test("settings page resets content scroll when switching categories", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
-
- assert.match(source, /const settingsContentScrollRef = ref<HTMLElement \| null>\(null\)/);
- assert.match(source, /function resetSettingsContentScroll\(\)/);
- assert.match(source, /if \(scroller\) scroller\.scrollTop = 0/);
- assert.match(source, /watch\(activeSettingsTab, async \(tab\) => \{\s+void resetSettingsContentScroll\(\);/);
- assert.match(source, /ref="settingsContentScrollRef" class="min-h-0 flex-1 overflow-y-auto overflow-x-hidden/);
-});
-
test("defaults SQL formatter settings", () => {
assert.deepEqual(DEFAULT_EDITOR_SETTINGS.sqlFormatter, DEFAULT_SQL_FORMATTER_SETTINGS);
assert.deepEqual(normalizeEditorSettings({}).sqlFormatter, DEFAULT_EDITOR_SETTINGS.sqlFormatter);
diff --git a/packages/app-tests/settingsTransferPanel.test.ts b/packages/app-tests/settingsTransferPanel.test.ts
deleted file mode 100644
index 5077f39573..0000000000
--- a/packages/app-tests/settingsTransferPanel.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";
-
-const panelPath = "apps/desktop/src/components/settings/SettingsTransferPanel.vue";
-
-function source(path: string): string {
- return readFileSync(path, "utf8");
-}
-
-test("settings transfer panel SFC compiles", () => {
- const { descriptor, errors } = parse(source(panelPath), { filename: panelPath });
- assert.deepEqual(errors, [], `${panelPath} should parse without SFC errors`);
- assert.ok(descriptor.scriptSetup, `${panelPath} should have a script setup block`);
- compileScript(descriptor, { id: panelPath });
- assert.ok(descriptor.template, `${panelPath} should have a template`);
- const result = compileTemplate({ id: panelPath, filename: panelPath, source: descriptor.template.content });
- assert.deepEqual(result.errors, [], `${panelPath} template should compile`);
-});
-
-test("about-page settings transfer buttons follow local-container icon semantics", () => {
- const panel = source(panelPath);
-
- // Treat the app as a local container: import brings data in (Download),
- // export sends data out (Upload). Same contract as SQL library / formatter.
- assert.match(panel, /@click="onImportClick"[\s\S]{0,200}<Download v-else/);
- assert.match(panel, /@click="onExportClick"[\s\S]{0,200}<Upload v-else/);
- assert.doesNotMatch(panel, /@click="onImportClick"[\s\S]{0,200}<Upload v-else/);
- assert.doesNotMatch(panel, /@click="onExportClick"[\s\S]{0,200}<Download v-else/);
-});
diff --git a/packages/app-tests/sidebarContextMenuHost.test.ts b/packages/app-tests/sidebarContextMenuHost.test.ts
index b64631896c..59ec941699 100644
--- a/packages/app-tests/sidebarContextMenuHost.test.ts
+++ b/packages/app-tests/sidebarContextMenuHost.test.ts
@@ -36,60 +36,6 @@ function functionRegion(source: string, name: string): string {
return next ? rest.slice(0, next.index) : rest;
}
-test("tree-level context menu opens with the current row items atomically", () => {
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
- const contextMenu = readFileSync("apps/desktop/src/components/ui/CustomContextMenu.vue", "utf8");
-
- assert.match(connectionTree, /openContextMenu\(event, items\)/);
- assert.match(connectionTree, /sidebarContextMenuRef\.value\?\.close\(\)/);
- assert.match(connectionTree, /sidebarContextMenuTarget\.value = createSidebarActionTarget\(node\)/);
- assert.match(connectionTree, /sidebarContextMenuTarget\.value = null/);
- assert.match(connectionTree, /<CustomContextMenu ref="sidebarContextMenuRef"/);
- assert.match(contextMenu, /function onContextMenu\(event: MouseEvent, itemsOverride\?: ContextMenuItem\[\]\)/);
- assert.match(contextMenu, /const items = itemsOverride \?\?/);
- assert.match(contextMenu, /defineExpose\(\{ close, menuRef, subRef \}\)/);
-});
-
-test("rare sidebar dialogs share module-level async wrappers with fallbacks", () => {
- const treeItem = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
- const asyncDialogs = readFileSync("apps/desktop/src/components/sidebar/sidebarAsyncDialogs.ts", "utf8");
-
- assert.doesNotMatch(treeItem, /defineAsyncComponent/);
- assert.match(asyncDialogs, /loadingComponent: SidebarAsyncDialogLoading/);
- assert.match(asyncDialogs, /errorComponent: SidebarAsyncDialogError/);
- assert.match(asyncDialogs, /timeout: 15_000/);
-});
-
-test("tree host owns sidebar data-open generations", () => {
- const treeItem = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
-
- assert.doesNotMatch(treeItem, /runSidebarDataOpenImmediately/);
- assert.doesNotMatch(treeItem, /emit\("open-data"/);
- assert.match(runtimeHost, /emit\("open-data", node, true, "default", openData\)/);
- assert.match(connectionTree, /<SidebarTreeRuntimeHost/);
- assert.match(connectionTree, /function openSidebarData/);
- assert.match(connectionTree, /runSidebarDataOpenImmediately/);
- assert.match(connectionTree, /createSidebarActionTarget\(node\)/);
-});
-
-test("query-tab object source opens the tab before connecting or loading", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const openObjectSourceBody = functionBody(runtimeHost, "openObjectSourceDialog");
-
- // #9035:点击后立刻建出带加载态的 tab/弹窗,ensureConnected 与 getObjectSource
- // 都必须发生在已挂载的 UI 之内,而不是先 await 完再挂载(那样界面没有任何反馈)。
- assert.match(openObjectSourceBody, /queryStore\.openObjectSourceTabPending\(\{/);
- assert.match(openObjectSourceBody, /objectType: sourceTarget\.objectType/);
- assert.match(openObjectSourceBody, /signature: sourceNode\.signature/);
- assert.match(openObjectSourceBody, /emit\("open-object-source", sourceNode, initialEditing\)/);
- // 断言「调用形态」而不是词本身:这段代码里注释会提到这两个名字
- assert.doesNotMatch(openObjectSourceBody, /ensureConnected\(/);
- assert.doesNotMatch(openObjectSourceBody, /api\.getObjectSource\(/);
- assert.doesNotMatch(openObjectSourceBody, /toast\(/);
-});
-
test("object source identity and editability are enforced in queryStore", () => {
const queryStore = readFileSync("apps/desktop/src/stores/queryStore.ts", "utf8");
const findBody = functionRegion(queryStore, "findMatchingObjectSourceTab");
@@ -116,67 +62,6 @@ test("object source identity and editability are enforced in queryStore", () =>
assert.match(applyBody, /clearObjectSourceLoad\(tab\)/);
});
-test("table copy menu uses the shared single and multi-selection clipboard path", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const copyNameBody = functionBody(runtimeHost, "copyName");
- const copySelectedNamesBody = functionBody(runtimeHost, "copySelectedNames");
- const clipboardMenuBody = functionBody(runtimeHost, "treeTableClipboardMenuItems");
-
- assert.match(clipboardMenuBody, /tableClipboardMenuState\(\s*normalizedTreeClipboardTableEntries\(\)/);
- assert.match(clipboardMenuBody, /state === "paste" \? \[pasteItem\] : \[copyItem, pasteItem\]/);
- assert.match(runtimeHost, /items\.push\(\.\.\.treeTableClipboardMenuItems\(node\)\)/);
- assert.doesNotMatch(runtimeHost, /function copyTableToClipboard\(/);
- assert.doesNotMatch(copyNameBody, /updateTreeClipboardForNodes/);
- assert.match(copySelectedNamesBody, /const selectedNodes = selectedTreeNodesInVisibleOrder\(\)/);
- assert.match(copySelectedNamesBody, /selectedNodes\.length > 1 && selectedNodes\.some\(\(node\) => node\.id === activeNode\.value\.id\) \? selectedNodes : \[activeNode\.value\]/);
- assert.match(copySelectedNamesBody, /updateTreeClipboardForNodes\(nodes\)/);
- assert.match(copySelectedNamesBody, /formatSelectedTableNamesForClipboard/);
-});
-
-test("MySQL object name menus expose leaf and display-path copy choices", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const copyNameBody = functionBody(runtimeHost, "copyName");
- const copyDisplayPathBody = functionBody(runtimeHost, "copyDisplayPath");
- const copyNameMenuItemBody = functionBody(runtimeHost, "copyNameMenuItem");
- const connectionMenuBody = functionBody(runtimeHost, "buildConnectionSidebarMenu");
- const databaseMenuBody = functionBody(runtimeHost, "buildDatabaseSidebarMenu");
- const objectMenuBody = functionBody(runtimeHost, "buildObjectSidebarMenu");
-
- assert.match(copyNameBody, /formatSelectedTableNamesForClipboard/);
- assert.match(copyDisplayPathBody, /copyDisplayPathForTreeNode\(node, connectionName\)/);
- assert.match(copyNameMenuItemBody, /currentDatabaseType\(\) === "mysql"/);
- assert.match(copyNameMenuItemBody, /children: \[/);
- assert.match(copyNameMenuItemBody, /t\("contextMenu\.name"\)/);
- assert.match(copyNameMenuItemBody, /t\("contextMenu\.fullPath"\)/);
- assert.match(copyNameMenuItemBody, /return \{ label: t\("contextMenu\.copyName"\), action: copyName, icon: Copy, shortcut: shortcutCopyName\.value \}/);
- assert.doesNotMatch(connectionMenuBody, /copyNameMenuItem\(\)/);
- assert.match(databaseMenuBody, /items\.push\(copyNameMenuItem\(\)\)/);
- assert.match(objectMenuBody, /items\.push\(copyNameMenuItem\(\)\)/);
- assert.match(objectMenuBody, /node\.type === "trigger" \? copyNameMenuItem\(\)/);
- assert.match(objectMenuBody, /node\.type === "sequence"[\s\S]*action: copyName/);
-});
-
-test("multi-select view ddl opens a combined ddl tab instead of export structure", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const openDdlBody = functionBody(runtimeHost, "openDdl");
-
- assert.doesNotMatch(openDdlBody, /exportStructure\(\)/);
- assert.match(openDdlBody, /openSidebarMultiTableDdlTab\(targets\)/);
- assert.match(runtimeHost, /openDdlForSelection/);
-});
-
-test("multi-select add-to-ai only mentions tables in the active execution context", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- // The function's return type annotation contains braces, so extract the body
- // from the signature line to the next column-0 closing brace.
- const selectedAiTableTargetsBody = /function selectedAiTableTargets\([^)]*\)[^\n]*\{[\s\S]*?\n\}/.exec(runtimeHost)?.[0] ?? "";
-
- assert.notEqual(selectedAiTableTargetsBody, "");
- assert.match(selectedAiTableTargetsBody, /resolveSidebarDdlTargets\(/);
- assert.match(selectedAiTableTargetsBody, /target\.type === "table"/);
- assert.doesNotMatch(selectedAiTableTargetsBody, /sidebarStructureExportTargets\(/);
-});
-
test("successful tree table paste consumes only the clipboard used to start it", () => {
const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTable");
@@ -209,13 +94,6 @@ test("tree table paste consumes the clipboard even if only the object-list refre
assert.match(confirmPasteTableBody, /if \(refreshFailCount > 0\)[\s\S]*?pasteTableRefreshFailed/);
});
-test("sidebar keyboard table copy uses the same normalized schema as the context menu", () => {
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
- const copySelectedSidebarNamesBody = functionBody(connectionTree, "copySelectedSidebarNames");
-
- assert.match(copySelectedSidebarNamesBody, /schema: connectionObjectTreeNodeSchema\(store\.getConfig\(node\.connectionId!\), node\.database!, node\.schema\)/);
-});
-
test("saved SQL tree rows expose copy, paste, export, rename, and confirmed deletion through the shared runtime host", () => {
const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
@@ -238,48 +116,3 @@ test("saved SQL tree rows expose copy, paste, export, rename, and confirmed dele
assert.match(runtimeHost, /async function confirmDeleteSavedSqlFile\(\)[\s\S]*?savedSqlStore\.deleteFile[\s\S]*?connectionStore\.removeTreeNode/);
assert.match(functionBody(runtimeHost, "requestDeleteSelectedNode"), /saved-sql-file[\s\S]*?showDeleteSavedSqlConfirm\.value = true/);
});
-
-test("explicit locate prioritizes the saved SQL row over SQL cursor table navigation", () => {
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
- const locateBody = functionBody(connectionTree, "locateTabInSidebar");
-
- assert.match(locateBody, /const locatesSavedSql = tabTarget\?\.type === "saved-sql-file"/);
- assert.match(locateBody, /const cursorCandidate = locatesSavedSql \? null : queryCursorTableCandidate/);
- assert.match(locateBody, /locatesSavedSql && savedSqlFile\?\.connectionId && savedSqlFile\.database[\s\S]*?type: "query-context"/);
- assert.match(locateBody, /findNodePathForTarget\(target, store\.treeNodes\)/);
-});
-
-test("tab context menu forwards the exact tab to centered sidebar locate without activating it", () => {
- const app = readFileSync("apps/desktop/src/App.vue", "utf8");
- const appSidebar = readFileSync("apps/desktop/src/components/layout/AppSidebar.vue", "utf8");
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
- const appLocateBody = functionBody(app, "locateTabInSidebar");
- const sidebarLocateBody = functionBody(appSidebar, "locateTabInSidebar");
- const activeLocateBody = functionBody(connectionTree, "locateActiveTabInSidebar");
- const locateBody = functionBody(connectionTree, "locateTabInSidebar");
-
- assert.match(app, /@locate-tab="locateTabInSidebar"/);
- assert.match(appLocateBody, /setSidebarOpen\(true\)/);
- assert.match(appLocateBody, /await nextTick\(\)/);
- assert.match(appLocateBody, /await appSidebarRef\.value\?\.locateTabInSidebar\(tab\)/);
- assert.doesNotMatch(appLocateBody, /activateQueryTab|activeTabId/);
- assert.match(sidebarLocateBody, /return connectionTreeRef\.value\?\.locateTabInSidebar\(tab\)/);
- assert.match(appSidebar, /defineExpose\(\{ focusSearch, locateTabInSidebar \}\)/);
- assert.match(activeLocateBody, /await locateTabInSidebar\(activeTab\.value, "smart"\)/);
- assert.match(locateBody, /await scrollToSidebarNode\(match\.id, \{ align \}\)/);
- assert.match(connectionTree, /defineExpose\(\{ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSidebar \}\)/);
- assert.match(connectionTree, /@request-connection-rename="startRenamingConnectionNode"/);
-});
-
-test("batch table paste refreshes each object list after all tables are processed", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTable");
- const pasteLoopIndex = confirmPasteTableBody.indexOf("for (const entry of entries)");
- const refreshLoopIndex = confirmPasteTableBody.indexOf("for (const refreshTarget of refreshTargets.values())");
-
- assert.notEqual(pasteLoopIndex, -1);
- assert.notEqual(refreshLoopIndex, -1);
- assert.ok(refreshLoopIndex > pasteLoopIndex, "object-list refresh must run after the table paste loop");
- assert.doesNotMatch(confirmPasteTableBody.slice(pasteLoopIndex, refreshLoopIndex), /refreshObjectListTreeNode/);
- assert.match(confirmPasteTableBody.slice(refreshLoopIndex), /refreshObjectListTreeNode\(refreshTarget\.connectionId, refreshTarget\.database, refreshTarget\.schema\)/);
-});
diff --git a/packages/app-tests/sidebarRuntimeDecomposition.test.ts b/packages/app-tests/sidebarRuntimeDecomposition.test.ts
deleted file mode 100644
index 494172e113..0000000000
--- a/packages/app-tests/sidebarRuntimeDecomposition.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-const treeItem = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
-const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
-const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
-const dataOpenRuntime = readFileSync("apps/desktop/src/composables/useSidebarDataOpenRuntime.ts", "utf8");
-
-function occurrences(source: string, pattern: RegExp): number {
- return source.match(pattern)?.length ?? 0;
-}
-
-test("sidebar rows stay within the hot-path source budget", () => {
- assert.ok(treeItem.split("\n").length <= 2_200, "TreeItem must stay below 2,200 lines");
- assert.ok(occurrences(treeItem, /^(?:async )?function /gm) <= 90, "TreeItem must stay below 90 top-level functions");
- // +1 for the plugin-platform connection visual (provider SVG on plugin rows)
- // and +1 for the disabled-trigger indicator.
- assert.ok(occurrences(treeItem, /^const [A-Za-z0-9_]+ = computed\(/gm) <= 30, "TreeItem must stay below 30 computed values");
- assert.doesNotMatch(treeItem, /ContextMenuItem|emit\("open-data"|getTreeItemDialogController|executeWithProductionSqlGuard/);
-});
-
-test("one tree-level runtime serves every row renderer", () => {
- assert.equal(occurrences(connectionTree, /<SidebarTreeRuntimeHost\b/g), 1);
- assert.equal(occurrences(connectionTree, /provide\(sidebarTreeRuntimeKey, sidebarTreeRuntime\)/g), 1);
- assert.match(connectionTree, /sidebarTreeRuntime\.buildContextMenu\(node\)/);
- assert.match(runtimeHost, /<template \/>/);
- assert.match(runtimeHost, /function bindMenuTarget\(/);
- assert.match(runtimeHost, /function activateActionTarget\(/);
- assert.match(runtimeHost, /useSidebarDataOpenRuntime\(\)/);
- assert.doesNotMatch(runtimeHost, /async function openData\(/);
- assert.match(dataOpenRuntime, /async function openData\(/);
- assert.match(dataOpenRuntime, /findExistingDataTabCandidate/);
- assert.match(dataOpenRuntime, /loadTableMetadata/);
- assert.match(dataOpenRuntime, /canApplyDataTabMetadata/);
-});
-
-test("connection detail tooltips expose every known visible-filter count", () => {
- assert.match(treeItem, /connectionStore\.getSidebarVisibleFilterSummary\(node\.connectionId\)/);
- assert.match(treeItem, /visibleFilterSummary\?\.selected != null && visibleFilterSummary\.total != null/);
- assert.doesNotMatch(treeItem, /visibleFilterSummary\?\.isActive/);
- assert.match(treeItem, /visibleSchemas\.detailLabel/);
- assert.match(treeItem, /visibleDatabases\.detailLabel/);
- assert.match(treeItem, /treeRuntime\.openPrimaryVisibleFilter\(node\)/);
- assert.match(runtimeHost, /function openPrimaryVisibleFilter\(node: TreeNode\)/);
- assert.match(runtimeHost, /openVisibleDatabasesDialog\(\)/);
- assert.doesNotMatch(treeItem, /SidebarVisibleFilterControl/);
-});
-
-test("the persistent runtime releases detached tree nodes", () => {
- const actionTarget = readFileSync("apps/desktop/src/lib/sidebar/sidebarActionTarget.ts", "utf8");
- const connectionMutationRuntime = readFileSync("apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts", "utf8");
- const tableMutationRuntime = readFileSync("apps/desktop/src/composables/useSidebarTableMutationRuntime.ts", "utf8");
-
- assert.match(actionTarget, /function releaseRemovedSidebarActionTarget/);
- assert.match(actionTarget, /children: undefined, hiddenChildren: undefined/);
- assert.match(runtimeHost, /\(\) => connectionStore\.treeNodes/);
- assert.match(runtimeHost, /findSidebarActionTarget\(nodes, createSidebarActionTarget\(activeNode\.value\)\)/);
- assert.match(connectionMutationRuntime, /releaseActiveNodeReference\(targets\.map\(\(target\) => target\.id\)\)/);
- assert.match(tableMutationRuntime, /releaseActiveNodeReference\(\[node\.id\]\)/);
-});
diff --git a/packages/app-tests/sidebarTreeAffordances.test.ts b/packages/app-tests/sidebarTreeAffordances.test.ts
index dab550d7db..5836041fb1 100644
--- a/packages/app-tests/sidebarTreeAffordances.test.ts
+++ b/packages/app-tests/sidebarTreeAffordances.test.ts
@@ -1,49 +1,8 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { syncSidebarTreeNodeExpansion } from "../../apps/desktop/src/lib/sidebar/sidebarTreeExpansion.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
-const treeItem = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
-const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
-const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
-const sidebarSearchTree = readFileSync("apps/desktop/src/lib/sidebar/sidebarSearchTree.ts", "utf8");
-const connectionStore = readFileSync("apps/desktop/src/stores/connectionStore.ts", "utf8");
-
-test("sidebar rows retain database-specific node affordances", () => {
- for (const nodeType of ["connection", "database", "schema", "table", "column", "mongo-db", "mongo-collection", "redis-db", "nacos-namespace", "mq-tenant"]) {
- const sources = `${treeItem}\n${runtimeHost}`;
- assert.ok(sources.includes(`node.type === "${nodeType}"`) || sources.includes(`node.type === '${nodeType}'`), nodeType);
- }
- assert.match(treeItem, /@dblclick="onDoubleClick"/);
- assert.match(treeItem, /@keydown="onKeydown"/);
- assert.match(treeItem, /@mousedown="onRowMouseDown"/);
- assert.match(treeItem, /@contextmenu="onTreeItemContextMenu"/);
-});
-
-test("plain tree sticky headers position the full row wrapper without a divider", () => {
- assert.match(treeItem, /<div v-else :class="\{ 'sidebar-tree-item--sticky': stickyHeader \}" @contextmenu="onTreeItemContextMenu">/);
- assert.doesNotMatch(treeItem, /'tree-item-highlight': highlighted,\s*'sidebar-tree-item--sticky': stickyHeader/);
- assert.match(treeItem, /\.sidebar-tree-item--sticky\s*\{[\s\S]*?position:\s*sticky;/);
- assert.match(treeItem, /\.sidebar-tree-item--sticky\s*\{[\s\S]*?background-color:\s*var\(--sidebar\);/);
- assert.doesNotMatch(treeItem, /\.sidebar-tree-item--sticky\s*\{[^}]*border-bottom:/);
- assert.doesNotMatch(connectionTree, /sticky-database-header[^\n]*border-b/);
- assert.match(connectionTree, /\.sticky-database-header\s*\{[\s\S]*?background-color:\s*var\(--sidebar\);/);
- assert.match(connectionTree, /v-for="\(item, index\) in flatNodes"/);
- assert.match(connectionTree, /:sticky-header="isPlainStickyContainerNode\(index\)"/);
- assert.match(connectionTree, /return flatTreeIndex\.value\.stickyContainerIndexByIndex\[index\] === index;/);
-});
-
-test("complex tree changes retain the full rebuild fallback", () => {
- assert.match(connectionTree, /const filteredNodes = computed/);
- assert.match(connectionTree, /filterSidebarTree\(/);
- assert.match(connectionTree, /const flatNodes = computed<FlatTreeNode\[]>/);
- assert.match(connectionTree, /flattenTree\(filteredNodes\.value\)/);
- assert.match(connectionTree, /watch\(flatNodes,/);
- assert.doesNotMatch(connectionTree, /treeScrollerRef\.value\?\.(?:forceUpdate|updateVisibleItems)/);
- assert.match(connectionTree, /@node-toggled="onNodeToggled"/);
-});
-
test("tree toggles synchronize filtered node clones with the live sidebar tree", () => {
const expandedConnection: TreeNode = {
id: "connection-1",
@@ -86,25 +45,3 @@ test("async tree expansion does not restore a stale rendered clone state", () =>
assert.equal(syncSidebarTreeNodeExpansion([liveDatabase], staleRenderedClone, true), false);
assert.equal(liveDatabase.isExpanded, true);
});
-
-test("tree filters retain a temporary expansion state", () => {
- assert.match(sidebarSearchTree, /return \{ \.\.\.node, children: matchingChildren \};/);
- assert.doesNotMatch(sidebarSearchTree, /children: matchingChildren,\s*isExpanded:\s*true/);
- assert.match(connectionTree, /function onSearchToggle\(node: TreeNode\) \{\s*if \(!isTreeSearchFiltering\.value \|\| !node\.children\) return;/);
- // The search guard must stay the first thing in onNodeToggled (filter toggles
- // must never sync back to the live tree); side-effect-free diagnostics may be
- // interleaved before the sync call, so match the guard and the required sync
- // separately instead of pinning the exact body.
- assert.match(connectionTree, /function onNodeToggled\(node: TreeNode, expanded: boolean\) \{\s*if \(isTreeSearchFiltering\.value\) return;[\s\S]*?syncSidebarTreeNodeExpansion\(store\.treeNodes, node, expanded\)/);
- assert.match(runtimeHost, /shouldRunTreeNodeRowAction\(action, clickDetail, isGroupLabel\(node\) \|\| isRepeatableNavigationTreeNode\(node\.type\)\)/);
-});
-
-test("tree rebuilds keep a context menu only while its target row remains visible", () => {
- assert.match(connectionTree, /nodes\.find\(\(\{ node \}\) => matchesSidebarActionTarget\(node, contextMenuTarget\)\)\?\.node/);
- assert.match(connectionTree, /if \(!visibleContextMenuTarget \|\| visibleContextMenuTarget\.valid === false\)/);
-});
-
-test("programmable object groups use the shared metadata loader", () => {
- assert.match(runtimeHost, /const databaseObjectGroup = !!objectTypesForGroupNode\(node\.type\)/);
- assert.match(connectionStore, /else if \(objectTypesForGroupNode\(node\.type\)\) \{\s*await loadObjectGroupChildren\(node, options\);/);
-});
diff --git a/packages/app-tests/sidebarTreeItemCleanup.test.ts b/packages/app-tests/sidebarTreeItemCleanup.test.ts
deleted file mode 100644
index d2f07b1acc..0000000000
--- a/packages/app-tests/sidebarTreeItemCleanup.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileScript, parse } from "vue/compiler-sfc";
-
-const treeItem = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
-
-test("sidebar row template components have script bindings", () => {
- const descriptor = parse(treeItem).descriptor;
- const bindings = compileScript(descriptor, { id: "sidebar-tree-item" }).bindings;
- const template = descriptor.template;
- assert.ok(template);
-
- const componentTags = new Set(Array.from(template.content.matchAll(/<([A-Z][A-Za-z0-9]*)\b/g), (match) => match[1]));
-
- for (const tag of componentTags) assert.ok(bindings[tag], `TreeItem template component ${tag} must be imported`);
-});
-
-test("recycled sidebar rows re-register paste handlers by node id", () => {
- assert.ok(treeItem.indexOf("const sidebarTreeContext = inject") < treeItem.indexOf("const stopPasteHandlerRegistration = watch"));
- assert.match(treeItem, /watch\(\s*\(\) => props\.node\.id,/);
- assert.match(treeItem, /registerPasteHandler\?\.\(nodeId, \(\) => treeRuntime\.requestPaste\(props\.node\)\)/);
- assert.match(treeItem, /if \(unregister\) onCleanup\(unregister\)/);
-});
-
-test("connection group rename requests are owned by the rendered row", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- const connectionMutationRuntime = readFileSync("apps/desktop/src/composables/useSidebarConnectionMutationRuntime.ts", "utf8");
- const connectionTree = readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8");
-
- assert.match(treeItem, /const renameInputRef = ref<HTMLInputElement>\(\)/);
- assert.match(treeItem, /watch\(\s*\(\) => props\.pendingRename,[\s\S]*?startRenameGroup\(\)/);
- assert.match(treeItem, /focusSidebarRenameInput\(\(\) => \(isRenamingGroup\.value \? renameInputRef\.value : undefined\)\)/);
- assert.match(runtimeHost, /requestGroupRename: \(groupId\) => emit\("request-group-rename", groupId\)/);
- assert.match(connectionMutationRuntime, /options\.requestGroupRename\(activeNode\.value\.id\)/);
- assert.doesNotMatch(runtimeHost, /const isRenamingGroup = ref\(/);
- assert.match(connectionTree, /@request-group-rename="startRenamingCreatedGroup"/);
-});
-
-test("sidebar row unmount clears observers, handlers and drag state", () => {
- assert.match(treeItem, /function handleMouseLeave\(\)[\s\S]*?labelResizeObserver\?\.disconnect\(\)/);
- assert.match(treeItem, /function finishTableReferenceDrag\(\)[\s\S]*?document\.removeEventListener\("mousemove"/);
- assert.match(treeItem, /onBeforeUnmount\(\(\) => \{[\s\S]*?stopPasteHandlerRegistration\(\)[\s\S]*?handleMouseLeave\(\)[\s\S]*?finishTableReferenceDrag\(\)/);
- assert.match(treeItem, /watch\([\s\S]*?\(\) => props\.node,[\s\S]*?finishTableReferenceDrag\(\)/);
-});
-
-test("sidebar rows do not own dialog templates or eager dialog state", () => {
- const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");
- assert.doesNotMatch(treeItem, /<Dialog(?:\s|>)/);
- assert.doesNotMatch(treeItem, /<DangerConfirmDialog/);
- assert.doesNotMatch(treeItem, /const show[A-Z][A-Za-z]+(?:Dialog|Confirm) = ref\(/);
- assert.doesNotMatch(treeItem, /function getTreeItemDialogController\(\)/);
- assert.match(treeItem, /inject\(sidebarTreeRuntimeKey\)/);
- assert.match(runtimeHost, /function getTreeItemDialogController\(\)/);
- assert.match(runtimeHost, /if \(treeItemDialogController\) return treeItemDialogController/);
-});
diff --git a/packages/app-tests/sqlFileExecutionDialog.test.ts b/packages/app-tests/sqlFileExecutionDialog.test.ts
deleted file mode 100644
index a155443e58..0000000000
--- a/packages/app-tests/sqlFileExecutionDialog.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";
-
-const dialogPath = "apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue";
-const dialogSource = readFileSync(dialogPath, "utf8");
-
-test("SQL file execution dialog SFC compiles", () => {
- const { descriptor, errors } = parse(dialogSource, { filename: dialogPath });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.scriptSetup);
- compileScript(descriptor, { id: dialogPath });
- assert.ok(descriptor.template);
- const result = compileTemplate({ id: dialogPath, filename: dialogPath, source: descriptor.template.content });
- assert.deepEqual(result.errors, []);
-});
-
-test("SQL file execution dialog keeps actions visible within narrow viewports", () => {
- assert.match(dialogSource, /DialogScrollContent class="[^"]*max-h-\[calc\(var\(--dbx-viewport-height\)-6rem\)\][^"]*flex-col[^"]*overflow-hidden/);
- assert.match(dialogSource, /<DialogHeader class="shrink-0">/);
- assert.match(dialogSource, /class="grid min-h-0 min-w-0 flex-1 gap-4 overflow-y-auto py-3"/);
- assert.match(dialogSource, /class="grid grid-cols-1 gap-3 sm:grid-cols-2"/);
- assert.match(dialogSource, /<DialogFooter class="shrink-0">/);
-});
-
-test("SQL file execution summary reserves space for aggregate columns", () => {
- assert.match(dialogSource, /v-if="!running && previews\.length > 1 && perFileResults\.length > 0"/);
- assert.doesNotMatch(dialogSource, /terminalStatus === 'done' && previews\.length > 1 && perFileResults\.length > 0/);
- assert.match(dialogSource, /<table class="w-full table-fixed">/);
- assert.match(dialogSource, /<colgroup>[\s\S]*<col \/>[\s\S]*<col class="w-\[4\.5rem\]" \/>[\s\S]*<col class="w-\[5\.5rem\]" \/>[\s\S]*<\/colgroup>/);
- assert.match(dialogSource, /<td class="px-2\.5 py-1\.5 truncate" :title="item\.fileName">/);
- assert.match(dialogSource, /<thead class="sticky top-0 z-10 border-b border-border bg-muted text-foreground shadow-/);
- assert.match(dialogSource, /<tfoot class="sticky bottom-0 z-10 border-t-2 border-primary\/35 bg-muted font-semibold text-foreground/);
- assert.match(dialogSource, /<th scope="row" class="px-2\.5 py-2 text-left">\{\{ t\("sqlFile\.totalFiles"/);
-});
diff --git a/packages/app-tests/sqlLibraryImportEncoding.test.ts b/packages/app-tests/sqlLibraryImportEncoding.test.ts
deleted file mode 100644
index 2cba3161fa..0000000000
--- a/packages/app-tests/sqlLibraryImportEncoding.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-const source = readFileSync("apps/desktop/src/components/layout/SqlLibraryPanel.vue", "utf8");
-
-test("SQL library imports use the charset-aware external SQL reader", () => {
- const start = source.indexOf("async function importDirectoryIntoLibrary");
- const end = source.indexOf("async function chooseSyncDirectory", start);
- const handler = start >= 0 && end > start ? source.slice(start, end) : "";
-
- assert.match(handler, /await api\.readExternalSqlFile\(path, externalSqlEditorMaxBytes\(settingsStore\.editorSettings\.externalSqlEditorMaxMb\)\)/);
- assert.doesNotMatch(handler, /readTextFile/);
-});
-
-test("SQL library directory imports use the native pruned folder scanner", () => {
- const start = source.indexOf("async function collectSqlFilesRecursively");
- const end = source.indexOf("async function importDirectoryIntoLibrary", start);
- const scanner = start >= 0 && end > start ? source.slice(start, end) : "";
-
- assert.match(scanner, /await api\.listSqlFilesInFolder\(dir\)/);
- assert.doesNotMatch(scanner, /@tauri-apps\/plugin-fs|readDir/);
-});
-
-test("SQL library directory imports preserve nested folder paths", () => {
- const start = source.indexOf("async function importDirectoryIntoLibrary");
- const end = source.indexOf("async function chooseSyncDirectory", start);
- const handler = start >= 0 && end > start ? source.slice(start, end) : "";
-
- assert.match(handler, /resolveImportedFolder\(folderConnectionId, targetFolder\?\.id, file\.folderNames, folderCache\)/);
- assert.match(handler, /uniqueImportedName\(file\.name, takenNames\)/);
- assert.doesNotMatch(handler, /relativeImportName/);
-});
-
-test("SQL library file menu can open a file with the current tab target", () => {
- assert.match(source, /label: t\("sqlLibrary\.openInCurrentDatabase"\)/);
- assert.match(source, /action: \(\) => openFile\(target, "current"\)/);
- assert.match(source, /disabled: !hasCurrentSavedSqlExecutionTarget\.value/);
-});
diff --git a/packages/app-tests/sshConfigHosts.test.ts b/packages/app-tests/sshConfigHosts.test.ts
index 5908b64402..d6723b968f 100644
--- a/packages/app-tests/sshConfigHosts.test.ts
+++ b/packages/app-tests/sshConfigHosts.test.ts
@@ -1,6 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import path from "node:path";
import { test } from "vitest";
import { applySshConfigHostAliasPrefill } from "../../apps/desktop/src/lib/connection/sshConfigHosts.ts";
import type { SshTunnelConfig } from "../../apps/desktop/src/types/database.ts";
@@ -62,12 +60,3 @@ test("leaves the form unchanged when no config alias matches", () => {
assert.deepEqual(target, before);
});
-
-test("loads and exposes SSH config aliases in tunnel profile maintenance", () => {
- const component = readFileSync(path.resolve("apps/desktop/src/components/connection/TunnelProfileManager.vue"), "utf8");
-
- assert.match(component, /api\.listSshConfigHosts\(\)/);
- assert.match(component, /list="tunnel-profile-ssh-config-host-aliases"/);
- assert.match(component, /<datalist id="tunnel-profile-ssh-config-host-aliases">/);
- assert.match(component, /@update:model-value="updateSelectedSshHost"/);
-});
diff --git a/packages/app-tests/syncTunnelProfiles.test.ts b/packages/app-tests/syncTunnelProfiles.test.ts
deleted file mode 100644
index 7b50b26e0e..0000000000
--- a/packages/app-tests/syncTunnelProfiles.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-function functionBody(source: string, name: string): string {
- const signature = `async function ${name}(`;
- const signatureIndex = source.indexOf(signature);
- assert.notEqual(signatureIndex, -1, `Could not find function ${name}`);
- const bodyStart = source.indexOf("{", signatureIndex);
- assert.notEqual(bodyStart, -1, `Could not find body for ${name}`);
-
- let depth = 0;
- for (let index = bodyStart; index < source.length; index += 1) {
- if (source[index] === "{") depth += 1;
- if (source[index] === "}") {
- depth -= 1;
- if (depth === 0) return source.slice(bodyStart + 1, index);
- }
- }
- throw new Error(`Could not parse body for ${name}`);
-}
-
-test("sync downloads refresh shared tunnel profiles", () => {
- const source = readFileSync("apps/desktop/src/components/editor/EditorSettingsDialog.vue", "utf8");
-
- for (const functionName of ["downloadSnippetSnapshot", "downloadWebDavSnapshot"]) {
- const body = functionBody(source, functionName);
- assert.match(body, /await tunnelProfileStore\.refresh\(\)/, `${functionName} should refresh downloaded tunnel profiles`);
- }
-});
diff --git a/packages/app-tests/tableInfoDefaultValue.test.ts b/packages/app-tests/tableInfoDefaultValue.test.ts
index 47d55fd94a..86da7e4e7f 100644
--- a/packages/app-tests/tableInfoDefaultValue.test.ts
+++ b/packages/app-tests/tableInfoDefaultValue.test.ts
@@ -1,11 +1,7 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
-import { compileTemplate, parse } from "vue/compiler-sfc";
import { tableColumnDefaultDisplayValue } from "@/lib/table/tableColumnDefaultPresentation";
-const tableInfoSurfaces = ["apps/desktop/src/components/objects/ObjectBrowser.vue", "apps/desktop/src/components/grid/DataGridTableInfoPanels.vue"];
-
test("table column defaults preserve raw database expressions", () => {
const values = [null, "''", "0", "CURRENT_TIMESTAMP", "((1))", "('prefix (internal)')", "x".repeat(512)] as const;
@@ -13,19 +9,3 @@ test("table column defaults preserve raw database expressions", () => {
assert.equal(tableColumnDefaultDisplayValue(undefined), "—");
assert.equal(tableColumnDefaultDisplayValue(""), "");
});
-
-test("both table information surfaces expose the same default-value column", () => {
- for (const path of tableInfoSurfaces) {
- const source = readFileSync(path, "utf8");
- const { descriptor, errors } = parse(source, { filename: path });
- assert.deepEqual(errors, []);
- assert.ok(descriptor.template);
- const result = compileTemplate({ id: path, filename: path, source: descriptor.template.content });
- assert.deepEqual(result.errors, []);
-
- assert.match(descriptor.template.content, /t\("structureEditor\.defaultValue"\)/);
- assert.match(descriptor.template.content, /data-table-info-column-default/);
- assert.match(descriptor.template.content, /:title="column\.column_default \?\? undefined"/);
- assert.match(descriptor.template.content, /tableColumnDefaultDisplayValue\(column\.column_default\)/);
- }
-});
diff --git a/packages/app-tests/tablePartitionsTabParity.test.ts b/packages/app-tests/tablePartitionsTabParity.test.ts
deleted file mode 100644
index 4c30164be4..0000000000
--- a/packages/app-tests/tablePartitionsTabParity.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { test } from "vitest";
-
-// The table-properties drawer exists twice (DataGrid and ObjectBrowser), each
-// with its own tab list, plus a shared body component. A partitions tab must be
-// wired into all of them together, otherwise the drawer silently loses the tab
-// on one surface.
-const drawerSurfaces = [
- "apps/desktop/src/components/grid/DataGrid.vue",
- "apps/desktop/src/components/objects/ObjectBrowser.vue",
-];
-
-test("both table-properties drawers expose a capability-gated partitions tab", () => {
- for (const path of drawerSurfaces) {
- const source = readFileSync(path, "utf8");
- assert.match(source, /id:\s*"partitions"/, `${path} must add a partitions tab`);
- assert.match(
- source,
- /tableMetadataCapabilities\.value\.partitions/,
- `${path} must gate the partitions tab on the capability`,
- );
- // A plain table must not show the tab at all, so both drawers probe the
- // cheap partition status and gate on the result.
- assert.match(source, /api\.getTablePartitionStatus/, `${path} must probe the partition status`);
- assert.match(source, /isPartitionedTable|tableIsPartitioned/, `${path} must gate on the probed status`);
- assert.match(source, /fetchPartitions|fetchTablePartitions/, `${path} must load partition metadata`);
- }
-});
-
-test("both drawers probe the partition status on demand, not only on table change", () => {
- // Regression: probing only in the table-change watcher meant opening the
- // drawer for an already-selected table never resolved the status, so the
- // Partitions tab was missing on every partitioned table.
- const expectations: Array<[string, RegExp]> = [
- ["apps/desktop/src/components/grid/DataGrid.vue", /if \(!partitionStatusResolved\.value\) await probeTablePartitionStatus\(\)/],
- [
- "apps/desktop/src/components/objects/ObjectBrowser.vue",
- /if \(!tablePartitionStatusResolved\.value\) await probeTablePartitionStatus\(\)/,
- ],
- ];
- for (const [path, pattern] of expectations) {
- assert.match(readFileSync(path, "utf8"), pattern, `${path} must probe on demand in selectTableInfoTab`);
- }
-});
-
-test("both drawers render the shared partitions panel", () => {
- const panels = readFileSync("apps/desktop/src/components/grid/DataGridTableInfoPanels.vue", "utf8");
- assert.match(panels, /TablePartitionsPanel/);
-
- const objectBrowser = readFileSync("apps/desktop/src/components/objects/ObjectBrowser.vue", "utf8");
- assert.match(objectBrowser, /TablePartitionsPanel/);
-});
-
-test("the partitions tab is a first-class persisted table-info tab", () => {
- const settings = readFileSync("apps/desktop/src/stores/settingsStore.ts", "utf8");
- assert.match(settings, /TABLE_INFO_TABS = new Set<TableInfoTab>\(\[[^\]]*"partitions"/);
-});
diff --git a/packages/app-tests/tableStructureEditorState.test.ts b/packages/app-tests/tableStructureEditorState.test.ts
index de8c38feab..84853bba07 100644
--- a/packages/app-tests/tableStructureEditorState.test.ts
+++ b/packages/app-tests/tableStructureEditorState.test.ts
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import {
applyManticoreDdlColumnExtras,
@@ -661,31 +660,6 @@ test("falls back to DDL when no editable metadata tab is available", () => {
assert.equal(firstStructureMetadataTab(ddlOnlyCapabilities, false), "ddl");
});
-test("preserves a restored structure draft tab without an explicit initial tab", () => {
- const source = readFileSync("apps/desktop/src/components/structure/TableStructureEditor.vue", "utf8");
- const restoredDraftBlock = source.match(/if \(props\.draft\?\.initialized\) \{[\s\S]*?\n \} else if/);
-
- assert.ok(restoredDraftBlock);
- assert.match(restoredDraftBlock[0], /restoreDraft\(props\.draft\);[\s\S]*applyPendingInitialStructureTab\(\);[\s\S]*applyInitialStructureTarget\(\);/);
-});
-
-test("renders editable structure tables with flat cell controls", () => {
- const source = readFileSync("apps/desktop/src/components/structure/TableStructureEditor.vue", "utf8");
-
- assert.match(source, /<CustomContextMenu :items="activeColumnContextMenuItems"[\s\S]*<RecycleScroller[\s\S]*item-class="structure-column-virtual-row"[\s\S]*list-class="structure-column-virtual-list"/);
- assert.match(source, /:item-size="columnVirtualItemSize"/);
- assert.match(source, /const useColumnVirtualFlowMode = isTauriRuntime\(\) && isMacOS\(\);/);
- assert.match(source, /:flow-mode="useColumnVirtualFlowMode"/);
- assert.doesNotMatch(source, /:disable-transform=/);
- assert.match(source, /<template #default="\{ item: \{ column, index \}, active \}">[\s\S]*<table class="structure-column-virtual-row-table/);
- assert.doesNotMatch(source, /<CustomContextMenu :key="column\.id"/);
- assert.match(source, /<tbody class="structure-edit-grid">/);
- assert.match(source, /const structureControlClass = "structure-grid-control /);
- assert.match(source, /\.structure-edit-grid :deep\(\.structure-grid-control\) \{[\s\S]*?border-radius: 0;/);
- assert.match(source, /\.structure-edit-grid > tbody > tr > td:focus-within,[\s\S]*?\.structure-edit-grid > tr > td:focus-within \{/);
- assert.match(source, /\.structure-column-virtual-scroller\.is-scrolling :deep\(\.structure-column-virtual-row \*\) \{[\s\S]*?transition: none !important;/);
-});
-
test("supports DDL tab in edit mode", () => {
assert.equal(isStructureMetadataTabSupported("ddl", fullCapabilities, false), true);
});
diff --git a/packages/app-tests/useFlatTree.test.ts b/packages/app-tests/useFlatTree.test.ts
index e9b2cd78ab..a4a4a8ca7b 100644
--- a/packages/app-tests/useFlatTree.test.ts
+++ b/packages/app-tests/useFlatTree.test.ts
@@ -1,11 +1,8 @@
import { strict as assert } from "node:assert";
-import { readFileSync } from "node:fs";
import { test } from "vitest";
import { createFlatTreeIndex, SIDEBAR_TREE_ROW_HEIGHT, SIDEBAR_TREE_PRERENDER_COUNT, SIDEBAR_TREE_SCROLL_BUFFER, flattenTree, shouldVirtualizeFlatTree } from "../../apps/desktop/src/composables/useFlatTree.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
-const connectionTreeSource = readFileSync(new URL("../../apps/desktop/src/components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
-
test("flattenTree preserves depth and node type for virtualized sidebar rows", () => {
const nodes: TreeNode[] = [
{
@@ -127,9 +124,3 @@ test("sidebar virtual tree keeps enough buffered rows for fast scrolling", () =>
test("sidebar virtual tree prerenders enough rows for the first frame", () => {
assert.ok(SIDEBAR_TREE_PRERENDER_COUNT >= 40);
});
-
-test("sidebar virtual tree recycles rows by render identity", () => {
- assert.match(connectionTreeSource, /key-field="renderKey"/);
- assert.match(connectionTreeSource, /type-field="poolType"/);
- assert.match(connectionTreeSource, /\bflow-mode\b/);
-});