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:
@@ -17,6 +17,9 @@ export interface DataSource {
|
||||
last_sync_at: string | null
|
||||
last_sync_result: any
|
||||
error_message: string
|
||||
// Single-field "credentials" map from the main response — DataSource
|
||||
// credentials are a per-connector atomic set.
|
||||
credentials?: { credentials: { configured: boolean } }
|
||||
created_at: string
|
||||
updated_at: string
|
||||
latest_sync_log?: SyncLog
|
||||
@@ -111,3 +114,27 @@ export function resumeDataSource(id: string) {
|
||||
export function getSyncLogs(id: string, limit = 20, offset = 0) {
|
||||
return get(`/api/v1/datasource/${id}/logs?limit=${limit}&offset=${offset}`)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Data source credential subresource. Unlike the other three resources,
|
||||
// DataSource exposes a single logical field "credentials" because connector
|
||||
// auth is a per-connector atomic map. See internal/handler/dto/datasource.go.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export interface DataSourceCredentialsResponse {
|
||||
fields: {
|
||||
credentials: { configured: boolean }
|
||||
}
|
||||
}
|
||||
|
||||
export async function putDataSourceCredentials(
|
||||
id: string,
|
||||
credentials: Record<string, unknown>,
|
||||
): Promise<DataSourceCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/datasource/${id}/credentials`, { credentials })
|
||||
return (response.data ?? response) as DataSourceCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteDataSourceCredentials(id: string): Promise<void> {
|
||||
await del(`/api/v1/datasource/${id}/credentials/credentials`)
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ export interface MCPService {
|
||||
url?: string // Optional: required for SSE/HTTP Streamable
|
||||
headers?: Record<string, string>
|
||||
auth_config?: {
|
||||
// Secret fields (api_key, token) are NEVER returned by the server in
|
||||
// this shape — they live behind the /credentials subresource. The
|
||||
// optional-property typing remains so create-mode payloads can still
|
||||
// carry them in the initial POST body.
|
||||
api_key?: string
|
||||
token?: string
|
||||
custom_headers?: Record<string, string>
|
||||
// Write-only flags — set to true in Update requests to explicitly remove
|
||||
// the corresponding credential. The server never returns these fields.
|
||||
clear_api_key?: boolean
|
||||
clear_token?: boolean
|
||||
}
|
||||
advanced_config?: {
|
||||
timeout?: number
|
||||
@@ -29,6 +29,10 @@ export interface MCPService {
|
||||
}
|
||||
env_vars?: Record<string, string> // Environment variables for stdio transport
|
||||
is_builtin?: boolean // Whether this is a builtin MCP service
|
||||
// Per-field "configured?" map embedded on the main response (server-side
|
||||
// dto.MCPServiceResponse.Credentials). Drives the CredentialResource card
|
||||
// without a follow-up GET. Absent for builtin services.
|
||||
credentials?: Record<McpCredentialField, CredentialFieldMetadata>
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@@ -127,6 +131,41 @@ export async function setMCPToolApproval(serviceId: string, toolName: string, re
|
||||
})
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Credential subresource (issue #988 follow-up).
|
||||
//
|
||||
// Secrets travel through a dedicated /credentials endpoint instead of the
|
||||
// main MCP PUT body. "Is this configured?" metadata is embedded on the main
|
||||
// MCPService response (MCPService.credentials), so there is no GET on this
|
||||
// endpoint — only PUT (write) and DELETE (clear). Both trigger an MCP
|
||||
// client reconnect server-side.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type McpCredentialField = 'api_key' | 'token'
|
||||
|
||||
export interface CredentialFieldMetadata {
|
||||
configured: boolean
|
||||
}
|
||||
|
||||
export interface McpCredentialsResponse {
|
||||
fields: Record<McpCredentialField, CredentialFieldMetadata>
|
||||
}
|
||||
|
||||
export async function putMCPCredentials(
|
||||
serviceId: string,
|
||||
body: Partial<Record<McpCredentialField, string>>
|
||||
): Promise<McpCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/mcp-services/${serviceId}/credentials`, body)
|
||||
return (response.data ?? response) as McpCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteMCPCredentialField(
|
||||
serviceId: string,
|
||||
field: McpCredentialField
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${serviceId}/credentials/${field}`)
|
||||
}
|
||||
|
||||
export async function resolveToolApproval(
|
||||
pendingId: string,
|
||||
body: { decision: 'approve' | 'reject'; modified_args?: Record<string, unknown>; reason?: string }
|
||||
|
||||
@@ -27,15 +27,18 @@ export interface ModelConfig {
|
||||
custom_headers?: Record<string, string>;
|
||||
supports_vision?: boolean; // Whether the model accepts image/multimodal input
|
||||
app_id?: string;
|
||||
// Secret fields (api_key, app_secret) are never returned by the server in
|
||||
// this shape — they live behind the /credentials subresource. They are
|
||||
// kept on the type so create-mode payloads can still carry them in the
|
||||
// initial POST body.
|
||||
app_secret?: string;
|
||||
// Write-only flags — set to true in Update requests to explicitly remove
|
||||
// the corresponding credential. The server never returns these fields.
|
||||
clear_api_key?: boolean;
|
||||
clear_app_secret?: boolean;
|
||||
};
|
||||
is_default?: boolean;
|
||||
is_builtin?: boolean;
|
||||
status?: string;
|
||||
// Per-field configured? metadata from the main response. Absent for
|
||||
// builtin models.
|
||||
credentials?: Record<ModelCredentialField, { configured: boolean }>;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
deleted_at?: string | null;
|
||||
@@ -135,6 +138,32 @@ export function deleteModel(id: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Model credential subresource. See mcp-service.ts for the matching MCP API
|
||||
// shape and the design notes in internal/handler/dto/mcp.go.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type ModelCredentialField = 'api_key' | 'app_secret'
|
||||
|
||||
export interface ModelCredentialsResponse {
|
||||
fields: Record<ModelCredentialField, { configured: boolean }>
|
||||
}
|
||||
|
||||
export async function putModelCredentials(
|
||||
id: string,
|
||||
body: Partial<Record<ModelCredentialField, string>>,
|
||||
): Promise<ModelCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/models/${id}/credentials`, body)
|
||||
return (response.data ?? response) as ModelCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteModelCredentialField(
|
||||
id: string,
|
||||
field: ModelCredentialField,
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/models/${id}/credentials/${field}`)
|
||||
}
|
||||
|
||||
export interface InitializeWeKnoraCloudRequest {
|
||||
app_id: string
|
||||
app_secret: string
|
||||
|
||||
@@ -8,16 +8,18 @@ export interface WebSearchProviderEntity {
|
||||
provider: 'bing' | 'google' | 'duckduckgo' | 'tavily' | 'ollama' | 'baidu' | 'searxng'
|
||||
description?: string
|
||||
parameters: {
|
||||
// api_key is never returned by the server in this shape; it lives behind
|
||||
// the /credentials subresource. Kept on the type so the initial create
|
||||
// POST can still include it.
|
||||
api_key?: string
|
||||
engine_id?: string
|
||||
base_url?: string
|
||||
proxy_url?: string
|
||||
extra_config?: Record<string, string>
|
||||
// Write-only flag — set to true in Update requests to explicitly remove
|
||||
// the stored API key. The server never returns this field.
|
||||
clear_api_key?: boolean
|
||||
}
|
||||
is_default?: boolean
|
||||
// Per-field configured? metadata from the main response.
|
||||
credentials?: Record<WebSearchCredentialField, { configured: boolean }>
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@@ -69,6 +71,31 @@ export function listWebSearchProviderTypes(): Promise<WebSearchProviderTypeInfo[
|
||||
})
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Web search provider credential subresource.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export type WebSearchCredentialField = 'api_key'
|
||||
|
||||
export interface WebSearchCredentialsResponse {
|
||||
fields: Record<WebSearchCredentialField, { configured: boolean }>
|
||||
}
|
||||
|
||||
export async function putWebSearchProviderCredentials(
|
||||
id: string,
|
||||
body: Partial<Record<WebSearchCredentialField, string>>,
|
||||
): Promise<WebSearchCredentialsResponse> {
|
||||
const response: any = await put(`/api/v1/web-search-providers/${id}/credentials`, body)
|
||||
return (response.data ?? response) as WebSearchCredentialsResponse
|
||||
}
|
||||
|
||||
export async function deleteWebSearchProviderCredentialField(
|
||||
id: string,
|
||||
field: WebSearchCredentialField,
|
||||
): Promise<void> {
|
||||
await del(`/api/v1/web-search-providers/${id}/credentials/${field}`)
|
||||
}
|
||||
|
||||
// Test a web search provider connection.
|
||||
// If id is provided, tests the existing saved provider.
|
||||
// If data is provided, tests with raw credentials (no persistence).
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,293 @@
|
||||
<!--
|
||||
CredentialResource — per-field "configured / unconfigured / editing" card.
|
||||
|
||||
Why this component exists:
|
||||
The previous UX (PR #990) showed a password input pre-filled with a redacted
|
||||
placeholder plus a red "Remove this credential" checkbox below it. That
|
||||
conflated three distinct user intents (preserve / replace / clear) into a
|
||||
single form field, and bundled credential changes with unrelated config
|
||||
edits in the same submit. Users could accidentally wipe a working key by
|
||||
toggling the wrong checkbox.
|
||||
|
||||
This component splits credentials out as an independent resource:
|
||||
- Read-only "configured" badge by default, derived from the `meta` prop.
|
||||
- "Replace" expands an input + Save/Cancel; commit is an explicit
|
||||
PUT to the credential subresource (no main-form submit needed).
|
||||
- "Remove" pops a danger-themed confirmation and on confirm calls DELETE
|
||||
immediately. No "save form to apply" intermediate state.
|
||||
|
||||
`meta` is the source of truth and comes from the parent resource's main
|
||||
GET response (`<resource>.credentials` on every DTO) — there is no
|
||||
dedicated GET /credentials endpoint. After a successful save/remove the
|
||||
component derives the new local state from the save's return value (or,
|
||||
for remove, by setting the field to unconfigured) and emits 'changed' so
|
||||
the parent can re-fetch the main resource if it cares about anything
|
||||
else that depends on credential state.
|
||||
-->
|
||||
<template>
|
||||
<div class="credential-resource">
|
||||
<div v-for="field in fields" :key="field.key" class="credential-row">
|
||||
<!-- Configured: read-only badge + actions -->
|
||||
<template v-if="stateOf(field.key) === 'configured'">
|
||||
<div class="credential-summary">
|
||||
<t-icon name="check-circle-filled" class="status-icon success" />
|
||||
<div class="credential-meta">
|
||||
<div class="credential-label">{{ field.label }}</div>
|
||||
<div class="credential-sub">{{ t('credential.configured') }}</div>
|
||||
</div>
|
||||
<div class="credential-actions">
|
||||
<t-button size="small" variant="outline" @click="enterEdit(field.key)">
|
||||
{{ t('credential.update') }}
|
||||
</t-button>
|
||||
<t-button size="small" variant="outline" theme="danger" :loading="busy[field.key] === 'remove'"
|
||||
@click="onRemove(field)">
|
||||
{{ t('credential.remove') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Unconfigured: collapsed prompt + "Configure" -->
|
||||
<template v-else-if="stateOf(field.key) === 'unconfigured'">
|
||||
<div class="credential-summary">
|
||||
<t-icon name="info-circle" class="status-icon muted" />
|
||||
<div class="credential-meta">
|
||||
<div class="credential-label">{{ field.label }}</div>
|
||||
<div class="credential-sub">{{ t('credential.unconfigured') }}</div>
|
||||
</div>
|
||||
<div class="credential-actions">
|
||||
<t-button size="small" variant="outline" @click="enterEdit(field.key)">
|
||||
{{ t('credential.configure') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Editing: inline input + Save / Cancel -->
|
||||
<template v-else>
|
||||
<div class="credential-edit">
|
||||
<div class="credential-label">{{ field.label }}</div>
|
||||
<t-input v-model="drafts[field.key]" type="password"
|
||||
:placeholder="field.placeholder ?? t('credential.inputPlaceholder')" :autocomplete="'new-password'"
|
||||
@keydown.enter.prevent="onSave(field)" />
|
||||
<div class="credential-edit-actions">
|
||||
<t-button size="small" variant="outline" @click="cancelEdit(field.key)">
|
||||
{{ t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button size="small" theme="primary" :loading="busy[field.key] === 'save'" :disabled="!drafts[field.key]"
|
||||
@click="onSave(field)">
|
||||
{{ t('common.save') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" generic="K extends string">
|
||||
import { ref, reactive, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
|
||||
export interface CredentialFieldDef<K extends string = string> {
|
||||
key: K
|
||||
label: string
|
||||
// Optional connector-specific placeholder shown only when the input is
|
||||
// visible (e.g. "ntn_xxxx" for Notion). Defaults to a generic "Enter value".
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
export interface CredentialResourceApi<K extends string = string> {
|
||||
// PUT /credentials — body keyed by field name, value is the new secret.
|
||||
// Returns the updated per-field configured map.
|
||||
save: (patch: Partial<Record<K, string>>) => Promise<Record<K, { configured: boolean }>>
|
||||
// DELETE /credentials/:field
|
||||
remove: (field: K) => Promise<void>
|
||||
}
|
||||
|
||||
interface Props {
|
||||
fields: CredentialFieldDef<K>[]
|
||||
api: CredentialResourceApi<K>
|
||||
// Initial per-field "configured?" map, sourced from the parent resource's
|
||||
// main GET response. The component reads it on first render and after
|
||||
// every reset; subsequent state transitions are tracked locally.
|
||||
meta: Record<K, { configured: boolean }>
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
// Fires after every successful save or remove so the parent can refresh
|
||||
// any derived view (e.g. badges that depend on credential state) or just
|
||||
// reload the main resource to keep `meta` in sync.
|
||||
(e: 'changed'): void
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
const { t } = useI18n()
|
||||
|
||||
type State = 'configured' | 'unconfigured' | 'editing'
|
||||
// Local view state per field. Source of truth is props.meta, but we track
|
||||
// the editing state and any locally-applied save/remove transitions here so
|
||||
// the UI doesn't snap back when the parent re-renders before re-fetching.
|
||||
const states = reactive<Record<string, State>>({})
|
||||
const drafts = reactive<Record<string, string>>({})
|
||||
const busy = reactive<Record<string, 'save' | 'remove' | null>>({})
|
||||
|
||||
function deriveStatesFromMeta(meta: Record<string, { configured: boolean }>) {
|
||||
for (const f of props.fields) {
|
||||
// Preserve in-progress edits across parent re-renders — `meta` describes
|
||||
// server state, the editing flag is user intent.
|
||||
if (states[f.key] === 'editing') continue
|
||||
states[f.key] = meta[f.key]?.configured ? 'configured' : 'unconfigured'
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize from the first meta snapshot, and re-derive whenever the parent
|
||||
// passes a new one (after a main-resource refresh). watch with immediate:true
|
||||
// covers both cases in one place.
|
||||
watch(
|
||||
() => props.meta,
|
||||
(m) => deriveStatesFromMeta(m ?? ({} as Record<K, { configured: boolean }>)),
|
||||
{ immediate: true, deep: true },
|
||||
)
|
||||
|
||||
// If the parent swaps the api (e.g. user opens a different resource), drop
|
||||
// transient state. props.meta will follow and re-init via the watch above.
|
||||
watch(() => props.api, () => {
|
||||
for (const k of Object.keys(states)) delete states[k]
|
||||
for (const k of Object.keys(drafts)) delete drafts[k]
|
||||
})
|
||||
|
||||
function stateOf(key: string): State {
|
||||
return states[key] ?? 'unconfigured'
|
||||
}
|
||||
|
||||
function enterEdit(key: string) {
|
||||
drafts[key] = ''
|
||||
states[key] = 'editing'
|
||||
}
|
||||
|
||||
// Cancel returns directly to whatever the parent told us via props.meta —
|
||||
// no async re-fetch needed, and no risk of staying stuck in 'editing'
|
||||
// because the previous implementation's refresh was a no-op when state
|
||||
// was already 'editing'.
|
||||
function cancelEdit(key: string) {
|
||||
drafts[key] = ''
|
||||
states[key] = props.meta?.[key as K]?.configured ? 'configured' : 'unconfigured'
|
||||
}
|
||||
|
||||
async function onSave(field: CredentialFieldDef) {
|
||||
const value = drafts[field.key]
|
||||
if (!value) return
|
||||
busy[field.key] = 'save'
|
||||
try {
|
||||
// Apply the save's returned metadata locally so the card flips to
|
||||
// 'configured' immediately. Skip the editing-preserve guard since this
|
||||
// particular field just finished editing.
|
||||
const updated = await props.api.save({ [field.key]: value } as Partial<Record<K, string>>)
|
||||
for (const f of props.fields) {
|
||||
if (f.key === field.key) continue
|
||||
if (states[f.key] === 'editing') continue
|
||||
states[f.key] = updated[f.key as K]?.configured ? 'configured' : 'unconfigured'
|
||||
}
|
||||
states[field.key] = updated[field.key as K]?.configured ? 'configured' : 'unconfigured'
|
||||
drafts[field.key] = ''
|
||||
MessagePlugin.success(t('credential.savedToast'))
|
||||
emit('changed')
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.message || t('credential.saveFailed'))
|
||||
} finally {
|
||||
busy[field.key] = null
|
||||
}
|
||||
}
|
||||
|
||||
// Remove is a single-click action: skip the modal confirm dialog and just
|
||||
// do it, with a toast for feedback. Rationale: the secret is irrecoverable
|
||||
// from the client side regardless of whether we confirm (we never had the
|
||||
// plaintext), so a modal adds friction without adding safety — re-typing
|
||||
// the secret is the recovery path either way. The danger-themed "Remove"
|
||||
// button itself already serves as a visual deterrent against misclicks.
|
||||
async function onRemove(field: CredentialFieldDef) {
|
||||
busy[field.key] = 'remove'
|
||||
try {
|
||||
await props.api.remove(field.key as K)
|
||||
states[field.key] = 'unconfigured'
|
||||
MessagePlugin.success(t('credential.removedToast'))
|
||||
emit('changed')
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.message || t('credential.removeFailed'))
|
||||
} finally {
|
||||
busy[field.key] = null
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.credential-resource {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.credential-row {
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
padding: 12px 14px;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.credential-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.credential-meta {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.credential-label {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.credential-sub {
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.credential-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-icon {
|
||||
font-size: 18px;
|
||||
flex-shrink: 0;
|
||||
|
||||
&.success {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
&.muted {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.credential-edit {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.credential-edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -4119,6 +4119,7 @@ export default {
|
||||
connected: 'Connected',
|
||||
connectionFailed: 'Connection failed',
|
||||
isRequired: 'is required',
|
||||
credentialsLabel: 'credentials',
|
||||
resourceHint: 'Select the spaces or folders to sync',
|
||||
untitled: 'Untitled',
|
||||
resourceLoadFailed: 'Failed to load resources',
|
||||
@@ -4284,15 +4285,22 @@ export default {
|
||||
createdAt: 'Created at',
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
// Placeholder shown inside a credential input when a value is currently
|
||||
// stored server-side. The bullet run doubles as a visual "something is
|
||||
// there" cue (matching how the password type renders dots); the
|
||||
// parenthetical tells the user what typing will do.
|
||||
storedPlaceholder: '•••••••• (Enter new value to replace)',
|
||||
clearHint: 'Remove this credential',
|
||||
confirmClearTitle: 'Confirm credential removal',
|
||||
confirmClearBody:
|
||||
'This permanently deletes the stored credential. Integrations using it will stop working. Continue?',
|
||||
// Shared credential resource UI (CredentialResource.vue). Keep keys
|
||||
// generic so the same component can drive MCP / Model / WebSearch /
|
||||
// DataSource credential surfaces without per-resource overrides.
|
||||
credential: {
|
||||
configured: 'Configured',
|
||||
unconfigured: 'Not configured',
|
||||
configure: 'Configure',
|
||||
update: 'Replace',
|
||||
remove: 'Remove',
|
||||
inputPlaceholder: 'Enter value',
|
||||
savedToast: 'Credential saved',
|
||||
saveFailed: 'Failed to save credential',
|
||||
removedToast: 'Credential removed',
|
||||
removeFailed: 'Failed to remove credential',
|
||||
confirmRemoveTitle: 'Remove {field}?',
|
||||
confirmRemoveBody:
|
||||
'This permanently deletes the stored credential. Integrations using it will stop working until you configure a new value.',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4183,6 +4183,7 @@ export default {
|
||||
connected: "연결됨",
|
||||
connectionFailed: "연결 실패",
|
||||
isRequired: "은(는) 필수입니다",
|
||||
credentialsLabel: "자격 증명",
|
||||
resourceHint: "동기화할 공간/폴더를 선택하세요",
|
||||
untitled: "제목 없음",
|
||||
resourceLoadFailed: "리소스 목록 로드 실패",
|
||||
@@ -4347,11 +4348,19 @@ export default {
|
||||
createdAt: "생성 시각",
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: "•••••••• (새 값을 입력하면 교체됩니다)",
|
||||
clearHint: "이 credential 제거",
|
||||
confirmClearTitle: "credential 제거 확인",
|
||||
confirmClearBody:
|
||||
"저장된 credential이 영구 삭제되며, 이를 사용하는 통합이 중단됩니다. 계속할까요?",
|
||||
credential: {
|
||||
configured: "구성됨",
|
||||
unconfigured: "구성되지 않음",
|
||||
configure: "구성",
|
||||
update: "교체",
|
||||
remove: "제거",
|
||||
inputPlaceholder: "값을 입력하세요",
|
||||
savedToast: "credential이 저장되었습니다",
|
||||
saveFailed: "credential 저장 실패",
|
||||
removedToast: "credential이 제거되었습니다",
|
||||
removeFailed: "credential 제거 실패",
|
||||
confirmRemoveTitle: "{field} 제거하시겠습니까?",
|
||||
confirmRemoveBody:
|
||||
"저장된 credential이 영구적으로 삭제되며, 이를 사용하는 통합은 새 값을 구성할 때까지 동작하지 않습니다.",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4083,6 +4083,7 @@ export default {
|
||||
connected: 'Подключено',
|
||||
connectionFailed: 'Подключение не удалось',
|
||||
isRequired: 'обязательно для заполнения',
|
||||
credentialsLabel: 'учётные данные',
|
||||
resourceHint: 'Выберите пространства или папки для синхронизации',
|
||||
untitled: 'Без названия',
|
||||
resourceLoadFailed: 'Не удалось загрузить список ресурсов',
|
||||
@@ -4247,11 +4248,19 @@ export default {
|
||||
createdAt: 'Создано',
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: '•••••••• (Введите новое значение для замены)',
|
||||
clearHint: 'Удалить эти учётные данные',
|
||||
confirmClearTitle: 'Подтверждение удаления учётных данных',
|
||||
confirmClearBody:
|
||||
'Это действие безвозвратно удалит сохранённые учётные данные. Интеграции, использующие их, перестанут работать. Продолжить?',
|
||||
credential: {
|
||||
configured: 'Настроено',
|
||||
unconfigured: 'Не настроено',
|
||||
configure: 'Настроить',
|
||||
update: 'Заменить',
|
||||
remove: 'Удалить',
|
||||
inputPlaceholder: 'Введите значение',
|
||||
savedToast: 'Учётные данные сохранены',
|
||||
saveFailed: 'Не удалось сохранить учётные данные',
|
||||
removedToast: 'Учётные данные удалены',
|
||||
removeFailed: 'Не удалось удалить учётные данные',
|
||||
confirmRemoveTitle: 'Удалить {field}?',
|
||||
confirmRemoveBody:
|
||||
'Сохранённые учётные данные будут безвозвратно удалены. Интеграции, использующие их, перестанут работать до настройки нового значения.',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -4115,6 +4115,7 @@ export default {
|
||||
connected: "已连接",
|
||||
connectionFailed: "连接失败",
|
||||
isRequired: "为必填项",
|
||||
credentialsLabel: "凭证",
|
||||
resourceHint: "选择要同步的内容空间/文件夹",
|
||||
untitled: "无标题",
|
||||
resourceLoadFailed: "加载资源列表失败",
|
||||
@@ -4280,11 +4281,19 @@ export default {
|
||||
createdAt: "创建时间",
|
||||
},
|
||||
},
|
||||
secret: {
|
||||
storedPlaceholder: "•••••••• (输入新值以替换)",
|
||||
clearHint: "删除此凭据",
|
||||
confirmClearTitle: "确认删除凭据",
|
||||
confirmClearBody:
|
||||
"此操作将永久删除已保存的凭据,依赖它的集成将停止工作。是否继续?",
|
||||
credential: {
|
||||
configured: "已配置",
|
||||
unconfigured: "未配置",
|
||||
configure: "配置",
|
||||
update: "更换",
|
||||
remove: "移除",
|
||||
inputPlaceholder: "请输入",
|
||||
savedToast: "凭据已保存",
|
||||
saveFailed: "保存凭据失败",
|
||||
removedToast: "凭据已移除",
|
||||
removeFailed: "移除凭据失败",
|
||||
confirmRemoveTitle: "移除 {field}?",
|
||||
confirmRemoveBody:
|
||||
"此操作将永久删除已保存的凭据,依赖它的集成将停止工作,直到您重新配置。",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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 ? '✓' : 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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user