From 20ffc62249eded69dc11000b204af4b7f18265ea Mon Sep 17 00:00:00 2001 From: onenewcode Date: Wed, 30 Sep 2026 15:34:23 +0800 Subject: [PATCH] fix(mcp): persist the access policy only on explicit apply --- .../editor/EditorSettingsDialog.vue | 221 +++++++++--------- ...Dialog.mcpQueryTimeout.integration.spec.ts | 46 ++-- ...itorSettingsDialog.mcpQueryTimeout.spec.ts | 143 +++++------- .../__tests__/mcpQueryTimeoutHarness.ts | 28 +-- .../settings/McpAuthorizationStepper.vue | 5 +- 5 files changed, 198 insertions(+), 245 deletions(-) diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue index d01fdf746e..3fe44d99d3 100644 --- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue +++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue @@ -106,7 +106,8 @@ import { type CustomThemeColors, type CustomTheme, type McpConnectionPolicy, - type McpGroupPolicy, + type McpGlobalPolicy, + normalizeMcpGlobalPolicy, type ClickTableNavigationTarget, type EditorSettings, type SqlCompletionTriggerMode, @@ -549,9 +550,9 @@ const settingsTitleComponent = computed(() => (isSettingsPage.value ? "h2" : Dia const showUnsavedSettingsCloseConfirm = ref(false); function requestCloseSettings(nextOpen: boolean) { - // Flush any pending debounced MCP query-timeout save so a value typed right - // before closing is persisted instead of dropped (see onMcpQueryTimeoutInput). - flushMcpQueryTimeoutSave(); + // Fold a timeout typed immediately before close into the draft so the unsaved + // prompt can see it. This must not persist: discard drops the draft. + stageMcpQueryTimeoutDraft(); if (shouldConfirmEditorSettingsDialogClose(nextOpen, hasChanges())) { showUnsavedSettingsCloseConfirm.value = true; return; @@ -574,6 +575,7 @@ function cancelUnsavedSettingsClose() { function discardUnsavedSettingsAndClose() { showUnsavedSettingsCloseConfirm.value = false; + syncMcpPolicyBaseline(mcpPolicyBaseline.value); emit("update:open", false); } @@ -2241,7 +2243,8 @@ function hasChanges(): boolean { editMetadataCacheMaxMemoryMb.value !== settingsStore.desktopSettings.metadata_cache_max_memory_mb || editDuckDbWorkerProcessIsolation.value !== settingsStore.desktopSettings.duckdb_worker_process_isolation || normalizeDuckDbWorkerMaxProcesses(editDuckDbWorkerMaxProcesses.value) !== settingsStore.desktopSettings.duckdb_worker_max_processes || - editSidebarTablePageSize.value !== (settingsStore.desktopSettings.sidebar_table_page_size ?? DEFAULT_SIDEBAR_TABLE_PAGE_SIZE) + editSidebarTablePageSize.value !== (settingsStore.desktopSettings.sidebar_table_page_size ?? DEFAULT_SIDEBAR_TABLE_PAGE_SIZE) || + mcpPolicyHasUnsavedChanges() ); } @@ -2289,6 +2292,7 @@ async function persistSettings() { } else if (sidebarTablePageSizeChanged) { await connectionStore.refreshSidebarObjectPagination(); } + await commitMcpPolicyDraft(); } function applySettingsErrorToast(error: unknown) { @@ -3500,41 +3504,52 @@ const mcpInstalling = ref(false); const mcpUninstalling = ref(false); const mcpInstallMessage = ref(""); const mcpInstallError = ref(false); -const mcpExecutionMode = computed(() => mcpExecutionModeFromPolicy(settingsStore.mcpGlobalPolicy)); +const mcpPolicyDraft = ref(normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy)); +const mcpPolicyBaseline = ref(normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy)); + +function syncMcpPolicyBaseline(policy: McpGlobalPolicy) { + const next = normalizeMcpGlobalPolicy(policy); + mcpPolicyBaseline.value = next; + mcpPolicyDraft.value = normalizeMcpGlobalPolicy(next); + mcpQueryTimeoutPendingValue = undefined; + if (mcpQueryTimeoutSaveTimer !== null) { + clearTimeout(mcpQueryTimeoutSaveTimer); + mcpQueryTimeoutSaveTimer = null; + } + mcpQueryTimeoutInput.value = next.queryTimeoutSecs === null ? "" : String(next.queryTimeoutSecs); +} + +function mcpPoliciesEqual(left: McpGlobalPolicy, right: McpGlobalPolicy): boolean { + return JSON.stringify(normalizeMcpGlobalPolicy(left)) === JSON.stringify(normalizeMcpGlobalPolicy(right)); +} + +function stageMcpPolicy(partial: Partial>) { + mcpPolicyDraft.value = normalizeMcpGlobalPolicy({ + ...mcpPolicyDraft.value, + ...partial, + }); +} + +function mcpPolicyHasUnsavedChanges(): boolean { + return mcpQueryTimeoutPendingValue !== undefined || !mcpPoliciesEqual(mcpPolicyDraft.value, mcpPolicyBaseline.value); +} + +const mcpExecutionMode = computed(() => mcpExecutionModeFromPolicy(mcpPolicyDraft.value)); const mcpExecutionModeOptions: McpExecutionMode[] = ["read_only", "safe_write", "high_risk_write"]; -const mcpAllowedConnectionIds = computed(() => settingsStore.mcpGlobalPolicy.allowedConnectionIds); -const mcpAllowedGroupIds = computed(() => settingsStore.mcpGlobalPolicy.allowedGroupIds); -const mcpQueryTimeoutInput = ref(settingsStore.mcpGlobalPolicy.queryTimeoutSecs === null ? "" : String(settingsStore.mcpGlobalPolicy.queryTimeoutSecs)); +const mcpAllowedConnectionIds = computed(() => mcpPolicyDraft.value.allowedConnectionIds); +const mcpAllowedGroupIds = computed(() => mcpPolicyDraft.value.allowedGroupIds); +const mcpQueryTimeoutInput = ref(mcpPolicyDraft.value.queryTimeoutSecs === null ? "" : String(mcpPolicyDraft.value.queryTimeoutSecs)); watch( - () => settingsStore.mcpGlobalPolicy.queryTimeoutSecs, + () => mcpPolicyDraft.value.queryTimeoutSecs, (value) => { + if (mcpQueryTimeoutPendingValue !== undefined) return; mcpQueryTimeoutInput.value = value === null ? "" : String(value); }, ); -type McpQueryTimeoutSaveStatus = "idle" | "saving" | "saved" | "failed"; -const mcpQueryTimeoutSaveStatus = ref("idle"); -let mcpQueryTimeoutSavedStatusTimer: ReturnType | null = null; - -function setMcpQueryTimeoutSaveStatus(status: McpQueryTimeoutSaveStatus) { - if (mcpQueryTimeoutSavedStatusTimer !== null) { - clearTimeout(mcpQueryTimeoutSavedStatusTimer); - mcpQueryTimeoutSavedStatusTimer = null; - } - mcpQueryTimeoutSaveStatus.value = status; - if (status === "saved") { - mcpQueryTimeoutSavedStatusTimer = setTimeout(() => { - mcpQueryTimeoutSavedStatusTimer = null; - mcpQueryTimeoutSaveStatus.value = "idle"; - }, 1600); - } -} - -// Debounce the persist so rapid typing coalesces into a single SQLite write. -// `flushMcpQueryTimeoutSave` runs on the settings-close path so a value typed -// right before closing is still persisted (the legacy @change binding only -// fired on blur/Enter, silently dropping the value when the window closed). +// Debounce typing into the policy draft. Persistence happens only on an explicit +// save; closing and discarding must not write this value. const MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS = 300; let mcpQueryTimeoutSaveTimer: ReturnType | null = null; let mcpQueryTimeoutPendingValue: number | null | undefined; @@ -3547,7 +3562,6 @@ function onMcpQueryTimeoutInput(event: Event) { // mistake that browser state for an explicit request to inherit the timeout. if (target.validity.badInput) return; const raw = target.value.trim(); - setMcpQueryTimeoutSaveStatus("saving"); if (raw === "") { mcpQueryTimeoutPendingValue = null; } else { @@ -3558,11 +3572,10 @@ function onMcpQueryTimeoutInput(event: Event) { toast(t("settings.mcpQueryTimeoutInvalid"), 5000); // Revert before Input's bubble-phase v-model handler sees the value, so // the proxy and parent ref remain aligned. - const reverted = settingsStore.mcpGlobalPolicy.queryTimeoutSecs === null ? "" : String(settingsStore.mcpGlobalPolicy.queryTimeoutSecs); + const reverted = mcpPolicyDraft.value.queryTimeoutSecs === null ? "" : String(mcpPolicyDraft.value.queryTimeoutSecs); mcpQueryTimeoutInput.value = reverted; target.value = reverted; mcpQueryTimeoutPendingValue = undefined; - setMcpQueryTimeoutSaveStatus("idle"); return; } mcpQueryTimeoutPendingValue = parsed; @@ -3570,28 +3583,22 @@ function onMcpQueryTimeoutInput(event: Event) { if (mcpQueryTimeoutSaveTimer !== null) clearTimeout(mcpQueryTimeoutSaveTimer); mcpQueryTimeoutSaveTimer = setTimeout(() => { mcpQueryTimeoutSaveTimer = null; - flushMcpQueryTimeoutSave(); + stageMcpQueryTimeoutDraft(); }, MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS); } -function flushMcpQueryTimeoutSave() { +function stageMcpQueryTimeoutDraft() { if (mcpQueryTimeoutSaveTimer !== null) { clearTimeout(mcpQueryTimeoutSaveTimer); mcpQueryTimeoutSaveTimer = null; } if (mcpQueryTimeoutPendingValue === undefined) return; - // Another MCP policy mutation may be in flight. Retain the value until the - // shared mutation gate reopens; saveMcpPolicy's finally block retries it. - if (mcpPolicyControlsDisabled.value) return; const value = mcpQueryTimeoutPendingValue; mcpQueryTimeoutPendingValue = undefined; - void saveMcpPolicy( - { queryTimeoutSecs: value }, - { - onSuccess: () => setMcpQueryTimeoutSaveStatus("saved"), - onFailure: () => setMcpQueryTimeoutSaveStatus("failed"), - }, - ); + mcpPolicyDraft.value = { + ...mcpPolicyDraft.value, + queryTimeoutSecs: value, + }; } const mcpSelectableConnections = computed(() => connectionStore.connections); const mcpGroupRows = computed(() => connectionGroupDestinationRows(connectionStore.sidebarLayout)); @@ -3646,42 +3653,25 @@ const mcpHttpHasUnsavedChanges = computed(() => { const webMcpEndpoint = computed(() => (webMcpHttpStatus.value ? `${window.location.origin}${webMcpHttpStatus.value.endpointPath}` : "")); -async function saveMcpPolicy( - partial: { - readOnly?: boolean; - allowDangerousSql?: boolean; - allowedConnectionIds?: string[] | null; - allowedGroupIds?: string[]; - allowedToolNames?: string[] | null; - connectionPolicies?: { - connectionId: string; - readOnly: boolean; - allowDangerousSql: boolean; - executionModeConfigured: boolean; - executionModePolicyVersion: number | null; - databaseScope: "all" | "selected" | "none"; - allowedDatabases: string[]; - databasePolicies: { databaseName: string; readOnly: boolean; allowDangerousSql: boolean }[]; - allowSalesforceDml: boolean; - }[]; - groupPolicies?: McpGroupPolicy[]; - queryTimeoutSecs?: number | null; - }, - callbacks?: { onSuccess?: () => void; onFailure?: () => void }, -) { - if (mcpPolicyControlsDisabled.value) return; +async function commitMcpPolicyDraft(): Promise { + stageMcpQueryTimeoutDraft(); + if (mcpPolicySaving.value || mcpPoliciesEqual(mcpPolicyDraft.value, mcpPolicyBaseline.value)) return; + const snapshot = normalizeMcpGlobalPolicy(mcpPolicyDraft.value); mcpPolicySaving.value = true; try { - await settingsStore.updateMcpGlobalPolicy(partial); - callbacks?.onSuccess?.(); - } catch (e: any) { - toast(t("settings.mcpPolicySaveFailed", { error: e?.message || String(e) }), 5000); - callbacks?.onFailure?.(); + await settingsStore.updateMcpGlobalPolicy({ + readOnly: snapshot.readOnly, + allowDangerousSql: snapshot.allowDangerousSql, + allowedConnectionIds: snapshot.allowedConnectionIds, + allowedGroupIds: snapshot.allowedGroupIds, + allowedToolNames: snapshot.allowedToolNames, + connectionPolicies: snapshot.connectionPolicies, + groupPolicies: snapshot.groupPolicies, + queryTimeoutSecs: snapshot.queryTimeoutSecs, + }); + if (mcpPoliciesEqual(mcpPolicyDraft.value, snapshot)) syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy); } finally { mcpPolicySaving.value = false; - // A query-timeout edit can have debounced while another policy write held - // the shared gate. Persist it once that write releases the gate. - if (mcpQueryTimeoutPendingValue !== undefined) flushMcpQueryTimeoutSave(); } } @@ -3690,7 +3680,7 @@ function onMcpExecutionModeChange(mode: McpExecutionMode) { if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) { return; } - void saveMcpPolicy(mcpPolicyFieldsForExecutionMode(mode)); + stageMcpPolicy(mcpPolicyFieldsForExecutionMode(mode)); } function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) { @@ -3714,21 +3704,21 @@ function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) } function onMcpResourceScopeChange(scope: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }) { - void saveMcpPolicy(scope); + stageMcpPolicy(scope); } type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write"; const mcpToolOptions = MCP_TOOL_OPTIONS; -const mcpAllowedToolNames = computed(() => settingsStore.mcpGlobalPolicy.allowedToolNames); +const mcpAllowedToolNames = computed(() => mcpPolicyDraft.value.allowedToolNames); function mcpToolAllowed(name: string): boolean { return mcpAllowedToolNames.value === null || mcpAllowedToolNames.value.includes(name); } function onMcpToolAllowedChange(name: string, allowed: boolean) { - void saveMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, allowed) }); + stageMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, allowed) }); } // Entries beyond the static options: discovered plugin tool names and the @@ -3742,11 +3732,11 @@ function onMcpCustomToolAdd() { if (!rawName.trim()) return; const { names, added } = addMcpAllowedToolName(mcpAllowedToolNames.value, rawName); mcpCustomToolInput.value = ""; - if (added) void saveMcpPolicy({ allowedToolNames: names }); + if (added) stageMcpPolicy({ allowedToolNames: names }); } function onMcpCustomToolRemove(name: string) { - void saveMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, false) }); + stageMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, false) }); } const mcpConnectionPolicyConnections = computed(() => { @@ -3754,14 +3744,14 @@ const mcpConnectionPolicyConnections = computed(() => { return allowed === null ? mcpSelectableConnections.value : mcpSelectableConnections.value.filter((connection) => allowed.includes(connection.id)); }); function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutionMode | "inherit" { - const rule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId); + const rule = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId); if (!rule || !rule.executionModeConfigured) return "inherit"; if (rule.readOnly) return "read_only"; return rule.allowDangerousSql ? "high_risk_write" : "safe_write"; } function mcpGroupExecutionMode(groupId: string): McpConnectionExecutionMode | "inherit" { - const rule = settingsStore.mcpGlobalPolicy.groupPolicies.find((item) => item.groupId === groupId); + const rule = mcpPolicyDraft.value.groupPolicies.find((item) => item.groupId === groupId); if (!rule) return "inherit"; if (rule.readOnly) return "read_only"; return rule.allowDangerousSql ? "high_risk_write" : "safe_write"; @@ -3828,7 +3818,7 @@ function mcpPermissionSource(row: { databaseMode: McpConnectionExecutionMode | " const mcpPermissionPreviewSearchQuery = ref(""); const mcpPermissionPreviewRows = computed(() => mcpConnectionPolicyConnections.value.flatMap((connection) => { - const rule = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connection.id); + const rule = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connection.id); const connectionMode = mcpConnectionExecutionMode(connection.id); const groupPolicy = mcpInheritedGroupPolicy(connection.id); const groupMode = groupPolicy.mode; @@ -3858,7 +3848,7 @@ const filteredMcpPermissionPreviewRows = computed(() => { function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecutionMode | "inherit") { if (mode === "high_risk_write" && !window.confirm(t("settings.mcpGroupPolicyHighRiskConfirm"))) return; - const groupPolicies = settingsStore.mcpGlobalPolicy.groupPolicies.filter((item) => item.groupId !== groupId); + const groupPolicies = mcpPolicyDraft.value.groupPolicies.filter((item) => item.groupId !== groupId); if (mode !== "inherit") { groupPolicies.push({ groupId, @@ -3866,7 +3856,7 @@ function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecu allowDangerousSql: mode === "high_risk_write", }); } - void saveMcpPolicy({ groupPolicies }); + stageMcpPolicy({ groupPolicies }); } // A connection rule is only worth persisting when it actually changes something: an @@ -3879,8 +3869,8 @@ function mcpConnectionPolicyIsMeaningful(rule: McpConnectionPolicy): boolean { function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") { if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return; - const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId); - const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId); + const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId); + const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId); const migrated = existing && existing.executionModePolicyVersion !== 1 ? migrateLegacyMcpConnectionPolicy(existing) : null; const selectedMode = migrated && mode === "inherit" @@ -3905,11 +3895,11 @@ function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConne allowSalesforceDml: (existing?.allowSalesforceDml ?? false) && !selectedMode.readOnly, }; if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next); - void saveMcpPolicy({ connectionPolicies: rules }); + stageMcpPolicy({ connectionPolicies: rules }); } function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boolean) { - const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId); + const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId); if (allowed) { // Read-only is a hard ceiling on the server too, so letting the box stay checked // here would only advertise a write path that every prepare call then refuses. @@ -3919,7 +3909,7 @@ function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boole return; } } - const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId); + const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId); const next: McpConnectionPolicy = { connectionId, readOnly: existing?.readOnly ?? false, @@ -3932,12 +3922,12 @@ function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boole allowSalesforceDml: allowed, }; if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next); - void saveMcpPolicy({ connectionPolicies: rules }); + stageMcpPolicy({ connectionPolicies: rules }); } function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit") { if (mode === "high_risk_write" && !window.confirm(t("settings.mcpDatabasePolicyHighRiskConfirm"))) return; - const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId); + const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId); if (!existing || existing.databaseScope !== "selected" || !existing.allowedDatabases.includes(databaseName)) return; const migrated = existing.executionModePolicyVersion === 1 ? null : migrateLegacyMcpConnectionPolicy(existing); const databasePolicies = (migrated?.databasePolicies ?? existing.databasePolicies).filter((policy) => policy.databaseName !== databaseName); @@ -3950,13 +3940,13 @@ function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: st executionModePolicyVersion: 1, databasePolicies, }; - const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId); + const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId); if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next); - void saveMcpPolicy({ connectionPolicies: rules }); + stageMcpPolicy({ connectionPolicies: rules }); } -function onMcpConnectionPoliciesChange(connectionPolicies: typeof settingsStore.mcpGlobalPolicy.connectionPolicies) { - void saveMcpPolicy({ connectionPolicies }); +function onMcpConnectionPoliciesChange(connectionPolicies: typeof mcpPolicyDraft.value.connectionPolicies) { + stageMcpPolicy({ connectionPolicies }); } function mcpHttpList(value: string): string[] { @@ -4846,12 +4836,13 @@ watch( confirmNewPassword.value = ""; try { await settingsStore.initMcpGlobalPolicy(true); - await loadMcpHttpSettings(); if (!settingsStore.mcpGlobalPolicy.configured && localStorage.getItem(MCP_READONLY_STORAGE_KEY) === "true") { await settingsStore.updateMcpGlobalPolicy({ readOnly: true }); } if (settingsStore.mcpGlobalPolicy.configured) localStorage.removeItem(MCP_READONLY_STORAGE_KEY); localStorage.removeItem(MCP_SCOPE_CONNECTION_STORAGE_KEY); + syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy); + await loadMcpHttpSettings(); } catch (e: any) { mcpPolicyLoadError.value = e?.message || String(e); toast( @@ -4893,6 +4884,7 @@ watch( await scrollToInitialSettingsSection(); } else { resetSettingsSearchState(); + syncMcpPolicyBaseline(mcpPolicyBaseline.value); } }, { immediate: true }, @@ -6342,8 +6334,11 @@ watch( ); onUnmounted(() => { - flushMcpQueryTimeoutSave(); - if (mcpQueryTimeoutSavedStatusTimer !== null) clearTimeout(mcpQueryTimeoutSavedStatusTimer); + if (mcpQueryTimeoutSaveTimer !== null) { + clearTimeout(mcpQueryTimeoutSaveTimer); + mcpQueryTimeoutSaveTimer = null; + } + mcpQueryTimeoutPendingValue = undefined; cleanupPreviewEditor(); resetSettingsSearchState(); }); @@ -10682,8 +10677,8 @@ LIMIT 100;{{ t("settings.mcpQueryTimeout") }}
-

- - - - {{ t(`settings.mcpQueryTimeoutSaveStatus_${mcpQueryTimeoutSaveStatus}`) }} -

@@ -11453,6 +11442,12 @@ LIMIT 100; {{ t("settings.mcpGuide") }} + + diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.integration.spec.ts index b5d5674ce4..2e737d2031 100644 --- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.integration.spec.ts +++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.integration.spec.ts @@ -1,11 +1,8 @@ // @vitest-environment happy-dom -// Real-DOM integration for the MCP query-timeout input (#8616). The settings -// dialog reads the fresh value from the native event target in capture phase, -// before Input's passive v-model proxy updates the parent ref. This test mounts the real -// Input component with exactly that wiring and drives it with real DOM events -// to prove the typing -> debounce -> saveMcpPolicy chain persists the fresh -// value (a two-way v-model would make the passive proxy emit asynchronously, -// so the handler would read a stale ref during the same native event). +// Real-DOM integration for the MCP query-timeout input. The settings dialog +// reads the fresh value from the native event target in capture phase, before +// Input's passive v-model proxy updates the parent ref. Typing stages that +// fresh value into the policy draft and does not persist it. import { afterEach, describe, expect, it, vi } from "vitest"; import { createApp, defineComponent, h, nextTick, type App } from "vue"; import Input from "@/components/ui/input/Input.vue"; @@ -44,44 +41,37 @@ describe("EditorSettingsDialog MCP query timeout real-DOM integration", () => { return el as HTMLInputElement; } - function harnessFor(saveMcpPolicy: ReturnType): { harness: McpQueryTimeoutHarness; inputRef: { value: string } } { + function harnessFor(): { harness: McpQueryTimeoutHarness; inputRef: { value: string } } { const inputRef = { value: "" }; const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: inputRef, policyQueryTimeoutSecs: null, - saveMcpPolicy, }); return { harness, inputRef }; } - it("typing into the real Input persists the fresh value after debounce", async () => { + it("typing into the real Input stages the fresh value after debounce", async () => { vi.useFakeTimers(); - const saveMcpPolicy = vi.fn(); - const { harness, inputRef } = harnessFor(saveMcpPolicy); + const { harness, inputRef } = harnessFor(); const el = await mountInput({ modelValue: inputRef, onInput: harness.onMcpQueryTimeoutInput, }); - // Simulate real typing: set the DOM value and dispatch a native input event. el.value = "300"; el.dispatchEvent(new Event("input", { bubbles: true })); - // The debounce has not elapsed yet: no save. - expect(saveMcpPolicy).not.toHaveBeenCalled(); + expect(harness.draft.value.queryTimeoutSecs).toBeNull(); - // Elapse the debounce window and assert the FRESH value was saved. vi.advanceTimersByTime(300); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 300 }); + expect(harness.draft.value.queryTimeoutSecs).toBe(300); }); - it("typing then flushing on close persists the fresh value immediately", async () => { + it("staging before the debounce elapses keeps the fresh value in the draft only", async () => { vi.useFakeTimers(); - const saveMcpPolicy = vi.fn(); - const { harness, inputRef } = harnessFor(saveMcpPolicy); + const { harness, inputRef } = harnessFor(); const el = await mountInput({ modelValue: inputRef, @@ -91,16 +81,13 @@ describe("EditorSettingsDialog MCP query timeout real-DOM integration", () => { el.value = "120"; el.dispatchEvent(new Event("input", { bubbles: true })); - // Close path: flush before the debounce elapses. - harness.flushMcpQueryTimeoutSave(); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 120 }); + harness.stageMcpQueryTimeoutDraft(); + expect(harness.draft.value.queryTimeoutSecs).toBe(120); }); - it("rapid typing in the real DOM coalesces into one save of the last value", async () => { + it("rapid typing in the real DOM coalesces into one draft update of the last value", async () => { vi.useFakeTimers(); - const saveMcpPolicy = vi.fn(); - const { harness, inputRef } = harnessFor(saveMcpPolicy); + const { harness, inputRef } = harnessFor(); const el = await mountInput({ modelValue: inputRef, @@ -117,7 +104,6 @@ describe("EditorSettingsDialog MCP query timeout real-DOM integration", () => { el.dispatchEvent(new Event("input", { bubbles: true })); vi.advanceTimersByTime(300); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 123 }); + expect(harness.draft.value.queryTimeoutSecs).toBe(123); }); }); diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts index 9e18116c4d..72f903f70a 100644 --- a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts +++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.mcpQueryTimeout.spec.ts @@ -1,21 +1,18 @@ import { readFileSync } from "node:fs"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { createMcpQueryTimeoutHarness } from "./mcpQueryTimeoutHarness"; +import { createMcpQueryTimeoutHarness, extractMcpQueryTimeoutDebounceBlock } from "./mcpQueryTimeoutHarness"; const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8"); -// 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 -// drives it with fake timers + mocked deps to assert actual save behaviour. +// The debounce block stages a query timeout into the policy draft. It must not +// persist: explicit save is the only write, and close/discard drops the draft. function nativeInputEvent(value: string, badInput = false): Event { return { currentTarget: { value, validity: { badInput } } } as unknown as Event; } -function expectQueryTimeoutSave(saveMcpPolicy: ReturnType, queryTimeoutSecs: number | null) { - expect(saveMcpPolicy).toHaveBeenCalled(); - expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs }); +function expectStagedTimeout(harness: ReturnType, queryTimeoutSecs: number | null) { + expect(harness.draft.value.queryTimeoutSecs).toBe(queryTimeoutSecs); } describe("EditorSettingsDialog MCP query timeout debounce runtime", () => { @@ -27,117 +24,105 @@ describe("EditorSettingsDialog MCP query timeout debounce runtime", () => { vi.useRealTimers(); }); - it("saves a typed value once the debounce window elapses", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); + it("stages a typed value into the draft once the debounce window elapses, without persisting", () => { + const block = extractMcpQueryTimeoutDebounceBlock(dialogSource); + expect(block).not.toContain("saveMcpPolicy"); + expect(block).not.toContain("updateMcpGlobalPolicy"); + + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null }); harness.onMcpQueryTimeoutInput(nativeInputEvent("300")); - expect(saveMcpPolicy).not.toHaveBeenCalled(); + expect(harness.draft.value.queryTimeoutSecs).toBeNull(); vi.advanceTimersByTime(299); - expect(saveMcpPolicy).not.toHaveBeenCalled(); + expect(harness.draft.value.queryTimeoutSecs).toBeNull(); vi.advanceTimersByTime(1); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expectQueryTimeoutSave(saveMcpPolicy, 300); + expectStagedTimeout(harness, 300); }); - it("reports saving immediately and saved after the persistence callback", () => { - const setSaveStatus = vi.fn(); - const saveMcpPolicy = vi.fn((_partial, callbacks?: { onSuccess?: () => void }) => callbacks?.onSuccess?.()); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy, setSaveStatus }); - harness.onMcpQueryTimeoutInput(nativeInputEvent("300")); - expect(setSaveStatus).toHaveBeenLastCalledWith("saving"); - harness.flushMcpQueryTimeoutSave(); - expect(setSaveStatus).toHaveBeenLastCalledWith("saved"); - }); - - it("coalesces rapid typing into a single save", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); + it("coalesces rapid typing into a single draft update", () => { + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null }); harness.onMcpQueryTimeoutInput(nativeInputEvent("1")); vi.advanceTimersByTime(100); harness.onMcpQueryTimeoutInput(nativeInputEvent("12")); vi.advanceTimersByTime(100); harness.onMcpQueryTimeoutInput(nativeInputEvent("123")); vi.advanceTimersByTime(300); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expectQueryTimeoutSave(saveMcpPolicy, 123); + expectStagedTimeout(harness, 123); }); - it("flush persists a pending value before the debounce elapses", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); + it("stages a pending value before the debounce elapses", () => { + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null }); harness.onMcpQueryTimeoutInput(nativeInputEvent("120")); - harness.flushMcpQueryTimeoutSave(); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - expectQueryTimeoutSave(saveMcpPolicy, 120); - // Flushing again with nothing pending is a no-op. - harness.flushMcpQueryTimeoutSave(); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); + harness.stageMcpQueryTimeoutDraft(); + expectStagedTimeout(harness, 120); + harness.stageMcpQueryTimeoutDraft(); + expectStagedTimeout(harness, 120); }); - it("flush after the timer fired does not double-save", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); + it("staging after the timer fired does not change the draft again", () => { + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null }); harness.onMcpQueryTimeoutInput(nativeInputEvent("60")); vi.advanceTimersByTime(300); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); - harness.flushMcpQueryTimeoutSave(); - expect(saveMcpPolicy).toHaveBeenCalledTimes(1); + expectStagedTimeout(harness, 60); + harness.draft.value.queryTimeoutSecs = 1; + harness.stageMcpQueryTimeoutDraft(); + expect(harness.draft.value.queryTimeoutSecs).toBe(1); }); - it("retains a pending value while another MCP policy mutation holds the gate", () => { - const saveMcpPolicy = vi.fn(); - const policyMutationBlocked = { value: true }; - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy, policyMutationBlocked }); - harness.onMcpQueryTimeoutInput(nativeInputEvent("60")); - vi.advanceTimersByTime(300); - expect(saveMcpPolicy).not.toHaveBeenCalled(); - - policyMutationBlocked.value = false; - harness.flushMcpQueryTimeoutSave(); - expectQueryTimeoutSave(saveMcpPolicy, 60); - }); - - it("empty input schedules null (inherit the connection)", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 300, saveMcpPolicy }); + it("empty input stages null (inherit the connection)", () => { + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 300 }); harness.onMcpQueryTimeoutInput(nativeInputEvent("")); - harness.flushMcpQueryTimeoutSave(); - expectQueryTimeoutSave(saveMcpPolicy, null); + harness.stageMcpQueryTimeoutDraft(); + expectStagedTimeout(harness, null); }); - it("zero input persists 0 (no limit)", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); + it("zero input stages 0 (no limit)", () => { + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null }); harness.onMcpQueryTimeoutInput(nativeInputEvent("0")); - harness.flushMcpQueryTimeoutSave(); - expectQueryTimeoutSave(saveMcpPolicy, 0); + harness.stageMcpQueryTimeoutDraft(); + expectStagedTimeout(harness, 0); }); - it("invalid input cancels the pending save and reverts the field", () => { - const saveMcpPolicy = vi.fn(); + it("invalid input cancels the pending stage and reverts the field", () => { const toast = vi.fn(); const input = { value: "1.5" }; - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input, policyQueryTimeoutSecs: null, saveMcpPolicy, toast }); + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input, policyQueryTimeoutSecs: null, toast }); const event = nativeInputEvent("1.5"); harness.onMcpQueryTimeoutInput(event); - // Invalid input must not schedule anything. vi.advanceTimersByTime(300); - expect(saveMcpPolicy).not.toHaveBeenCalled(); + expect(harness.draft.value.queryTimeoutSecs).toBeNull(); expect(toast).toHaveBeenCalledTimes(1); - // The bound ref is reverted to the persisted value ("" == inherit). expect(input.value).toBe(""); - // The native input is reverted too (one-way binding needs the DOM write). expect((event.currentTarget as { value: string }).value).toBe(""); }); it("does not treat a bad number-input intermediate state as inherit", () => { - const saveMcpPolicy = vi.fn(); - const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 90, saveMcpPolicy }); + const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 90 }); harness.onMcpQueryTimeoutInput(nativeInputEvent("45")); vi.advanceTimersByTime(100); harness.onMcpQueryTimeoutInput(nativeInputEvent("", true)); vi.advanceTimersByTime(200); - expectQueryTimeoutSave(saveMcpPolicy, 45); - expect(saveMcpPolicy.mock.calls.some(([partial]) => partial.queryTimeoutSecs === null)).toBe(false); + expectStagedTimeout(harness, 45); + }); + + it("close confirmation stages the draft and does not persist, and unmount does not write", () => { + const closeStart = dialogSource.indexOf("function requestCloseSettings"); + const closeEnd = dialogSource.indexOf("function onSettingsRootOpenChange"); + const closeFn = dialogSource.slice(closeStart, closeEnd); + expect(closeFn).toContain("stageMcpQueryTimeoutDraft()"); + expect(closeFn).not.toContain("updateMcpGlobalPolicy"); + expect(closeFn).not.toContain("saveMcpGlobalPolicy"); + + const discardStart = dialogSource.indexOf("function discardUnsavedSettingsAndClose"); + const discardFn = dialogSource.slice(discardStart, dialogSource.indexOf("interface TableColumnTemplateOverrideRow")); + expect(discardFn).not.toContain("updateMcpGlobalPolicy"); + expect(discardFn).not.toContain("commitMcpPolicyDraft"); + expect(discardFn).not.toContain("stageMcpQueryTimeoutDraft"); + + const unmountStart = dialogSource.lastIndexOf("onUnmounted(() => {"); + const unmountEnd = dialogSource.indexOf("});", unmountStart); + const unmountFn = dialogSource.slice(unmountStart, unmountEnd); + expect(unmountFn).not.toContain("stageMcpQueryTimeoutDraft"); + expect(unmountFn).not.toContain("updateMcpGlobalPolicy"); + expect(unmountFn).not.toContain("commitMcpPolicyDraft"); }); }); diff --git a/apps/desktop/src/components/editor/__tests__/mcpQueryTimeoutHarness.ts b/apps/desktop/src/components/editor/__tests__/mcpQueryTimeoutHarness.ts index 3a50f01a87..8995f3e6cd 100644 --- a/apps/desktop/src/components/editor/__tests__/mcpQueryTimeoutHarness.ts +++ b/apps/desktop/src/components/editor/__tests__/mcpQueryTimeoutHarness.ts @@ -6,7 +6,8 @@ import ts from "typescript"; export interface McpQueryTimeoutHarness { onMcpQueryTimeoutInput: (event: Event) => void; - flushMcpQueryTimeoutSave: () => void; + stageMcpQueryTimeoutDraft: () => void; + draft: { value: { queryTimeoutSecs: number | null } }; } export function extractMcpQueryTimeoutDebounceBlock(source: string): string { @@ -16,28 +17,13 @@ export function extractMcpQueryTimeoutDebounceBlock(source: string): string { return source.slice(start, end); } -export function createMcpQueryTimeoutHarness(options: { - source: string; - input: { value: string }; - policyQueryTimeoutSecs: number | null; - saveMcpPolicy: (partial: { queryTimeoutSecs: number | null }, callbacks?: { onSuccess?: () => void; onFailure?: () => void }) => void; - policyMutationBlocked?: { value: boolean }; - setSaveStatus?: (status: "idle" | "saving" | "saved" | "failed") => void; - toast?: (message: string, duration: number) => void; - t?: (key: string) => string; -}): McpQueryTimeoutHarness { +export function createMcpQueryTimeoutHarness(options: { source: string; input: { value: string }; policyQueryTimeoutSecs: number | null; toast?: (message: string, duration: number) => void; t?: (key: string) => string }): McpQueryTimeoutHarness { const block = extractMcpQueryTimeoutDebounceBlock(options.source); const javascript = ts.transpileModule(block, { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 }, }).outputText; - const factory = new Function("mcpQueryTimeoutInput", "settingsStore", "saveMcpPolicy", "toast", "t", "mcpPolicyControlsDisabled", "setMcpQueryTimeoutSaveStatus", `${javascript}\nreturn { onMcpQueryTimeoutInput, flushMcpQueryTimeoutSave };`); - return factory( - options.input, - { mcpGlobalPolicy: { queryTimeoutSecs: options.policyQueryTimeoutSecs } }, - options.saveMcpPolicy, - options.toast ?? (() => {}), - options.t ?? ((key: string) => key), - options.policyMutationBlocked ?? { value: false }, - options.setSaveStatus ?? (() => {}), - ) as McpQueryTimeoutHarness; + const draft = { value: { queryTimeoutSecs: options.policyQueryTimeoutSecs } }; + const factory = new Function("mcpQueryTimeoutInput", "mcpPolicyDraft", "toast", "t", `${javascript}\nreturn { onMcpQueryTimeoutInput, stageMcpQueryTimeoutDraft };`); + const harness = factory(options.input, draft, options.toast ?? (() => {}), options.t ?? ((key: string) => key)) as Omit; + return { ...harness, draft }; } diff --git a/apps/desktop/src/components/settings/McpAuthorizationStepper.vue b/apps/desktop/src/components/settings/McpAuthorizationStepper.vue index 855fcbecdb..1b9f2d23c2 100644 --- a/apps/desktop/src/components/settings/McpAuthorizationStepper.vue +++ b/apps/desktop/src/components/settings/McpAuthorizationStepper.vue @@ -15,8 +15,9 @@ const steps = computed const currentStep = ref("overrides"); const currentIndex = computed(() => steps.value.findIndex((step) => step.id === currentStep.value)); -// Every step is directly reachable from the nav above and all policy edits save as they are made, -// so the last step has nothing to advance to and nothing to confirm. +// Every step is directly reachable from the nav above and all policy edits stage into the +// dialog draft, so the last step has nothing to advance to and nothing to confirm here — +// persistence is the settings footer Apply button's job, not this stepper's. const isLastStep = computed(() => currentIndex.value === steps.value.length - 1); function scrollableAncestor(target: EventTarget | null): HTMLElement | null {