refactor(credentials): introduce /credentials subresource pattern

Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.

Why
---
The previous design had three problems:

1. Main PUT body carried secret fields. The frontend echoed back a
   redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
   defense in the service layer tried to detect "user did not change this"
   vs "user wants to clear this". A regression in that defense (or a new
   frontend forgetting it) silently overwrites the stored secret with the
   placeholder.

2. The "remove this credential" UX was a red checkbox under a pre-filled
   password input. Three intents (preserve / replace / clear) collapsed
   onto one field, and credential changes were bundled with unrelated
   config edits in the same submit. Users wiped working keys by mistake.

3. Secret presence was inferred from "did the response come back with a
   '***' placeholder", which couples the contract to a magic string.

Design
------
Each of the four resources now exposes:

  PUT    /{resource}/{id}/credentials          # write one or more fields
  DELETE /{resource}/{id}/credentials/{field}  # clear a single field

"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.

Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.

Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
  (unconfigured / configured / editing) and drives the dedicated
  endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
  card with the same behaviour because its credentials are a single
  atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
  prop. The previous async refresh() was a no-op while state was still
  'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
  deterrent; a modal confirm adds friction without adding safety (the
  plaintext is irrecoverable client-side either way — recovery means
  re-typing).

DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.

Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.

Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
  types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
  / ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
  RedactedSecretPlaceholder constant is retained because VectorStore
  still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
  redaction handling removed; i18n keys renamed secret -> credential.
