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

This commit is contained in:
t8y2 committed 2026-09-23 22:10:06 +08:00
1 parent 349d77d180
commit 8897e12714
257 files changed
+166 -12815

No files matched your search

@@ -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");
});
});
@@ -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)"));
});
});
@@ -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>");
});
});
@@ -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");
@@ -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";');
});
});
@@ -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]');
});
});
@@ -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;");
});
});
@@ -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");
});
});
@@ -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);
});
});
@@ -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"');
});
});
@@ -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\(\);/);
});
});
@@ -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"');
});
});
@@ -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"');
}
});
});
@@ -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
@@ -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)");
});
});
@@ -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: ".+"/);
});
});
@@ -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);
});
});
@@ -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);");
});
});
@@ -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`\)/);
});
});
@@ -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");
@@ -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") }}');
});
});
@@ -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> }));
@@ -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");
});
});
@@ -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"');
});
});
@@ -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();");
});
});
@@ -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);
});
});
@@ -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);");
});
});
@@ -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,");
});
});
@@ -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()" />');
});
});