fix(mcp): persist the access policy only on explicit apply

This commit is contained in:
onenewcode authored and GitHub committed 2026-09-30 15:34:23 +08:00
1 parent dc02e3bccf
commit 20ffc62249
5 files changed
+198 -245

No files matched your search

@@ -106,7 +106,8 @@ import {
type CustomThemeColors, type CustomThemeColors,
type CustomTheme, type CustomTheme,
type McpConnectionPolicy, type McpConnectionPolicy,
type McpGroupPolicy, type McpGlobalPolicy,
normalizeMcpGlobalPolicy,
type ClickTableNavigationTarget, type ClickTableNavigationTarget,
type EditorSettings, type EditorSettings,
type SqlCompletionTriggerMode, type SqlCompletionTriggerMode,
@@ -549,9 +550,9 @@ const settingsTitleComponent = computed(() => (isSettingsPage.value ? "h2" : Dia
const showUnsavedSettingsCloseConfirm = ref(false); const showUnsavedSettingsCloseConfirm = ref(false);
function requestCloseSettings(nextOpen: boolean) { function requestCloseSettings(nextOpen: boolean) {
// Flush any pending debounced MCP query-timeout save so a value typed right // Fold a timeout typed immediately before close into the draft so the unsaved
// before closing is persisted instead of dropped (see onMcpQueryTimeoutInput). // prompt can see it. This must not persist: discard drops the draft.
flushMcpQueryTimeoutSave(); stageMcpQueryTimeoutDraft();
if (shouldConfirmEditorSettingsDialogClose(nextOpen, hasChanges())) { if (shouldConfirmEditorSettingsDialogClose(nextOpen, hasChanges())) {
showUnsavedSettingsCloseConfirm.value = true; showUnsavedSettingsCloseConfirm.value = true;
return; return;
@@ -574,6 +575,7 @@ function cancelUnsavedSettingsClose() {
function discardUnsavedSettingsAndClose() { function discardUnsavedSettingsAndClose() {
showUnsavedSettingsCloseConfirm.value = false; showUnsavedSettingsCloseConfirm.value = false;
syncMcpPolicyBaseline(mcpPolicyBaseline.value);
emit("update:open", false); emit("update:open", false);
} }
@@ -2241,7 +2243,8 @@ function hasChanges(): boolean {
editMetadataCacheMaxMemoryMb.value !== settingsStore.desktopSettings.metadata_cache_max_memory_mb || editMetadataCacheMaxMemoryMb.value !== settingsStore.desktopSettings.metadata_cache_max_memory_mb ||
editDuckDbWorkerProcessIsolation.value !== settingsStore.desktopSettings.duckdb_worker_process_isolation || editDuckDbWorkerProcessIsolation.value !== settingsStore.desktopSettings.duckdb_worker_process_isolation ||
normalizeDuckDbWorkerMaxProcesses(editDuckDbWorkerMaxProcesses.value) !== settingsStore.desktopSettings.duckdb_worker_max_processes || 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) { } else if (sidebarTablePageSizeChanged) {
await connectionStore.refreshSidebarObjectPagination(); await connectionStore.refreshSidebarObjectPagination();
} }
await commitMcpPolicyDraft();
} }
function applySettingsErrorToast(error: unknown) { function applySettingsErrorToast(error: unknown) {
@@ -3500,41 +3504,52 @@ const mcpInstalling = ref(false);
const mcpUninstalling = ref(false); const mcpUninstalling = ref(false);
const mcpInstallMessage = ref(""); const mcpInstallMessage = ref("");
const mcpInstallError = ref(false); const mcpInstallError = ref(false);
const mcpExecutionMode = computed(() => mcpExecutionModeFromPolicy(settingsStore.mcpGlobalPolicy)); const mcpPolicyDraft = ref<McpGlobalPolicy>(normalizeMcpGlobalPolicy(settingsStore.mcpGlobalPolicy));
const mcpPolicyBaseline = ref<McpGlobalPolicy>(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<Omit<McpGlobalPolicy, "configured">>) {
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 mcpExecutionModeOptions: McpExecutionMode[] = ["read_only", "safe_write", "high_risk_write"];
const mcpAllowedConnectionIds = computed(() => settingsStore.mcpGlobalPolicy.allowedConnectionIds); const mcpAllowedConnectionIds = computed(() => mcpPolicyDraft.value.allowedConnectionIds);
const mcpAllowedGroupIds = computed(() => settingsStore.mcpGlobalPolicy.allowedGroupIds); const mcpAllowedGroupIds = computed(() => mcpPolicyDraft.value.allowedGroupIds);
const mcpQueryTimeoutInput = ref<string>(settingsStore.mcpGlobalPolicy.queryTimeoutSecs === null ? "" : String(settingsStore.mcpGlobalPolicy.queryTimeoutSecs)); const mcpQueryTimeoutInput = ref<string>(mcpPolicyDraft.value.queryTimeoutSecs === null ? "" : String(mcpPolicyDraft.value.queryTimeoutSecs));
watch( watch(
() => settingsStore.mcpGlobalPolicy.queryTimeoutSecs, () => mcpPolicyDraft.value.queryTimeoutSecs,
(value) => { (value) => {
if (mcpQueryTimeoutPendingValue !== undefined) return;
mcpQueryTimeoutInput.value = value === null ? "" : String(value); mcpQueryTimeoutInput.value = value === null ? "" : String(value);
}, },
); );
type McpQueryTimeoutSaveStatus = "idle" | "saving" | "saved" | "failed"; // Debounce typing into the policy draft. Persistence happens only on an explicit
const mcpQueryTimeoutSaveStatus = ref<McpQueryTimeoutSaveStatus>("idle"); // save; closing and discarding must not write this value.
let mcpQueryTimeoutSavedStatusTimer: ReturnType<typeof setTimeout> | 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).
const MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS = 300; const MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS = 300;
let mcpQueryTimeoutSaveTimer: ReturnType<typeof setTimeout> | null = null; let mcpQueryTimeoutSaveTimer: ReturnType<typeof setTimeout> | null = null;
let mcpQueryTimeoutPendingValue: number | null | undefined; 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. // mistake that browser state for an explicit request to inherit the timeout.
if (target.validity.badInput) return; if (target.validity.badInput) return;
const raw = target.value.trim(); const raw = target.value.trim();
setMcpQueryTimeoutSaveStatus("saving");
if (raw === "") { if (raw === "") {
mcpQueryTimeoutPendingValue = null; mcpQueryTimeoutPendingValue = null;
} else { } else {
@@ -3558,11 +3572,10 @@ function onMcpQueryTimeoutInput(event: Event) {
toast(t("settings.mcpQueryTimeoutInvalid"), 5000); toast(t("settings.mcpQueryTimeoutInvalid"), 5000);
// Revert before Input's bubble-phase v-model handler sees the value, so // Revert before Input's bubble-phase v-model handler sees the value, so
// the proxy and parent ref remain aligned. // 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; mcpQueryTimeoutInput.value = reverted;
target.value = reverted; target.value = reverted;
mcpQueryTimeoutPendingValue = undefined; mcpQueryTimeoutPendingValue = undefined;
setMcpQueryTimeoutSaveStatus("idle");
return; return;
} }
mcpQueryTimeoutPendingValue = parsed; mcpQueryTimeoutPendingValue = parsed;
@@ -3570,28 +3583,22 @@ function onMcpQueryTimeoutInput(event: Event) {
if (mcpQueryTimeoutSaveTimer !== null) clearTimeout(mcpQueryTimeoutSaveTimer); if (mcpQueryTimeoutSaveTimer !== null) clearTimeout(mcpQueryTimeoutSaveTimer);
mcpQueryTimeoutSaveTimer = setTimeout(() => { mcpQueryTimeoutSaveTimer = setTimeout(() => {
mcpQueryTimeoutSaveTimer = null; mcpQueryTimeoutSaveTimer = null;
flushMcpQueryTimeoutSave(); stageMcpQueryTimeoutDraft();
}, MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS); }, MCP_QUERY_TIMEOUT_SAVE_DEBOUNCE_MS);
} }
function flushMcpQueryTimeoutSave() { function stageMcpQueryTimeoutDraft() {
if (mcpQueryTimeoutSaveTimer !== null) { if (mcpQueryTimeoutSaveTimer !== null) {
clearTimeout(mcpQueryTimeoutSaveTimer); clearTimeout(mcpQueryTimeoutSaveTimer);
mcpQueryTimeoutSaveTimer = null; mcpQueryTimeoutSaveTimer = null;
} }
if (mcpQueryTimeoutPendingValue === undefined) return; 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; const value = mcpQueryTimeoutPendingValue;
mcpQueryTimeoutPendingValue = undefined; mcpQueryTimeoutPendingValue = undefined;
void saveMcpPolicy( mcpPolicyDraft.value = {
{ queryTimeoutSecs: value }, ...mcpPolicyDraft.value,
{ queryTimeoutSecs: value,
onSuccess: () => setMcpQueryTimeoutSaveStatus("saved"), };
onFailure: () => setMcpQueryTimeoutSaveStatus("failed"),
},
);
} }
const mcpSelectableConnections = computed(() => connectionStore.connections); const mcpSelectableConnections = computed(() => connectionStore.connections);
const mcpGroupRows = computed(() => connectionGroupDestinationRows(connectionStore.sidebarLayout)); const mcpGroupRows = computed(() => connectionGroupDestinationRows(connectionStore.sidebarLayout));
@@ -3646,42 +3653,25 @@ const mcpHttpHasUnsavedChanges = computed(() => {
const webMcpEndpoint = computed(() => (webMcpHttpStatus.value ? `${window.location.origin}${webMcpHttpStatus.value.endpointPath}` : "")); const webMcpEndpoint = computed(() => (webMcpHttpStatus.value ? `${window.location.origin}${webMcpHttpStatus.value.endpointPath}` : ""));
async function saveMcpPolicy( async function commitMcpPolicyDraft(): Promise<void> {
partial: { stageMcpQueryTimeoutDraft();
readOnly?: boolean; if (mcpPolicySaving.value || mcpPoliciesEqual(mcpPolicyDraft.value, mcpPolicyBaseline.value)) return;
allowDangerousSql?: boolean; const snapshot = normalizeMcpGlobalPolicy(mcpPolicyDraft.value);
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;
mcpPolicySaving.value = true; mcpPolicySaving.value = true;
try { try {
await settingsStore.updateMcpGlobalPolicy(partial); await settingsStore.updateMcpGlobalPolicy({
callbacks?.onSuccess?.(); readOnly: snapshot.readOnly,
} catch (e: any) { allowDangerousSql: snapshot.allowDangerousSql,
toast(t("settings.mcpPolicySaveFailed", { error: e?.message || String(e) }), 5000); allowedConnectionIds: snapshot.allowedConnectionIds,
callbacks?.onFailure?.(); allowedGroupIds: snapshot.allowedGroupIds,
allowedToolNames: snapshot.allowedToolNames,
connectionPolicies: snapshot.connectionPolicies,
groupPolicies: snapshot.groupPolicies,
queryTimeoutSecs: snapshot.queryTimeoutSecs,
});
if (mcpPoliciesEqual(mcpPolicyDraft.value, snapshot)) syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy);
} finally { } finally {
mcpPolicySaving.value = false; 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"))) { if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) {
return; return;
} }
void saveMcpPolicy(mcpPolicyFieldsForExecutionMode(mode)); stageMcpPolicy(mcpPolicyFieldsForExecutionMode(mode));
} }
function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) { function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode) {
@@ -3714,21 +3704,21 @@ function onMcpExecutionModeKeydown(event: KeyboardEvent, mode: McpExecutionMode)
} }
function onMcpResourceScopeChange(scope: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }) { function onMcpResourceScopeChange(scope: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }) {
void saveMcpPolicy(scope); stageMcpPolicy(scope);
} }
type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write"; type McpConnectionExecutionMode = "read_only" | "safe_write" | "high_risk_write";
const mcpToolOptions = MCP_TOOL_OPTIONS; const mcpToolOptions = MCP_TOOL_OPTIONS;
const mcpAllowedToolNames = computed(() => settingsStore.mcpGlobalPolicy.allowedToolNames); const mcpAllowedToolNames = computed(() => mcpPolicyDraft.value.allowedToolNames);
function mcpToolAllowed(name: string): boolean { function mcpToolAllowed(name: string): boolean {
return mcpAllowedToolNames.value === null || mcpAllowedToolNames.value.includes(name); return mcpAllowedToolNames.value === null || mcpAllowedToolNames.value.includes(name);
} }
function onMcpToolAllowedChange(name: string, allowed: boolean) { 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 // Entries beyond the static options: discovered plugin tool names and the
@@ -3742,11 +3732,11 @@ function onMcpCustomToolAdd() {
if (!rawName.trim()) return; if (!rawName.trim()) return;
const { names, added } = addMcpAllowedToolName(mcpAllowedToolNames.value, rawName); const { names, added } = addMcpAllowedToolName(mcpAllowedToolNames.value, rawName);
mcpCustomToolInput.value = ""; mcpCustomToolInput.value = "";
if (added) void saveMcpPolicy({ allowedToolNames: names }); if (added) stageMcpPolicy({ allowedToolNames: names });
} }
function onMcpCustomToolRemove(name: string) { function onMcpCustomToolRemove(name: string) {
void saveMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, false) }); stageMcpPolicy({ allowedToolNames: toggleMcpAllowedToolName(mcpAllowedToolNames.value, name, false) });
} }
const mcpConnectionPolicyConnections = computed(() => { const mcpConnectionPolicyConnections = computed(() => {
@@ -3754,14 +3744,14 @@ const mcpConnectionPolicyConnections = computed(() => {
return allowed === null ? mcpSelectableConnections.value : mcpSelectableConnections.value.filter((connection) => allowed.includes(connection.id)); return allowed === null ? mcpSelectableConnections.value : mcpSelectableConnections.value.filter((connection) => allowed.includes(connection.id));
}); });
function mcpConnectionExecutionMode(connectionId: string): McpConnectionExecutionMode | "inherit" { 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 || !rule.executionModeConfigured) return "inherit";
if (rule.readOnly) return "read_only"; if (rule.readOnly) return "read_only";
return rule.allowDangerousSql ? "high_risk_write" : "safe_write"; return rule.allowDangerousSql ? "high_risk_write" : "safe_write";
} }
function mcpGroupExecutionMode(groupId: string): McpConnectionExecutionMode | "inherit" { 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) return "inherit";
if (rule.readOnly) return "read_only"; if (rule.readOnly) return "read_only";
return rule.allowDangerousSql ? "high_risk_write" : "safe_write"; return rule.allowDangerousSql ? "high_risk_write" : "safe_write";
@@ -3828,7 +3818,7 @@ function mcpPermissionSource(row: { databaseMode: McpConnectionExecutionMode | "
const mcpPermissionPreviewSearchQuery = ref(""); const mcpPermissionPreviewSearchQuery = ref("");
const mcpPermissionPreviewRows = computed(() => const mcpPermissionPreviewRows = computed(() =>
mcpConnectionPolicyConnections.value.flatMap((connection) => { 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 connectionMode = mcpConnectionExecutionMode(connection.id);
const groupPolicy = mcpInheritedGroupPolicy(connection.id); const groupPolicy = mcpInheritedGroupPolicy(connection.id);
const groupMode = groupPolicy.mode; const groupMode = groupPolicy.mode;
@@ -3858,7 +3848,7 @@ const filteredMcpPermissionPreviewRows = computed(() => {
function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecutionMode | "inherit") { function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecutionMode | "inherit") {
if (mode === "high_risk_write" && !window.confirm(t("settings.mcpGroupPolicyHighRiskConfirm"))) return; 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") { if (mode !== "inherit") {
groupPolicies.push({ groupPolicies.push({
groupId, groupId,
@@ -3866,7 +3856,7 @@ function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecu
allowDangerousSql: mode === "high_risk_write", allowDangerousSql: mode === "high_risk_write",
}); });
} }
void saveMcpPolicy({ groupPolicies }); stageMcpPolicy({ groupPolicies });
} }
// A connection rule is only worth persisting when it actually changes something: an // 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") { function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") {
if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return; if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return;
const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId); const existing = mcpPolicyDraft.value.connectionPolicies.find((item) => item.connectionId === connectionId);
const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId); const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId);
const migrated = existing && existing.executionModePolicyVersion !== 1 ? migrateLegacyMcpConnectionPolicy(existing) : null; const migrated = existing && existing.executionModePolicyVersion !== 1 ? migrateLegacyMcpConnectionPolicy(existing) : null;
const selectedMode = const selectedMode =
migrated && mode === "inherit" migrated && mode === "inherit"
@@ -3905,11 +3895,11 @@ function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConne
allowSalesforceDml: (existing?.allowSalesforceDml ?? false) && !selectedMode.readOnly, allowSalesforceDml: (existing?.allowSalesforceDml ?? false) && !selectedMode.readOnly,
}; };
if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next); if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules }); stageMcpPolicy({ connectionPolicies: rules });
} }
function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boolean) { 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) { if (allowed) {
// Read-only is a hard ceiling on the server too, so letting the box stay checked // 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. // here would only advertise a write path that every prepare call then refuses.
@@ -3919,7 +3909,7 @@ function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boole
return; return;
} }
} }
const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId); const rules = mcpPolicyDraft.value.connectionPolicies.filter((item) => item.connectionId !== connectionId);
const next: McpConnectionPolicy = { const next: McpConnectionPolicy = {
connectionId, connectionId,
readOnly: existing?.readOnly ?? false, readOnly: existing?.readOnly ?? false,
@@ -3932,12 +3922,12 @@ function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boole
allowSalesforceDml: allowed, allowSalesforceDml: allowed,
}; };
if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next); if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules }); stageMcpPolicy({ connectionPolicies: rules });
} }
function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit") { function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: string, mode: McpConnectionExecutionMode | "inherit") {
if (mode === "high_risk_write" && !window.confirm(t("settings.mcpDatabasePolicyHighRiskConfirm"))) return; 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; if (!existing || existing.databaseScope !== "selected" || !existing.allowedDatabases.includes(databaseName)) return;
const migrated = existing.executionModePolicyVersion === 1 ? null : migrateLegacyMcpConnectionPolicy(existing); const migrated = existing.executionModePolicyVersion === 1 ? null : migrateLegacyMcpConnectionPolicy(existing);
const databasePolicies = (migrated?.databasePolicies ?? existing.databasePolicies).filter((policy) => policy.databaseName !== databaseName); const databasePolicies = (migrated?.databasePolicies ?? existing.databasePolicies).filter((policy) => policy.databaseName !== databaseName);
@@ -3950,13 +3940,13 @@ function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: st
executionModePolicyVersion: 1, executionModePolicyVersion: 1,
databasePolicies, 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); if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules }); stageMcpPolicy({ connectionPolicies: rules });
} }
function onMcpConnectionPoliciesChange(connectionPolicies: typeof settingsStore.mcpGlobalPolicy.connectionPolicies) { function onMcpConnectionPoliciesChange(connectionPolicies: typeof mcpPolicyDraft.value.connectionPolicies) {
void saveMcpPolicy({ connectionPolicies }); stageMcpPolicy({ connectionPolicies });
} }
function mcpHttpList(value: string): string[] { function mcpHttpList(value: string): string[] {
@@ -4846,12 +4836,13 @@ watch(
confirmNewPassword.value = ""; confirmNewPassword.value = "";
try { try {
await settingsStore.initMcpGlobalPolicy(true); await settingsStore.initMcpGlobalPolicy(true);
await loadMcpHttpSettings();
if (!settingsStore.mcpGlobalPolicy.configured && localStorage.getItem(MCP_READONLY_STORAGE_KEY) === "true") { if (!settingsStore.mcpGlobalPolicy.configured && localStorage.getItem(MCP_READONLY_STORAGE_KEY) === "true") {
await settingsStore.updateMcpGlobalPolicy({ readOnly: true }); await settingsStore.updateMcpGlobalPolicy({ readOnly: true });
} }
if (settingsStore.mcpGlobalPolicy.configured) localStorage.removeItem(MCP_READONLY_STORAGE_KEY); if (settingsStore.mcpGlobalPolicy.configured) localStorage.removeItem(MCP_READONLY_STORAGE_KEY);
localStorage.removeItem(MCP_SCOPE_CONNECTION_STORAGE_KEY); localStorage.removeItem(MCP_SCOPE_CONNECTION_STORAGE_KEY);
syncMcpPolicyBaseline(settingsStore.mcpGlobalPolicy);
await loadMcpHttpSettings();
} catch (e: any) { } catch (e: any) {
mcpPolicyLoadError.value = e?.message || String(e); mcpPolicyLoadError.value = e?.message || String(e);
toast( toast(
@@ -4893,6 +4884,7 @@ watch(
await scrollToInitialSettingsSection(); await scrollToInitialSettingsSection();
} else { } else {
resetSettingsSearchState(); resetSettingsSearchState();
syncMcpPolicyBaseline(mcpPolicyBaseline.value);
} }
}, },
{ immediate: true }, { immediate: true },
@@ -6342,8 +6334,11 @@ watch(
); );
onUnmounted(() => { onUnmounted(() => {
flushMcpQueryTimeoutSave(); if (mcpQueryTimeoutSaveTimer !== null) {
if (mcpQueryTimeoutSavedStatusTimer !== null) clearTimeout(mcpQueryTimeoutSavedStatusTimer); clearTimeout(mcpQueryTimeoutSaveTimer);
mcpQueryTimeoutSaveTimer = null;
}
mcpQueryTimeoutPendingValue = undefined;
cleanupPreviewEditor(); cleanupPreviewEditor();
resetSettingsSearchState(); resetSettingsSearchState();
}); });
@@ -10682,8 +10677,8 @@ LIMIT 100;</pre
:connections="mcpSelectableConnections" :connections="mcpSelectableConnections"
:allowed-group-ids="mcpAllowedGroupIds" :allowed-group-ids="mcpAllowedGroupIds"
:allowed-connection-ids="mcpAllowedConnectionIds" :allowed-connection-ids="mcpAllowedConnectionIds"
:group-policies="settingsStore.mcpGlobalPolicy.groupPolicies" :group-policies="mcpPolicyDraft.groupPolicies"
:connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies" :connection-policies="mcpPolicyDraft.connectionPolicies"
:disabled="mcpPolicyControlsDisabled" :disabled="mcpPolicyControlsDisabled"
:busy="mcpPolicyLoading || mcpPolicySaving" :busy="mcpPolicyLoading || mcpPolicySaving"
@update:scope="onMcpResourceScopeChange" @update:scope="onMcpResourceScopeChange"
@@ -10697,7 +10692,7 @@ LIMIT 100;</pre
<McpDatabaseScopePicker <McpDatabaseScopePicker
:connections="mcpSelectableConnections" :connections="mcpSelectableConnections"
:allowed-connection-ids="mcpEffectiveAllowedConnectionIds" :allowed-connection-ids="mcpEffectiveAllowedConnectionIds"
:connection-policies="settingsStore.mcpGlobalPolicy.connectionPolicies" :connection-policies="mcpPolicyDraft.connectionPolicies"
:disabled="mcpPolicyControlsDisabled" :disabled="mcpPolicyControlsDisabled"
:busy="mcpPolicyLoading || mcpPolicySaving" :busy="mcpPolicyLoading || mcpPolicySaving"
@update:connection-policies="onMcpConnectionPoliciesChange" @update:connection-policies="onMcpConnectionPoliciesChange"
@@ -10843,12 +10838,6 @@ LIMIT 100;</pre
<Label id="mcp-query-timeout-label">{{ t("settings.mcpQueryTimeout") }}</Label> <Label id="mcp-query-timeout-label">{{ t("settings.mcpQueryTimeout") }}</Label>
<div class="space-y-1"> <div class="space-y-1">
<Input id="mcp-query-timeout" v-model="mcpQueryTimeoutInput" type="number" min="0" step="1" inputmode="numeric" placeholder="0" :disabled="mcpPolicyControlsDisabled" @input.capture="onMcpQueryTimeoutInput" /> <Input id="mcp-query-timeout" v-model="mcpQueryTimeoutInput" type="number" min="0" step="1" inputmode="numeric" placeholder="0" :disabled="mcpPolicyControlsDisabled" @input.capture="onMcpQueryTimeoutInput" />
<p v-if="mcpQueryTimeoutSaveStatus !== 'idle'" class="flex h-4 items-center justify-end gap-1 text-[11px] text-muted-foreground" role="status" aria-live="polite">
<Loader2 v-if="mcpQueryTimeoutSaveStatus === 'saving'" class="size-3 animate-spin" />
<Check v-else-if="mcpQueryTimeoutSaveStatus === 'saved'" class="size-3 text-emerald-600 dark:text-emerald-400" />
<AlertTriangle v-else class="size-3 text-destructive" />
{{ t(`settings.mcpQueryTimeoutSaveStatus_${mcpQueryTimeoutSaveStatus}`) }}
</p>
</div> </div>
</div> </div>
</div> </div>
@@ -11453,6 +11442,12 @@ LIMIT 100;</pre
<ExternalLink class="mr-1 h-3 w-3" /> <ExternalLink class="mr-1 h-3 w-3" />
{{ t("settings.mcpGuide") }} {{ t("settings.mcpGuide") }}
</Button> </Button>
<Button :disabled="!hasChanges() || hasApplyBlocker" @click="applySettings">
{{ t("settings.apply") }}
</Button>
<Button :disabled="!hasChanges() || hasApplyBlocker" @click="applySettingsAndClose">
{{ t("settings.applyAndClose") }}
</Button>
</DialogFooter> </DialogFooter>
<DialogFooter v-else-if="activeSettingsTab === 'security' && isWeb" class="mx-0 mb-0 flex-row flex-wrap items-center justify-end gap-2 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 sm:flex-row sm:gap-2 [&>button]:w-auto [&>button]:shrink-0"> <DialogFooter v-else-if="activeSettingsTab === 'security' && isWeb" class="mx-0 mb-0 flex-row flex-wrap items-center justify-end gap-2 rounded-none border-t border-border/60 bg-transparent px-0 pb-0 pt-3 sm:flex-row sm:gap-2 [&>button]:w-auto [&>button]:shrink-0">
@@ -1,11 +1,8 @@
// @vitest-environment happy-dom // @vitest-environment happy-dom
// Real-DOM integration for the MCP query-timeout input (#8616). The settings // Real-DOM integration for the MCP query-timeout input. The settings dialog
// dialog reads the fresh value from the native event target in capture phase, // reads the fresh value from the native event target in capture phase, before
// before Input's passive v-model proxy updates the parent ref. This test mounts the real // Input's passive v-model proxy updates the parent ref. Typing stages that
// Input component with exactly that wiring and drives it with real DOM events // fresh value into the policy draft and does not persist it.
// 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).
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import { createApp, defineComponent, h, nextTick, type App } from "vue"; import { createApp, defineComponent, h, nextTick, type App } from "vue";
import Input from "@/components/ui/input/Input.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; return el as HTMLInputElement;
} }
function harnessFor(saveMcpPolicy: ReturnType<typeof vi.fn>): { harness: McpQueryTimeoutHarness; inputRef: { value: string } } { function harnessFor(): { harness: McpQueryTimeoutHarness; inputRef: { value: string } } {
const inputRef = { value: "" }; const inputRef = { value: "" };
const harness = createMcpQueryTimeoutHarness({ const harness = createMcpQueryTimeoutHarness({
source: dialogSource, source: dialogSource,
input: inputRef, input: inputRef,
policyQueryTimeoutSecs: null, policyQueryTimeoutSecs: null,
saveMcpPolicy,
}); });
return { harness, inputRef }; 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(); vi.useFakeTimers();
const saveMcpPolicy = vi.fn(); const { harness, inputRef } = harnessFor();
const { harness, inputRef } = harnessFor(saveMcpPolicy);
const el = await mountInput({ const el = await mountInput({
modelValue: inputRef, modelValue: inputRef,
onInput: harness.onMcpQueryTimeoutInput, onInput: harness.onMcpQueryTimeoutInput,
}); });
// Simulate real typing: set the DOM value and dispatch a native input event.
el.value = "300"; el.value = "300";
el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("input", { bubbles: true }));
// The debounce has not elapsed yet: no save. expect(harness.draft.value.queryTimeoutSecs).toBeNull();
expect(saveMcpPolicy).not.toHaveBeenCalled();
// Elapse the debounce window and assert the FRESH value was saved.
vi.advanceTimersByTime(300); vi.advanceTimersByTime(300);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expect(harness.draft.value.queryTimeoutSecs).toBe(300);
expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 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(); vi.useFakeTimers();
const saveMcpPolicy = vi.fn(); const { harness, inputRef } = harnessFor();
const { harness, inputRef } = harnessFor(saveMcpPolicy);
const el = await mountInput({ const el = await mountInput({
modelValue: inputRef, modelValue: inputRef,
@@ -91,16 +81,13 @@ describe("EditorSettingsDialog MCP query timeout real-DOM integration", () => {
el.value = "120"; el.value = "120";
el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("input", { bubbles: true }));
// Close path: flush before the debounce elapses. harness.stageMcpQueryTimeoutDraft();
harness.flushMcpQueryTimeoutSave(); expect(harness.draft.value.queryTimeoutSecs).toBe(120);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1);
expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 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(); vi.useFakeTimers();
const saveMcpPolicy = vi.fn(); const { harness, inputRef } = harnessFor();
const { harness, inputRef } = harnessFor(saveMcpPolicy);
const el = await mountInput({ const el = await mountInput({
modelValue: inputRef, modelValue: inputRef,
@@ -117,7 +104,6 @@ describe("EditorSettingsDialog MCP query timeout real-DOM integration", () => {
el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("input", { bubbles: true }));
vi.advanceTimersByTime(300); vi.advanceTimersByTime(300);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expect(harness.draft.value.queryTimeoutSecs).toBe(123);
expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs: 123 });
}); });
}); });
@@ -1,21 +1,18 @@
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; 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"); const dialogSource = readFileSync(new URL("../EditorSettingsDialog.vue", import.meta.url), "utf8");
// Behavioral coverage for the debounce/flush runtime (review finding): the // The debounce block stages a query timeout into the policy draft. It must not
// string assertions above cannot catch a broken runtime path, so this harness // persist: explicit save is the only write, and close/discard drops the draft.
// extracts the real debounce block from the .vue source, compiles it, and
// drives it with fake timers + mocked deps to assert actual save behaviour.
function nativeInputEvent(value: string, badInput = false): Event { function nativeInputEvent(value: string, badInput = false): Event {
return { currentTarget: { value, validity: { badInput } } } as unknown as Event; return { currentTarget: { value, validity: { badInput } } } as unknown as Event;
} }
function expectQueryTimeoutSave(saveMcpPolicy: ReturnType<typeof vi.fn>, queryTimeoutSecs: number | null) { function expectStagedTimeout(harness: ReturnType<typeof createMcpQueryTimeoutHarness>, queryTimeoutSecs: number | null) {
expect(saveMcpPolicy).toHaveBeenCalled(); expect(harness.draft.value.queryTimeoutSecs).toBe(queryTimeoutSecs);
expect(saveMcpPolicy.mock.calls.at(-1)?.[0]).toEqual({ queryTimeoutSecs });
} }
describe("EditorSettingsDialog MCP query timeout debounce runtime", () => { describe("EditorSettingsDialog MCP query timeout debounce runtime", () => {
@@ -27,117 +24,105 @@ describe("EditorSettingsDialog MCP query timeout debounce runtime", () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it("saves a typed value once the debounce window elapses", () => { it("stages a typed value into the draft once the debounce window elapses, without persisting", () => {
const saveMcpPolicy = vi.fn(); const block = extractMcpQueryTimeoutDebounceBlock(dialogSource);
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy }); expect(block).not.toContain("saveMcpPolicy");
expect(block).not.toContain("updateMcpGlobalPolicy");
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null });
harness.onMcpQueryTimeoutInput(nativeInputEvent("300")); harness.onMcpQueryTimeoutInput(nativeInputEvent("300"));
expect(saveMcpPolicy).not.toHaveBeenCalled(); expect(harness.draft.value.queryTimeoutSecs).toBeNull();
vi.advanceTimersByTime(299); vi.advanceTimersByTime(299);
expect(saveMcpPolicy).not.toHaveBeenCalled(); expect(harness.draft.value.queryTimeoutSecs).toBeNull();
vi.advanceTimersByTime(1); vi.advanceTimersByTime(1);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expectStagedTimeout(harness, 300);
expectQueryTimeoutSave(saveMcpPolicy, 300);
}); });
it("reports saving immediately and saved after the persistence callback", () => { it("coalesces rapid typing into a single draft update", () => {
const setSaveStatus = vi.fn(); const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null });
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 });
harness.onMcpQueryTimeoutInput(nativeInputEvent("1")); harness.onMcpQueryTimeoutInput(nativeInputEvent("1"));
vi.advanceTimersByTime(100); vi.advanceTimersByTime(100);
harness.onMcpQueryTimeoutInput(nativeInputEvent("12")); harness.onMcpQueryTimeoutInput(nativeInputEvent("12"));
vi.advanceTimersByTime(100); vi.advanceTimersByTime(100);
harness.onMcpQueryTimeoutInput(nativeInputEvent("123")); harness.onMcpQueryTimeoutInput(nativeInputEvent("123"));
vi.advanceTimersByTime(300); vi.advanceTimersByTime(300);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expectStagedTimeout(harness, 123);
expectQueryTimeoutSave(saveMcpPolicy, 123);
}); });
it("flush persists a pending value before the debounce elapses", () => { it("stages a pending value before the debounce elapses", () => {
const saveMcpPolicy = vi.fn(); const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null });
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy });
harness.onMcpQueryTimeoutInput(nativeInputEvent("120")); harness.onMcpQueryTimeoutInput(nativeInputEvent("120"));
harness.flushMcpQueryTimeoutSave(); harness.stageMcpQueryTimeoutDraft();
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expectStagedTimeout(harness, 120);
expectQueryTimeoutSave(saveMcpPolicy, 120); harness.stageMcpQueryTimeoutDraft();
// Flushing again with nothing pending is a no-op. expectStagedTimeout(harness, 120);
harness.flushMcpQueryTimeoutSave();
expect(saveMcpPolicy).toHaveBeenCalledTimes(1);
}); });
it("flush after the timer fired does not double-save", () => { it("staging after the timer fired does not change the draft again", () => {
const saveMcpPolicy = vi.fn(); const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null });
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy });
harness.onMcpQueryTimeoutInput(nativeInputEvent("60")); harness.onMcpQueryTimeoutInput(nativeInputEvent("60"));
vi.advanceTimersByTime(300); vi.advanceTimersByTime(300);
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); expectStagedTimeout(harness, 60);
harness.flushMcpQueryTimeoutSave(); harness.draft.value.queryTimeoutSecs = 1;
expect(saveMcpPolicy).toHaveBeenCalledTimes(1); harness.stageMcpQueryTimeoutDraft();
expect(harness.draft.value.queryTimeoutSecs).toBe(1);
}); });
it("retains a pending value while another MCP policy mutation holds the gate", () => { it("empty input stages null (inherit the connection)", () => {
const saveMcpPolicy = vi.fn(); const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 300 });
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 });
harness.onMcpQueryTimeoutInput(nativeInputEvent("")); harness.onMcpQueryTimeoutInput(nativeInputEvent(""));
harness.flushMcpQueryTimeoutSave(); harness.stageMcpQueryTimeoutDraft();
expectQueryTimeoutSave(saveMcpPolicy, null); expectStagedTimeout(harness, null);
}); });
it("zero input persists 0 (no limit)", () => { it("zero input stages 0 (no limit)", () => {
const saveMcpPolicy = vi.fn(); const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null });
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: null, saveMcpPolicy });
harness.onMcpQueryTimeoutInput(nativeInputEvent("0")); harness.onMcpQueryTimeoutInput(nativeInputEvent("0"));
harness.flushMcpQueryTimeoutSave(); harness.stageMcpQueryTimeoutDraft();
expectQueryTimeoutSave(saveMcpPolicy, 0); expectStagedTimeout(harness, 0);
}); });
it("invalid input cancels the pending save and reverts the field", () => { it("invalid input cancels the pending stage and reverts the field", () => {
const saveMcpPolicy = vi.fn();
const toast = vi.fn(); const toast = vi.fn();
const input = { value: "1.5" }; 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"); const event = nativeInputEvent("1.5");
harness.onMcpQueryTimeoutInput(event); harness.onMcpQueryTimeoutInput(event);
// Invalid input must not schedule anything.
vi.advanceTimersByTime(300); vi.advanceTimersByTime(300);
expect(saveMcpPolicy).not.toHaveBeenCalled(); expect(harness.draft.value.queryTimeoutSecs).toBeNull();
expect(toast).toHaveBeenCalledTimes(1); expect(toast).toHaveBeenCalledTimes(1);
// The bound ref is reverted to the persisted value ("" == inherit).
expect(input.value).toBe(""); 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(""); expect((event.currentTarget as { value: string }).value).toBe("");
}); });
it("does not treat a bad number-input intermediate state as inherit", () => { 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 });
const harness = createMcpQueryTimeoutHarness({ source: dialogSource, input: { value: "" }, policyQueryTimeoutSecs: 90, saveMcpPolicy });
harness.onMcpQueryTimeoutInput(nativeInputEvent("45")); harness.onMcpQueryTimeoutInput(nativeInputEvent("45"));
vi.advanceTimersByTime(100); vi.advanceTimersByTime(100);
harness.onMcpQueryTimeoutInput(nativeInputEvent("", true)); harness.onMcpQueryTimeoutInput(nativeInputEvent("", true));
vi.advanceTimersByTime(200); vi.advanceTimersByTime(200);
expectQueryTimeoutSave(saveMcpPolicy, 45); expectStagedTimeout(harness, 45);
expect(saveMcpPolicy.mock.calls.some(([partial]) => partial.queryTimeoutSecs === null)).toBe(false); });
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");
}); });
}); });
@@ -6,7 +6,8 @@ import ts from "typescript";
export interface McpQueryTimeoutHarness { export interface McpQueryTimeoutHarness {
onMcpQueryTimeoutInput: (event: Event) => void; onMcpQueryTimeoutInput: (event: Event) => void;
flushMcpQueryTimeoutSave: () => void; stageMcpQueryTimeoutDraft: () => void;
draft: { value: { queryTimeoutSecs: number | null } };
} }
export function extractMcpQueryTimeoutDebounceBlock(source: string): string { export function extractMcpQueryTimeoutDebounceBlock(source: string): string {
@@ -16,28 +17,13 @@ export function extractMcpQueryTimeoutDebounceBlock(source: string): string {
return source.slice(start, end); return source.slice(start, end);
} }
export function createMcpQueryTimeoutHarness(options: { export function createMcpQueryTimeoutHarness(options: { source: string; input: { value: string }; policyQueryTimeoutSecs: number | null; toast?: (message: string, duration: number) => void; t?: (key: string) => string }): McpQueryTimeoutHarness {
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 {
const block = extractMcpQueryTimeoutDebounceBlock(options.source); const block = extractMcpQueryTimeoutDebounceBlock(options.source);
const javascript = ts.transpileModule(block, { const javascript = ts.transpileModule(block, {
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 }, compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
}).outputText; }).outputText;
const factory = new Function("mcpQueryTimeoutInput", "settingsStore", "saveMcpPolicy", "toast", "t", "mcpPolicyControlsDisabled", "setMcpQueryTimeoutSaveStatus", `${javascript}\nreturn { onMcpQueryTimeoutInput, flushMcpQueryTimeoutSave };`); const draft = { value: { queryTimeoutSecs: options.policyQueryTimeoutSecs } };
return factory( const factory = new Function("mcpQueryTimeoutInput", "mcpPolicyDraft", "toast", "t", `${javascript}\nreturn { onMcpQueryTimeoutInput, stageMcpQueryTimeoutDraft };`);
options.input, const harness = factory(options.input, draft, options.toast ?? (() => {}), options.t ?? ((key: string) => key)) as Omit<McpQueryTimeoutHarness, "draft">;
{ mcpGlobalPolicy: { queryTimeoutSecs: options.policyQueryTimeoutSecs } }, return { ...harness, draft };
options.saveMcpPolicy,
options.toast ?? (() => {}),
options.t ?? ((key: string) => key),
options.policyMutationBlocked ?? { value: false },
options.setSaveStatus ?? (() => {}),
) as McpQueryTimeoutHarness;
} }
@@ -15,8 +15,9 @@ const steps = computed<Array<{ id: StepId; title: string; description: string }>
const currentStep = ref<StepId>("overrides"); const currentStep = ref<StepId>("overrides");
const currentIndex = computed(() => steps.value.findIndex((step) => step.id === currentStep.value)); 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, // Every step is directly reachable from the nav above and all policy edits stage into the
// so the last step has nothing to advance to and nothing to confirm. // 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); const isLastStep = computed(() => currentIndex.value === steps.value.length - 1);
function scrollableAncestor(target: EventTarget | null): HTMLElement | null { function scrollableAncestor(target: EventTarget | null): HTMLElement | null {