This commit is contained in:
wizardchen
2026-05-17 15:09:30 +08:00
committed by lyingbug
parent f30e9ccd0f
commit 7643dd457e
53 changed files with 3271 additions and 2347 deletions
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
createDataSource,
@@ -10,6 +10,8 @@ import {
validateCredentials,
listResources,
deleteDataSource,
putDataSourceCredentials,
deleteDataSourceCredentials,
type DataSource,
type Resource,
} from '@/api/datasource'
@@ -28,37 +30,56 @@ const isEdit = computed(() => !!props.dataSource)
const step = ref(0)
const submitting = ref(false)
// Fixed placeholder returned by the server for redacted credential strings.
// Must match internal/types/secret.go → RedactedSecretPlaceholder.
const REDACTED_PLACEHOLDER = '***'
// In edit mode the credential "configured?" flag travels on the main
// DataSource response (DataSource.credentials.credentials.configured —
// server-side dto.DataSourceResponse.Credentials). True iff a credential
// map is currently stored server-side.
const credentialsConfigured = ref(false)
// Per-field: is this specific credential key stored server-side? Drives the
// per-input placeholder swap to the "••••••• (Enter new value to replace)"
// hint when the server marked it present.
function hasFieldCredential(key: string): boolean {
return props.dataSource?.config?.credentials?.[key] === REDACTED_PLACEHOLDER
}
// "Replace credentials" mode toggle in edit. Defaults to false: a configured
// connector shows a small "Credentials configured ✓" line with Replace /
// Remove actions. Toggling Replace reveals the credential inputs so the
// user can type a new set. Untoggling discards anything typed.
const replaceCredentialsMode = ref(false)
// Connector-level rollup: true when any credential key is stored. Used to
// decide whether to render the "Remove all credentials" checkbox.
const hasExistingCredentials = computed(() => {
const creds = props.dataSource?.config?.credentials
if (!creds) return false
return Object.values(creds).some(v => v === REDACTED_PLACEHOLDER)
// Whether the credential input section is interactive right now. In create
// mode it's always shown; in edit mode only when the user opted in to
// Replace, OR when nothing is configured yet (degenerate case where the
// data source row exists with no credentials stored).
const credentialsInputVisible = computed(() => {
if (!isEdit.value) return true
if (!credentialsConfigured.value) return true
return replaceCredentialsMode.value
})
// Placeholder for a given credential input: stored → shared hint,
// otherwise the connector-specific default (e.g. "ntn_xxxx" for Notion).
function credentialPlaceholder(field: { key: string; placeholder: string }): string {
return hasFieldCredential(field.key)
? t('secret.storedPlaceholder')
: field.placeholder
function refreshCredentialsStatus() {
// Re-derive from whatever the parent passed in props.dataSource. Called
// when the dialog opens or props.dataSource is swapped; the parent is
// expected to re-fetch the data source list after credential mutations
// so the new metadata flows in here automatically.
if (!isEdit.value || !props.dataSource) {
credentialsConfigured.value = false
return
}
credentialsConfigured.value =
props.dataSource.credentials?.credentials?.configured === true
}
// Explicit "remove all credentials" flag. Because credentials form an atomic
// set per connector (e.g. an OAuth pair) we only support all-or-nothing
// clearing, mirroring the backend DataSourceConfig.ClearCredentials contract.
const clearCredentials = ref(false)
// Single-click remove with toast feedback. Mirrors the CredentialResource
// component's UX: the secret is irrecoverable client-side either way, so a
// modal confirm just adds friction. The danger-themed button is the deterrent.
async function removeCredentials() {
if (!props.dataSource?.id) return
try {
await deleteDataSourceCredentials(props.dataSource.id)
credentialsConfigured.value = false
replaceCredentialsMode.value = false
form.value.config.credentials = {}
MessagePlugin.success(t('credential.removedToast'))
} catch (e: any) {
MessagePlugin.error(e?.message || t('credential.removeFailed'))
}
}
// Form data
const form = ref({
@@ -245,14 +266,12 @@ watch(visible, (v) => {
selectedResourceIds.value = []
if (isEdit.value && props.dataSource) {
// Reset clear intent on every open so an aborted deletion doesn't
// carry over to the next edit session.
clearCredentials.value = false
// Credentials are intentionally NOT pre-filled from the server response
// — even though the server returns '***' for stored secrets, the form
// holds an empty map. This keeps the "non-empty means user typed it"
// invariant that the save path relies on, and the badge reflects the
// stored state via hasExistingCredentials instead.
// Reset edit/replace toggle every open so an aborted replace doesn't
// carry over. credentialsConfigured will be refreshed from the
// /credentials subresource (run separately below).
replaceCredentialsMode.value = false
credentialsConfigured.value = false
refreshCredentialsStatus()
form.value = {
name: props.dataSource.name,
type: props.dataSource.type,
@@ -269,7 +288,8 @@ watch(visible, (v) => {
selectedResourceIds.value = form.value.config?.resource_ids || []
tempDsId.value = props.dataSource.id
} else {
clearCredentials.value = false
replaceCredentialsMode.value = false
credentialsConfigured.value = false
form.value = {
name: '',
type: '',
@@ -450,51 +470,60 @@ function prevStep() {
step.value--
}
// Prompt the user before irrevocable credential removal.
function confirmClearIfNeeded(): Promise<boolean> {
if (!clearCredentials.value) return Promise.resolve(true)
return new Promise((resolve) => {
const d = DialogPlugin.confirm({
header: t('secret.confirmClearTitle'),
body: t('secret.confirmClearBody'),
confirmBtn: { content: t('common.confirm'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: () => { d.hide(); resolve(true) },
onCancel: () => { d.hide(); resolve(false) },
onClose: () => { d.hide(); resolve(false) },
})
})
}
// Build the config payload for Create / Update requests. In edit mode this
// applies write-only secret semantics:
// - clearCredentials checked → send clear_credentials: true (backend wipes)
// - user typed credential values → send them as-is
// - user left fields blank → send empty credentials map (backend preserves
// every existing credential key individually)
// Build the config payload for Create / Update requests.
//
// Create mode: credentials flow inline so the initial data source row
// already carries them.
//
// Edit mode: credentials NEVER flow through the main PUT — they go via the
// /credentials subresource, committed before the main submit (see
// commitCredentialsIfNeeded). Sending an empty map keeps the backend
// validator happy.
function buildConfigPayload(): Record<string, unknown> {
const cfg: Record<string, unknown> = {
credentials: clearCredentials.value ? {} : { ...form.value.config.credentials },
return {
credentials: isEdit.value ? {} : { ...form.value.config.credentials },
resource_ids: form.value.config.resource_ids,
settings: form.value.config.settings,
}
if (clearCredentials.value) {
cfg.clear_credentials = true
}
// In edit mode, when the user opted in to Replace credentials and typed at
// least one value, commit it to /credentials before the main PUT. Aborts
// the whole submit on failure so we don't leave the row partially saved.
async function commitCredentialsIfNeeded(dsId: string): Promise<boolean> {
if (!isEdit.value || !replaceCredentialsMode.value) return true
const filled = Object.entries(form.value.config.credentials).filter(
([, v]) => typeof v === 'string' ? v !== '' : v != null,
)
if (filled.length === 0) return true
try {
await putDataSourceCredentials(dsId, Object.fromEntries(filled))
credentialsConfigured.value = true
replaceCredentialsMode.value = false
form.value.config.credentials = {}
return true
} catch (e: any) {
MessagePlugin.error(e?.message || e?.error || t('credential.saveFailed'))
return false
}
return cfg
}
// --- Final submit ---
async function handleSubmit() {
const ok = await confirmClearIfNeeded()
if (!ok) return
form.value.config.resource_ids = selectedResourceIds.value
submitting.value = true
try {
let dataSourceId = tempDsId.value
if (tempDsId.value) {
// Commit credential replacement BEFORE the main PUT so a validation
// failure on credentials doesn't leave us with an updated row that
// still points at the old broken token.
const credsOk = await commitCredentialsIfNeeded(tempDsId.value)
if (!credsOk) {
submitting.value = false
return
}
await updateDataSource(tempDsId.value, {
...form.value,
config: buildConfigPayload(),
@@ -565,21 +594,11 @@ const stepTitles = computed(() => [
</script>
<template>
<t-dialog
v-model:visible="visible"
:header="isEdit ? t('datasource.editTitle') : t('datasource.createTitle')"
:footer="false"
width="640px"
destroy-on-close
:on-close="handleClose"
>
<t-dialog v-model:visible="visible" :header="isEdit ? t('datasource.editTitle') : t('datasource.createTitle')"
:footer="false" width="640px" destroy-on-close :on-close="handleClose">
<!-- Step indicator -->
<div class="ds-steps">
<div
v-for="(title, i) in stepTitles"
:key="i"
:class="['ds-step', { active: step === i, done: step > i }]"
>
<div v-for="(title, i) in stepTitles" :key="i" :class="['ds-step', { active: step === i, done: step > i }]">
<span class="ds-step-num">{{ step > i ? '&#10003;' : i + 1 }}</span>
<span class="ds-step-title">{{ title }}</span>
</div>
@@ -588,12 +607,8 @@ const stepTitles = computed(() => [
<!-- Step 0: Select connector type -->
<div v-if="step === 0" class="ds-step-content">
<div class="ds-type-grid">
<div
v-for="def in connectorDefs"
:key="def.type"
:class="['ds-type-card', { disabled: !def.available }]"
@click="selectType(def)"
>
<div v-for="def in connectorDefs" :key="def.type" :class="['ds-type-card', { disabled: !def.available }]"
@click="selectType(def)">
<div class="ds-type-header">
<DataSourceTypeIcon :type="def.type" :size="20" />
<span class="ds-type-name">{{ t(`datasource.connector.${def.type}`) }}</span>
@@ -607,7 +622,8 @@ const stepTitles = computed(() => [
<!-- Step 1: Credentials -->
<div v-if="step === 1" class="ds-step-content">
<!-- Compact collapsible prereq hint -->
<div v-if="currentDef && currentDef.requiredPermissions.length > 0" class="ds-prereq-bar" @click="prereqExpanded = !prereqExpanded">
<div v-if="currentDef && currentDef.requiredPermissions.length > 0" class="ds-prereq-bar"
@click="prereqExpanded = !prereqExpanded">
<t-icon name="help-circle" size="14px" />
<span>{{ t(`datasource.prereqBarText_${form.type}`, t('datasource.prereqBarText')) }}</span>
<t-icon :name="prereqExpanded ? 'chevron-up' : 'chevron-down'" size="14px" class="ds-prereq-arrow" />
@@ -616,14 +632,17 @@ const stepTitles = computed(() => [
<div class="ds-prereq-item">
<span class="ds-prereq-num">1</span>
<div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep1Brief_${form.type}`, t('datasource.prereqBotBrief')) }}</div>
<div class="ds-prereq-item-desc">{{ t(`datasource.prereqStep1Desc_${form.type}`, t('datasource.prereqBotDesc')) }}</div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep1Brief_${form.type}`,
t('datasource.prereqBotBrief')) }}</div>
<div class="ds-prereq-item-desc">{{ t(`datasource.prereqStep1Desc_${form.type}`,
t('datasource.prereqBotDesc')) }}</div>
</div>
</div>
<div class="ds-prereq-item">
<span class="ds-prereq-num">2</span>
<div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep2Brief_${form.type}`, t('datasource.prereqPermBrief')) }}</div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep2Brief_${form.type}`,
t('datasource.prereqPermBrief')) }}</div>
<div class="ds-prereq-item-desc">
<template v-if="!t(`datasource.prereqStep2Desc_${form.type}`)">
<code v-for="perm in currentDef.requiredPermissions" :key="perm" class="ds-perm-tag">{{ perm }}</code>
@@ -635,8 +654,11 @@ const stepTitles = computed(() => [
<div class="ds-prereq-item">
<span class="ds-prereq-num">3</span>
<div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep3Brief_${form.type}`, t('datasource.prereqMemberBrief')) }}</div>
<div class="ds-prereq-item-desc">{{ t(`datasource.prereqStep3Desc_${form.type}`, t('datasource.prereqMemberDesc')) }}</div>
<div class="ds-prereq-item-title">{{ t(`datasource.prereqStep3Brief_${form.type}`,
t('datasource.prereqMemberBrief')) }}</div>
<div class="ds-prereq-item-desc">{{ t(`datasource.prereqStep3Desc_${form.type}`,
t('datasource.prereqMemberDesc'))
}}</div>
</div>
</div>
<a :href="currentDef.permissionPageUrl" target="_blank" rel="noopener" class="doc-link ds-prereq-link">
@@ -660,32 +682,45 @@ const stepTitles = computed(() => [
</div>
<!--
Credential fields. When the server returned '***' for a field the
per-input placeholder swaps to the shared "••••••• (Enter new value
to replace)" hint so the input carries the "something is stored"
signal without a separate badge. The "Remove all credentials"
checkbox below handles the destructive clear for the whole set
(DataSource credentials are per-connector atomic bundles).
Credentials card (edit mode). DataSource credentials are a
per-connector atomic set (OAuth pair, GitHub PAT + username, etc.),
so unlike MCP/Model/WebSearch the credential subresource exposes
only one logical field. The UI here mirrors <CredentialResource>'s
three-state behavior (configured / unconfigured / editing) but with
the connector-specific form embedded inline when editing.
-->
<div v-for="field in currentDef?.fields || []" :key="field.key" class="form-item">
<label class="form-label">
{{ t(field.labelKey) }}
<span v-if="!field.optional" class="required-mark">*</span>
</label>
<t-input
v-model="form.config.credentials[field.key]"
:disabled="clearCredentials"
:placeholder="credentialPlaceholder(field)"
:type="field.secret ? 'password' : 'text'"
/>
<div v-if="field.hintKey" class="form-hint">{{ t(field.hintKey) }}</div>
<div v-if="isEdit && credentialsConfigured && !replaceCredentialsMode" class="form-item credential-card">
<div class="credential-card-row">
<span class="credential-badge">
<t-icon name="check-circle-filled" size="14px" />
{{ t('credential.configured') }}
</span>
<t-button variant="text" theme="primary" @click="replaceCredentialsMode = true">
{{ t('credential.update') }}
</t-button>
<t-button variant="text" theme="danger" @click="removeCredentials">
{{ t('credential.remove') }}
</t-button>
</div>
</div>
<div v-if="isEdit && hasExistingCredentials" class="form-item">
<t-checkbox v-model="clearCredentials" class="clear-credential">
{{ t('secret.clearHint') }}
</t-checkbox>
</div>
<template v-if="credentialsInputVisible">
<div v-for="field in currentDef?.fields || []" :key="field.key" class="form-item">
<label class="form-label">
{{ t(field.labelKey) }}
<span v-if="!field.optional" class="required-mark">*</span>
</label>
<t-input v-model="form.config.credentials[field.key]" :placeholder="field.placeholder"
:type="field.secret ? 'password' : 'text'" />
<div v-if="field.hintKey" class="form-hint">{{ t(field.hintKey) }}</div>
</div>
<div v-if="isEdit && replaceCredentialsMode" class="form-item">
<t-button variant="text" @click="replaceCredentialsMode = false; form.config.credentials = {}">
{{ t('common.cancel') }}
</t-button>
</div>
</template>
<div class="form-actions">
<t-button variant="outline" :loading="testing" @click="testConnection">
@@ -715,27 +750,16 @@ const stepTitles = computed(() => [
<p class="form-tip">{{ t('datasource.resourceHint') }}</p>
<div v-if="loadingResources" style="text-align:center;padding:20px"><t-loading /></div>
<div v-else-if="resources.length > 0" class="ds-resource-list">
<div
v-for="{ resource: r, depth } in visibleTree"
:key="r.external_id"
<div v-for="{ resource: r, depth } in visibleTree" :key="r.external_id"
:class="['ds-resource-row', { selected: checkStates.get(r.external_id) === 'checked' }]"
:style="{ paddingLeft: `${12 + depth * 24}px` }"
@click="toggleResource(r.external_id)"
>
<span
v-if="r.has_children"
class="ds-expand-btn"
@click.stop="toggleExpand(r.external_id)"
>
:style="{ paddingLeft: `${12 + depth * 24}px` }" @click="toggleResource(r.external_id)">
<span v-if="r.has_children" class="ds-expand-btn" @click.stop="toggleExpand(r.external_id)">
<t-icon :name="expandedResourceIds.has(r.external_id) ? 'chevron-down' : 'chevron-right'" size="16px" />
</span>
<span v-else class="ds-expand-placeholder" />
<t-checkbox
:checked="checkStates.get(r.external_id) === 'checked'"
:indeterminate="checkStates.get(r.external_id) === 'indeterminate'"
@click.stop
@change="toggleResource(r.external_id)"
/>
<t-checkbox :checked="checkStates.get(r.external_id) === 'checked'"
:indeterminate="checkStates.get(r.external_id) === 'indeterminate'" @click.stop
@change="toggleResource(r.external_id)" />
<div class="ds-resource-info">
<div class="ds-resource-name">{{ r.name || t('datasource.untitled') }}</div>
<div class="ds-resource-meta">
@@ -768,7 +792,8 @@ const stepTitles = computed(() => [
<t-button variant="outline" size="small" @click="loadResources">
{{ t('datasource.retryLoadResources') }}
</t-button>
<a v-if="currentDef?.permissionDocUrl" :href="currentDef.permissionDocUrl" target="_blank" rel="noopener" class="doc-link">
<a v-if="currentDef?.permissionDocUrl" :href="currentDef.permissionDocUrl" target="_blank" rel="noopener"
class="doc-link">
{{ t('datasource.permissionDocLink') }}
<t-icon name="link" class="link-icon" />
</a>
@@ -838,8 +863,14 @@ const stepTitles = computed(() => [
color: var(--td-text-color-placeholder);
}
.ds-step.active { color: var(--td-brand-color); font-weight: 600; }
.ds-step.done { color: var(--td-success-color); }
.ds-step.active {
color: var(--td-brand-color);
font-weight: 600;
}
.ds-step.done {
color: var(--td-success-color);
}
.ds-step-num {
width: 22px;
@@ -852,10 +883,21 @@ const stepTitles = computed(() => [
border: 1px solid currentColor;
}
.ds-step.active .ds-step-num { background: var(--td-brand-color); color: #fff; border-color: var(--td-brand-color); }
.ds-step.done .ds-step-num { background: var(--td-success-color); color: #fff; border-color: var(--td-success-color); }
.ds-step.active .ds-step-num {
background: var(--td-brand-color);
color: #fff;
border-color: var(--td-brand-color);
}
.ds-step-content { min-height: 200px; }
.ds-step.done .ds-step-num {
background: var(--td-success-color);
color: #fff;
border-color: var(--td-success-color);
}
.ds-step-content {
min-height: 200px;
}
/* --- Step 0: type cards --- */
.ds-type-grid {
@@ -872,13 +914,41 @@ const stepTitles = computed(() => [
transition: all 0.2s;
}
.ds-type-card:hover:not(.disabled) { border-color: var(--td-brand-color); background: var(--td-brand-color-light); }
.ds-type-card.disabled { opacity: 0.5; cursor: not-allowed; }
.ds-type-card:hover:not(.disabled) {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
}
.ds-type-header { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.ds-type-name { font-size: 13px; font-weight: 600; }
.ds-type-soon { font-size: 10px; color: var(--td-text-color-placeholder); background: var(--td-bg-color-component); padding: 1px 6px; border-radius: 3px; }
.ds-type-desc { font-size: 11px; color: var(--td-text-color-secondary); line-height: 1.5; }
.ds-type-card.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ds-type-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.ds-type-name {
font-size: 13px;
font-weight: 600;
}
.ds-type-soon {
font-size: 10px;
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-component);
padding: 1px 6px;
border-radius: 3px;
}
.ds-type-desc {
font-size: 11px;
color: var(--td-text-color-secondary);
line-height: 1.5;
}
/* --- Step 1: collapsible prereq --- */
.ds-prereq-bar {
@@ -982,19 +1052,56 @@ const stepTitles = computed(() => [
word-break: break-all;
}
.form-item { margin-bottom: 16px; }
.form-label { display: block; font-size: 13px; font-weight: 500; margin-bottom: 6px; color: var(--td-text-color-primary); }
.required-mark { color: var(--td-error-color); margin-left: 2px; }
.form-item {
margin-bottom: 16px;
}
.form-label {
display: block;
font-size: 13px;
font-weight: 500;
margin-bottom: 6px;
color: var(--td-text-color-primary);
}
.required-mark {
color: var(--td-error-color);
margin-left: 2px;
}
/* Destructive-action checkbox — red label, matches the other 3 dialogs. */
.clear-credential :deep(.t-checkbox__label) {
color: var(--td-error-color);
font-size: 13px;
}
.form-tip { font-size: 12px; color: var(--td-text-color-placeholder); margin: 4px 0 12px; }
.form-hint { font-size: 12px; color: var(--td-text-color-placeholder); margin-top: 6px; line-height: 1.5; }
.form-actions { display: flex; align-items: center; gap: 8px; margin-top: 12px; }
.test-ok { color: var(--td-success-color); font-size: 13px; display: flex; align-items: center; gap: 4px; }
.form-tip {
font-size: 12px;
color: var(--td-text-color-placeholder);
margin: 4px 0 12px;
}
.form-hint {
font-size: 12px;
color: var(--td-text-color-placeholder);
margin-top: 6px;
line-height: 1.5;
}
.form-actions {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
}
.test-ok {
color: var(--td-success-color);
font-size: 13px;
display: flex;
align-items: center;
gap: 4px;
}
.test-error-box {
display: flex;
@@ -1027,10 +1134,23 @@ const stepTitles = computed(() => [
word-break: break-word;
}
.ds-dialog-footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 24px; padding-top: 16px; border-top: 1px solid var(--td-border-level-2-color); }
.ds-dialog-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 24px;
padding-top: 16px;
border-top: 1px solid var(--td-border-level-2-color);
}
/* --- Step 2: resource list --- */
.ds-resource-list { max-height: 400px; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; }
.ds-resource-list {
max-height: 400px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 2px;
}
.ds-expand-btn {
display: flex;
@@ -1044,8 +1164,15 @@ const stepTitles = computed(() => [
flex-shrink: 0;
transition: background 0.15s;
}
.ds-expand-btn:hover { background: var(--td-bg-color-component-hover); }
.ds-expand-placeholder { width: 20px; flex-shrink: 0; }
.ds-expand-btn:hover {
background: var(--td-bg-color-component-hover);
}
.ds-expand-placeholder {
width: 20px;
flex-shrink: 0;
}
.ds-resource-row {
display: flex;
@@ -1161,5 +1288,4 @@ const stepTitles = computed(() => [
justify-content: center;
gap: 16px;
}
</style>
+25 -52
View File
@@ -6,11 +6,8 @@
<h2>{{ $t('modelSettings.title') }}</h2>
<p class="section-description">{{ $t('modelSettings.description') }}</p>
</div>
<t-dropdown
:options="addModelOptions"
placement="bottom-right"
@click="(data: any) => openAddDialog(data.value)"
>
<t-dropdown :options="addModelOptions" placement="bottom-right"
@click="(data: any) => openAddDialog(data.value)">
<t-button theme="primary" variant="outline" size="small">
<template #icon><add-icon /></template>
{{ $t('modelSettings.actions.addModel') }}
@@ -21,12 +18,8 @@
<div class="builtin-models-hint" role="note">
<p class="builtin-hint-label">{{ $t('modelSettings.builtinModels.title') }}</p>
<p class="builtin-hint-text">{{ $t('modelSettings.builtinModels.description') }}</p>
<a
class="doc-link"
href="https://github.com/Tencent/WeKnora/blob/main/docs/BUILTIN_MODELS.md"
target="_blank"
rel="noopener noreferrer"
>
<a class="doc-link" href="https://github.com/Tencent/WeKnora/blob/main/docs/BUILTIN_MODELS.md" target="_blank"
rel="noopener noreferrer">
{{ $t('modelSettings.builtinModels.viewGuide') }}
<t-icon name="link" class="link-icon" />
</a>
@@ -36,21 +29,17 @@
<t-tabs v-model="activeTypeFilter" class="model-type-tabs">
<t-tab-panel value="all" :label="`${$t('common.all')}(${allLegacyModels.length})`" />
<t-tab-panel value="chat" :label="`${$t('modelSettings.typeShort.chat')}(${countByType('chat')})`" />
<t-tab-panel value="embedding" :label="`${$t('modelSettings.typeShort.embedding')}(${countByType('embedding')})`" />
<t-tab-panel value="embedding"
:label="`${$t('modelSettings.typeShort.embedding')}(${countByType('embedding')})`" />
<t-tab-panel value="rerank" :label="`${$t('modelSettings.typeShort.rerank')}(${countByType('rerank')})`" />
<t-tab-panel value="vllm" :label="`${$t('modelSettings.typeShort.vllm')}(${countByType('vllm')})`" />
<t-tab-panel value="asr" :label="`${$t('modelSettings.typeShort.asr')}(${countByType('asr')})`" />
</t-tabs>
<div v-if="filteredModels.length > 0" class="model-grid">
<SettingCard
v-for="model in filteredModels"
:key="`${model._modelType}-${model.id}`"
:title="model.name"
:disabled="model.isBuiltin"
:actions="getModelOptions(model._modelType, model)"
@action="(value: string) => handleMenuAction({ value }, model._modelType, model)"
>
<SettingCard v-for="model in filteredModels" :key="`${model._modelType}-${model.id}`" :title="model.name"
:disabled="model.isBuiltin" :actions="getModelOptions(model._modelType, model)"
@action="(value: string) => handleMenuAction({ value }, model._modelType, model)">
<template #tags>
<t-tag size="small" variant="light" :class="`model-type-tag model-type-tag--${model._modelType}`">
{{ typeLabel(model._modelType) }}
@@ -79,11 +68,7 @@
</div>
<div v-else class="empty-state">
<t-empty :description="emptyHint">
<t-dropdown
:options="addModelOptions"
placement="bottom"
@click="(data: any) => openAddDialog(data.value)"
>
<t-dropdown :options="addModelOptions" placement="bottom" @click="(data: any) => openAddDialog(data.value)">
<t-button theme="primary" variant="outline" size="small">
<template #icon><add-icon /></template>
{{ $t('modelSettings.actions.addModel') }}
@@ -93,12 +78,8 @@
</div>
<!-- 模型编辑器抽屉 -->
<ModelEditorDialog
v-model:visible="showDialog"
:model-type="currentModelType"
:model-data="editingModel"
@confirm="handleModelSave"
/>
<ModelEditorDialog v-model:visible="showDialog" :model-type="currentModelType" :model-data="editingModel"
@confirm="handleModelSave" />
</div>
</template>
@@ -138,13 +119,10 @@ const backendTypeToModelType: Record<string, ModelType> = {
}
// 将后端模型格式转换为旧的前端格式(附带 _modelType 便于渲染)
// NOTE: apiKey is intentionally NEVER pre-filled from the server response.
// The server returns '***' as a redacted placeholder when a key is stored,
// and '' when it is not. We expose this as hasExistingApiKey so the editor
// dialog can render a "Set / Not set" badge, while the apiKey field starts
// blank — this preserves the invariant "non-empty formData.apiKey means the
// user typed something" that the save path relies on to decide preserve /
// replace / clear.
// apiKey is always blank here: the server's main GET response does not
// include it (see internal/handler/dto/model.go — ModelParametersDTO omits
// secret fields). Credential read/write happens inside the editor dialog
// via the dedicated /credentials subresource.
function convertToLegacyFormat(model: ModelConfig) {
return {
id: model.id!,
@@ -153,7 +131,6 @@ function convertToLegacyFormat(model: ModelConfig) {
modelName: model.name,
baseUrl: model.parameters.base_url || '',
apiKey: '',
hasExistingApiKey: model.parameters.api_key === '***',
provider: model.parameters.provider || '',
dimension: model.parameters.embedding_parameters?.dimension,
isBuiltin: model.is_builtin || false,
@@ -161,7 +138,10 @@ function convertToLegacyFormat(model: ModelConfig) {
customHeaders: model.parameters.custom_headers
? Object.entries(model.parameters.custom_headers).map(([key, value]) => ({ key, value: String(value) }))
: [],
_modelType: backendTypeToModelType[model.type] || 'chat' as ModelType
_modelType: backendTypeToModelType[model.type] || 'chat' as ModelType,
// Preserve the credential metadata map so the editor dialog can render
// the "Configured" state without an extra round-trip.
credentials: model.credentials,
}
}
@@ -291,19 +271,12 @@ const handleModelSave = async (modelData: any) => {
}
}
// 将前端格式转换为后端格式.
// Three-state api_key semantics (write-only secrets pattern):
// - clearApiKey set → send { clear_api_key: true }
// - user typed a value → send { api_key: "..." }
// - empty (default on edit) → omit api_key → server preserves
// - empty on create → omit api_key → no stored secret
// api_key flows in only on initial create (modelData.apiKey is wiped on
// every edit-mode open). Edits to existing models commit credentials via
// the /credentials subresource (handled inside ModelEditorDialog).
const trimmedApiKey = (modelData.apiKey ?? '').trim()
const apiKeyFields: { api_key?: string; clear_api_key?: boolean } =
modelData.clearApiKey
? { clear_api_key: true }
: trimmedApiKey
? { api_key: trimmedApiKey }
: {}
const apiKeyFields: { api_key?: string } =
!editingModel.value && trimmedApiKey ? { api_key: trimmedApiKey } : {}
const apiModelData: ModelConfig = {
name: modelData.modelName.trim(),
@@ -15,14 +15,9 @@
<!-- Provider List -->
<div v-if="providerEntities.length > 0" class="provider-grid">
<SettingCard
v-for="entity in providerEntities"
:key="entity.id"
:title="entity.name"
:description="entity.description || ''"
:actions="getProviderOptions(entity)"
@action="(value: string) => handleMenuAction({ value }, entity)"
>
<SettingCard v-for="entity in providerEntities" :key="entity.id" :title="entity.name"
:description="entity.description || ''" :actions="getProviderOptions(entity)"
@action="(value: string) => handleMenuAction({ value }, entity)">
<template #tags>
<t-tag theme="primary" size="small" variant="light">
{{ entity.provider }}
@@ -54,12 +49,9 @@
</div>
<!-- Add/Edit Drawer -->
<SettingDrawer
v-model:visible="showAddProviderDialog"
<SettingDrawer v-model:visible="showAddProviderDialog"
:title="editingProvider ? t('webSearchSettings.editProvider') : t('webSearchSettings.addProvider')"
:confirm-loading="saving"
@confirm="saveProvider"
>
:confirm-loading="saving" @confirm="saveProvider">
<t-form ref="formRef" :data="providerForm" label-align="top" class="provider-form">
<t-form-item :label="t('webSearchSettings.providerTypeLabel')" name="provider">
<t-select v-model="providerForm.provider" :disabled="!!editingProvider" @change="onProviderTypeChange">
@@ -75,14 +67,16 @@
</t-form-item>
<t-form-item :label="t('webSearchSettings.providerNameLabel')" name="name">
<t-input v-model="providerForm.name" :placeholder="selectedProviderType?.name || t('webSearchSettings.providerNamePlaceholder')" />
<t-input v-model="providerForm.name"
:placeholder="selectedProviderType?.name || t('webSearchSettings.providerNamePlaceholder')" />
</t-form-item>
<t-form-item :label="t('webSearchSettings.providerDescLabel')" name="description">
<t-input v-model="providerForm.description" :placeholder="t('webSearchSettings.providerDescPlaceholder')" />
</t-form-item>
<template v-if="selectedProviderType?.requires_api_key || selectedProviderType?.requires_engine_id || selectedProviderType?.requires_base_url">
<template
v-if="selectedProviderType?.requires_api_key || selectedProviderType?.requires_engine_id || selectedProviderType?.requires_base_url">
<div class="form-divider"></div>
<div class="credentials-hint" v-if="selectedProviderType?.docs_url">
@@ -92,38 +86,39 @@
</a>
</div>
<t-form-item v-if="selectedProviderType?.requires_base_url" :label="t('webSearchSettings.baseUrlLabel')" name="parameters.base_url">
<t-input
v-model="providerForm.parameters.base_url"
:placeholder="t('webSearchSettings.baseUrlPlaceholder')"
/>
<t-form-item v-if="selectedProviderType?.requires_base_url" :label="t('webSearchSettings.baseUrlLabel')"
name="parameters.base_url">
<t-input v-model="providerForm.parameters.base_url"
:placeholder="t('webSearchSettings.baseUrlPlaceholder')" />
</t-form-item>
<!--
Edit mode: credential is managed by the shared <CredentialResource>
card via the /credentials subresource. Create mode keeps a plain
input so the initial api_key flows in with the first POST.
API key is mandatory for every requires_api_key=true provider
(Bing / Google / Tavily / Ollama / Baidu — see
validateProviderParameters in service/web_search_provider.go),
so the "Remove this credential" affordance shown in the other
three dialogs is intentionally omitted here. Revoking access
means deleting the whole provider row from the list.
(validation in service/web_search_provider.go). The component's
"Remove" action is still available because a user might want to
rotate via remove + re-add, but in normal use they will use
"Replace" instead.
-->
<div v-if="selectedProviderType?.requires_api_key" class="credential-field">
<label class="credential-label">{{ t('webSearchSettings.apiKeyLabel') }}</label>
<t-input
v-model="providerForm.parameters.api_key"
type="password"
:placeholder="apiKeyPlaceholder"
/>
<CredentialResource v-if="editingProvider?.id" :api="credentialApi" :fields="credentialFields"
:meta="credentialMeta" />
<t-input v-else v-model="providerForm.parameters.api_key" type="password"
:placeholder="apiKeyPlaceholder" />
</div>
<t-form-item v-if="selectedProviderType?.requires_engine_id" :label="t('webSearchSettings.engineIdLabel')" name="parameters.engine_id">
<t-form-item v-if="selectedProviderType?.requires_engine_id" :label="t('webSearchSettings.engineIdLabel')"
name="parameters.engine_id">
<t-input v-model="providerForm.parameters.engine_id" :placeholder="t('webSearchSettings.engineIdLabel')" />
</t-form-item>
</template>
<t-form-item v-if="selectedProviderType?.supports_proxy" :label="t('webSearchSettings.proxyUrlLabel')" name="parameters.proxy_url">
<t-input
v-model="providerForm.parameters.proxy_url"
:placeholder="t('webSearchSettings.proxyUrlPlaceholder')"
/>
<t-form-item v-if="selectedProviderType?.supports_proxy" :label="t('webSearchSettings.proxyUrlLabel')"
name="parameters.proxy_url">
<t-input v-model="providerForm.parameters.proxy_url"
:placeholder="t('webSearchSettings.proxyUrlPlaceholder')" />
<template #help>
<span class="switch-help">{{ t('webSearchSettings.proxyUrlHelp') }}</span>
</template>
@@ -142,13 +137,8 @@
</t-form>
<template #footer-left>
<t-button
v-if="selectedProviderType && !isProviderFree(selectedProviderType)"
theme="default"
variant="outline"
:loading="testing"
@click="testConnection"
>
<t-button v-if="selectedProviderType && !isProviderFree(selectedProviderType)" theme="default" variant="outline"
:loading="testing" @click="testConnection">
{{ testing ? t('webSearchSettings.testing') : t('webSearchSettings.testConnection') }}
</t-button>
</template>
@@ -168,11 +158,18 @@ import {
updateWebSearchProvider,
deleteWebSearchProvider as deleteWebSearchProviderAPI,
testWebSearchProvider,
putWebSearchProviderCredentials,
deleteWebSearchProviderCredentialField,
type WebSearchProviderEntity,
type WebSearchProviderTypeInfo,
type WebSearchCredentialField,
} from '@/api/web-search-provider'
import SettingCard from '@/components/settings/SettingCard.vue'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
} from '@/components/credentials/CredentialResource.vue'
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
const { t } = useI18n()
@@ -188,10 +185,6 @@ const testingId = ref<string | null>(null)
const saving = ref(false)
const formRef = ref<any>()
// Fixed placeholder returned by the server for redacted secrets. Must match
// internal/types/secret.go → RedactedSecretPlaceholder.
const REDACTED_PLACEHOLDER = '***'
const providerForm = ref<{
name: string
provider: string
@@ -211,21 +204,31 @@ const selectedProviderType = computed(() => {
return providerTypes.value.find(pt => pt.id === providerForm.value.provider)
})
// "Is an API key currently stored?" is signaled by the server returning the
// fixed REDACTED_PLACEHOLDER in the response. Drive the label badge from this.
const hasExistingApiKey = computed(() => {
return editingProvider.value?.parameters?.api_key === REDACTED_PLACEHOLDER
// Create-mode placeholder (edit mode replaces the input with
// <CredentialResource>, which has its own placeholder).
const apiKeyPlaceholder = computed(() => t('webSearchSettings.apiKeyPlaceholder'))
const credentialFields = computed<CredentialFieldDef<WebSearchCredentialField>[]>(() => [
{ key: 'api_key', label: t('webSearchSettings.apiKeyLabel') as string },
])
const credentialApi = computed<CredentialResourceApi<WebSearchCredentialField>>(() => {
const id = editingProvider.value?.id ?? ''
return {
save: async (patch) => {
const meta = await putWebSearchProviderCredentials(id, patch)
return meta.fields
},
remove: async (field) => {
await deleteWebSearchProviderCredentialField(id, field)
},
}
})
// In edit mode with a stored key, swap the placeholder to the shared
// "bullets + Enter new value to replace" hint. Otherwise fall back to the
// provider-specific placeholder (creation) or the "leave blank to keep"
// copy used when no key is stored yet.
const apiKeyPlaceholder = computed(() => {
if (!editingProvider.value) return t('webSearchSettings.apiKeyPlaceholder')
return hasExistingApiKey.value
? t('secret.storedPlaceholder')
: t('webSearchSettings.apiKeyUnchanged')
// Initial configured? from the main provider response (embedded server-side
// in dto.WebSearchProviderResponse.Credentials).
const credentialMeta = computed(() => editingProvider.value?.credentials ?? {
api_key: { configured: false },
})
const isProviderFree = (providerType: WebSearchProviderTypeInfo) => {
@@ -305,18 +308,15 @@ const saveProvider = async () => {
saving.value = true
try {
// Build the parameters payload using two-state semantics:
// - user typed a value → send api_key (replaces stored)
// - empty + editing → omit api_key (server preserves stored value)
// - empty + creating → omit api_key (no secret to store yet)
// No clear path: every requires_api_key provider mandates a value, so
// "revoke" means deleting the provider row, not zeroing the key.
// Build the parameters payload. api_key only flows in on initial
// create — edit mode commits credentials through <CredentialResource>
// (a dedicated PUT /credentials call) before this save runs.
const paramsOut: WebSearchProviderEntity['parameters'] = {
engine_id: providerForm.value.parameters.engine_id,
base_url: providerForm.value.parameters.base_url,
proxy_url: providerForm.value.parameters.proxy_url,
}
if (providerForm.value.parameters.api_key) {
if (!editingProvider.value && providerForm.value.parameters.api_key) {
paramsOut.api_key = providerForm.value.parameters.api_key
}
@@ -1,28 +1,16 @@
<template>
<SettingDrawer
:visible="dialogVisible"
<SettingDrawer :visible="dialogVisible"
:title="mode === 'add' ? t('mcpServiceDialog.addTitle') : t('mcpServiceDialog.editTitle')"
:confirm-loading="submitting"
@update:visible="(v: boolean) => dialogVisible = v"
@confirm="handleSubmit"
@cancel="handleClose"
>
<t-form
ref="formRef"
:data="formData"
:rules="rules"
label-align="top"
>
:confirm-loading="submitting" @update:visible="(v: boolean) => dialogVisible = v" @confirm="handleSubmit"
@cancel="handleClose">
<t-form ref="formRef" :data="formData" :rules="rules" label-align="top">
<t-form-item :label="t('mcpServiceDialog.name')" name="name">
<t-input v-model="formData.name" :placeholder="t('mcpServiceDialog.namePlaceholder')" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.description')" name="description">
<t-textarea
v-model="formData.description"
:autosize="{ minRows: 3, maxRows: 5 }"
:placeholder="t('mcpServiceDialog.descriptionPlaceholder')"
/>
<t-textarea v-model="formData.description" :autosize="{ minRows: 3, maxRows: 5 }"
:placeholder="t('mcpServiceDialog.descriptionPlaceholder')" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.transportType')" name="transport_type">
@@ -34,10 +22,7 @@
</t-form-item>
<!-- URL for SSE/HTTP Streamable -->
<t-form-item
:label="t('mcpServiceDialog.serviceUrl')"
name="url"
>
<t-form-item :label="t('mcpServiceDialog.serviceUrl')" name="url">
<t-input v-model="formData.url" :placeholder="t('mcpServiceDialog.serviceUrlPlaceholder')" />
</t-form-item>
@@ -51,73 +36,40 @@
<t-collapse :default-value="[]">
<t-collapse-panel :header="t('mcpServiceDialog.authConfig')" value="auth">
<!--
Credential fields follow the "write-only secrets" pattern.
When a value is currently stored on the server the placeholder
is swapped for a bullet run + "Enter new value to replace"
hint, so the visual "something is there" signal is carried by
the input itself rather than by a separate Set/Not-set badge.
The Remove checkbox still offers an explicit clear path.
-->
<div class="credential-field">
<label class="credential-label">{{ t('mcpServiceDialog.apiKey') }}</label>
<t-input
v-model="formData.auth_config.api_key"
type="password"
:disabled="clearApiKey"
:placeholder="apiKeyPlaceholder"
/>
<t-checkbox
v-if="mode === 'edit' && hasExistingApiKey"
v-model="clearApiKey"
class="clear-credential"
>
{{ t('secret.clearHint') }}
</t-checkbox>
</div>
Edit mode: credentials live behind a dedicated subresource. The
CredentialResource component drives configured/unconfigured/editing
state per field and commits each change to /credentials directly,
decoupling credential edits from the surrounding form.
<div class="credential-field">
<label class="credential-label">{{ t('mcpServiceDialog.bearerToken') }}</label>
<t-input
v-model="formData.auth_config.token"
type="password"
:disabled="clearToken"
:placeholder="tokenPlaceholder"
/>
<t-checkbox
v-if="mode === 'edit' && hasExistingToken"
v-model="clearToken"
class="clear-credential"
>
{{ t('secret.clearHint') }}
</t-checkbox>
</div>
Add mode: the resource doesn't exist yet, so we accept the initial
credentials as plain inputs and POST them together with the rest of
the service in handleSubmit. From the second save onwards, the
edit-mode path takes over.
-->
<CredentialResource v-if="mode === 'edit' && props.service?.id" :api="credentialApi"
:fields="credentialFields" :meta="credentialMeta" />
<template v-else>
<t-form-item :label="t('mcpServiceDialog.apiKey')">
<t-input v-model="formData.auth_config.api_key" type="password"
:placeholder="t('mcpServiceDialog.optional')" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.bearerToken')">
<t-input v-model="formData.auth_config.token" type="password"
:placeholder="t('mcpServiceDialog.optional')" />
</t-form-item>
</template>
</t-collapse-panel>
<!-- Advanced Config -->
<t-collapse-panel :header="t('mcpServiceDialog.advancedConfig')" value="advanced">
<t-form-item :label="t('mcpServiceDialog.timeoutSec')">
<t-input-number
v-model="formData.advanced_config.timeout"
:min="1"
:max="300"
placeholder="30"
/>
<t-input-number v-model="formData.advanced_config.timeout" :min="1" :max="300" placeholder="30" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.retryCount')">
<t-input-number
v-model="formData.advanced_config.retry_count"
:min="0"
:max="10"
placeholder="3"
/>
<t-input-number v-model="formData.advanced_config.retry_count" :min="0" :max="10" placeholder="3" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.retryDelaySec')">
<t-input-number
v-model="formData.advanced_config.retry_delay"
:min="0"
:max="60"
placeholder="1"
/>
<t-input-number v-model="formData.advanced_config.retry_delay" :min="0" :max="60" placeholder="1" />
</t-form-item>
</t-collapse-panel>
</t-collapse>
@@ -127,15 +79,22 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
createMCPService,
updateMCPService,
type MCPService
putMCPCredentials,
deleteMCPCredentialField,
type MCPService,
type McpCredentialField,
} from '@/api/mcp-service'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
} from '@/components/credentials/CredentialResource.vue'
interface Props {
visible: boolean
@@ -155,10 +114,6 @@ const formRef = ref<FormInstanceFunctions>()
const submitting = ref(false)
const { t } = useI18n()
// Fixed placeholder returned by the server for sensitive fields whose values
// are withheld. Must match internal/types/secret.go → RedactedSecretPlaceholder.
const REDACTED_PLACEHOLDER = '***'
const formData = ref({
name: '',
description: '',
@@ -166,44 +121,48 @@ const formData = ref({
transport_type: 'sse' as 'sse' | 'http-streamable',
url: '',
auth_config: {
// Only used in add-mode; in edit-mode the CredentialResource owns these.
api_key: '',
token: ''
token: '',
},
advanced_config: {
timeout: 30,
retry_count: 3,
retry_delay: 1
retry_delay: 1,
},
})
// Field metadata for the credential subresource. Keep label keys local to
// MCP so other resources don't accidentally inherit "API Key" / "Bearer
// Token" labels via the shared component.
const credentialFields = computed<CredentialFieldDef<McpCredentialField>[]>(() => [
{ key: 'api_key', label: t('mcpServiceDialog.apiKey') },
{ key: 'token', label: t('mcpServiceDialog.bearerToken') },
])
// Adapter that binds the generic CredentialResource component to the MCP
// credential endpoints. Recomputed if the user opens a different service.
const credentialApi = computed<CredentialResourceApi<McpCredentialField>>(() => {
const id = props.service?.id ?? ''
return {
save: async (patch) => {
const meta = await putMCPCredentials(id, patch)
return meta.fields
},
remove: async (field) => {
await deleteMCPCredentialField(id, field)
},
}
})
// Explicit "remove stored credential" flags. Reset to false on every open/reset.
const clearApiKey = ref(false)
const clearToken = ref(false)
// "Is a credential currently stored?" is signaled by the server returning the
// fixed REDACTED_PLACEHOLDER instead of an empty string. Drive the label
// badge and placeholder hint from this signal.
const hasExistingApiKey = computed(
() => props.service?.auth_config?.api_key === REDACTED_PLACEHOLDER
)
const hasExistingToken = computed(
() => props.service?.auth_config?.token === REDACTED_PLACEHOLDER
)
// Placeholders swap to the shared "stored credential" hint when the server
// signals a value is present (parameters come back as '***'). Otherwise
// the field is genuinely empty and we fall through to the normal
// "Optional" placeholder that appears in add mode too.
const apiKeyPlaceholder = computed(() =>
hasExistingApiKey.value
? t('secret.storedPlaceholder')
: t('mcpServiceDialog.optional')
)
const tokenPlaceholder = computed(() =>
hasExistingToken.value
? t('secret.storedPlaceholder')
: t('mcpServiceDialog.optional')
)
// Initial "configured?" metadata read from the main service response. The
// component reads this on mount; subsequent state changes after save/remove
// are tracked locally by the component itself (and re-derived from this
// whenever the parent reloads the service).
const credentialMeta = computed(() => props.service?.credentials ?? {
api_key: { configured: false },
token: { configured: false },
})
const rules: Record<string, FormRule[]> = {
name: [{ required: true, message: t('mcpServiceDialog.rules.nameRequired') as string, type: 'error' }],
@@ -214,27 +173,22 @@ const rules: Record<string, FormRule[]> = {
if (!val || val.trim() === '') {
return { result: false, message: t('mcpServiceDialog.rules.urlRequired') as string, type: 'error' }
}
// Basic URL validation
try {
new URL(val)
return { result: true, message: '', type: 'success' }
} catch {
return { result: false, message: t('mcpServiceDialog.rules.urlInvalid') as string, type: 'error' }
}
}
}
]
},
},
],
}
const dialogVisible = computed({
get: () => props.visible,
set: (value) => emit('update:visible', value)
set: (value) => emit('update:visible', value),
})
// Reset form function — defined before watch to avoid hoisting issues.
// Sensitive fields are always blank: the watch below does not copy the
// server-provided redacted placeholder into formData, and clear flags are
// reset so a reopen does not carry over an aborted deletion intent.
const resetForm = () => {
formData.value = {
name: '',
@@ -242,31 +196,16 @@ const resetForm = () => {
enabled: true,
transport_type: 'sse',
url: '',
auth_config: {
api_key: '',
token: ''
},
advanced_config: {
timeout: 30,
retry_count: 3,
retry_delay: 1
}
auth_config: { api_key: '', token: '' },
advanced_config: { timeout: 30, retry_count: 3, retry_delay: 1 },
}
clearApiKey.value = false
clearToken.value = false
formRef.value?.clearValidate()
}
// Watch service prop to initialize form.
// Sensitive fields (api_key, token) are NEVER pre-filled from the server
// response — even when the server returns '***' indicating a stored value.
// This keeps the "non-empty means user typed it" invariant that the submit
// logic relies on to decide between preserve and replace.
watch(
() => props.service,
(service) => {
if (service) {
// Note: stdio transport_type will fall back to 'sse' as stdio is disabled
const transportType = service.transport_type === 'stdio' ? 'sse' : (service.transport_type || 'sse')
formData.value = {
name: service.name || '',
@@ -274,76 +213,28 @@ watch(
enabled: service.enabled ?? true,
transport_type: transportType as 'sse' | 'http-streamable',
url: service.url || '',
auth_config: {
api_key: '',
token: ''
},
// Credentials are owned by CredentialResource in edit mode, but reset
// the local state too so a switch to add-mode starts clean.
auth_config: { api_key: '', token: '' },
advanced_config: {
timeout: service.advanced_config?.timeout || 30,
retry_count: service.advanced_config?.retry_count || 3,
retry_delay: service.advanced_config?.retry_delay || 1
}
retry_delay: service.advanced_config?.retry_delay || 1,
},
}
clearApiKey.value = false
clearToken.value = false
} else {
resetForm()
}
},
{ immediate: true }
{ immediate: true },
)
// Prompt the user before irrevocable credential removal.
const confirmClearIfNeeded = (): Promise<boolean> => {
if (!clearApiKey.value && !clearToken.value) return Promise.resolve(true)
return new Promise((resolve) => {
const d = DialogPlugin.confirm({
header: t('secret.confirmClearTitle'),
body: t('secret.confirmClearBody'),
confirmBtn: { content: t('common.confirm'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: () => {
d.hide()
resolve(true)
},
onCancel: () => {
d.hide()
resolve(false)
},
onClose: () => {
d.hide()
resolve(false)
}
})
})
}
// Handle submit — three-state auth_config payload:
// - clear flag set → send { clear_api_key: true } / { clear_token: true }
// - user typed a value → send the value
// - otherwise → omit the field, server preserves the stored value
// If auth_config would be empty, omit the key entirely.
const handleSubmit = async () => {
const valid = await formRef.value?.validate()
if (!valid) return
const proceed = await confirmClearIfNeeded()
if (!proceed) return
submitting.value = true
try {
const authPayload: Record<string, unknown> = {}
if (clearApiKey.value) {
authPayload.clear_api_key = true
} else if (formData.value.auth_config.api_key) {
authPayload.api_key = formData.value.auth_config.api_key
}
if (clearToken.value) {
authPayload.clear_token = true
} else if (formData.value.auth_config.token) {
authPayload.token = formData.value.auth_config.token
}
const data: Partial<MCPService> = {
name: formData.value.name,
description: formData.value.description,
@@ -352,14 +243,19 @@ const handleSubmit = async () => {
advanced_config: formData.value.advanced_config,
url: formData.value.url || undefined,
}
if (Object.keys(authPayload).length > 0) {
data.auth_config = authPayload as MCPService['auth_config']
}
if (props.mode === 'add') {
// Initial credentials go along with the first POST. Subsequent edits
// route through the /credentials subresource.
const initialAuth: NonNullable<MCPService['auth_config']> = {}
if (formData.value.auth_config.api_key) initialAuth.api_key = formData.value.auth_config.api_key
if (formData.value.auth_config.token) initialAuth.token = formData.value.auth_config.token
if (Object.keys(initialAuth).length > 0) data.auth_config = initialAuth
await createMCPService(data)
MessagePlugin.success(t('mcpServiceDialog.toasts.created'))
} else {
// Edit-mode: never send credential fields here. CredentialResource
// already committed any changes through the dedicated endpoint.
await updateMCPService(props.service!.id, data)
MessagePlugin.success(t('mcpServiceDialog.toasts.updated'))
}
@@ -367,7 +263,9 @@ const handleSubmit = async () => {
emit('success')
} catch (error) {
MessagePlugin.error(
props.mode === 'add' ? (t('mcpServiceDialog.toasts.createFailed') as string) : (t('mcpServiceDialog.toasts.updateFailed') as string)
props.mode === 'add'
? (t('mcpServiceDialog.toasts.createFailed') as string)
: (t('mcpServiceDialog.toasts.updateFailed') as string),
)
console.error('Failed to save MCP service:', error)
} finally {
@@ -375,7 +273,6 @@ const handleSubmit = async () => {
}
}
// Handle close
const handleClose = () => {
dialogVisible.value = false
}
@@ -383,37 +280,4 @@ const handleClose = () => {
<style scoped lang="less">
/* Stdio-related styles removed as stdio transport is disabled for security reasons */
/**
* Credential field: stacks the label row, the password input, and the
* optional "Remove this credential" checkbox vertically. Replaces the
* t-form-item-based layout for the auth-config fields so the inline badge
* doesn't get clipped by the form's 120px label-width and the clear
* checkbox doesn't sit alongside the input.
*/
.credential-field {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.credential-label {
display: block;
font-size: 14px;
color: var(--td-text-color-primary);
line-height: 22px;
}
.clear-credential {
:deep(.t-checkbox__label) {
color: var(--td-error-color);
font-size: 13px;
}
}
</style>