diff --git a/frontend/src/assets/theme/styleGuard.test.mjs b/frontend/src/assets/theme/styleGuard.test.mjs index a11db3f6..8681e1dc 100644 --- a/frontend/src/assets/theme/styleGuard.test.mjs +++ b/frontend/src/assets/theme/styleGuard.test.mjs @@ -6,7 +6,9 @@ import { fileURLToPath } from 'node:url' /** * 样式守卫(棘轮):统计 views/ components/ assets/ 里绕过设计令牌或和 TDesign 打架的写法, - * 只允许计数下降。新增任何一处都会让测试失败;清理后请把 baseline 调低。 + * 只允许计数下降。新增任何一处都会让测试失败;清理后请把 baseline 调低(测试会提示目标值)。 + * 低于 baseline 不算失败:两个各自清理并下调 baseline 的 PR 先后合并时,main 不应因此变红。 + * 注释中的示例代码不计入。 * * 令牌定义在 assets/theme/theme.css(--app-radius-* / --app-text-* / --app-space-* / * --app-motion-* / --z-*),TDesign 全局覆盖放在 assets/theme/tdesign-overrides.less。 @@ -28,7 +30,7 @@ const RULES = [ name: 'legacy-blue-rgba', why: '旧版 TDesign 蓝 rgba(0,82,217) 已不是品牌色', pattern: /rgba\(\s*0\s*,\s*82\s*,\s*217\s*,/g, - baseline: 18, + baseline: 7, }, { name: 'td-token-fallback', @@ -40,43 +42,43 @@ const RULES = [ name: 'radius-literal', why: '圆角请用 var(--app-radius-xs|sm|md|lg|xl|pill)(4/6/8/10/12/999px)', pattern: /border(?:-[a-z]+)*-radius\s*:\s*\d+(?:\.\d+)?px/g, - baseline: 162, + baseline: 160, }, { name: 'font-size-literal', - why: '字号请用 var(--app-text-2xs … 4xl)(10~24px)', - pattern: /font-size\s*:\s*\d+(?:\.\d+)?px/g, - baseline: 28, + why: '字号请用 var(--app-text-2xs … 4xl)(10~24px),简写写成 font: var(--app-text-sm)/1.5 …;图标尺寸用 t-icon 的 size 属性', + pattern: /\bfont(?:-size)?\s*:\s*\d+(?:\.\d+)?px/g, + baseline: 33, }, { name: 'motion-literal', why: '过渡时长请用 var(--app-motion-instant|fast|base|slow)(120/150/200/300ms)', pattern: /transition[^;{]*?(? m.replace(/[^\n]/g, ' ') + return text + .replace(/\/\*[\s\S]*?\*\//g, blank) + .replace(//g, blank) + .replace(/(^|[ \t])\/\/[^\n]*/gm, blank) +} + +const sources = (() => { + const list = [] for (const dir of SCAN_DIRS) { for (const file of walk(join(SRC_ROOT, dir))) { const rel = relative(SRC_ROOT, file).replaceAll('\\', '/') - if (EXEMPT_FILES.has(rel)) continue - const text = readFileSync(file, 'utf8') - const n = (text.match(rule.pattern) ?? []).length - if (n > 0) { - byFile.set(rel, n) - total += n - } + if (!EXEMPT_FILES.has(rel)) list.push({ rel, text: stripComments(readFileSync(file, 'utf8')) }) } } - return { total, byFile } + return list +})() + +function findMatches(rule) { + const hits = [] + for (const { rel, text } of sources) { + for (const m of text.matchAll(rule.pattern)) { + const line = text.slice(0, m.index).split('\n').length + const snippet = text.split('\n')[line - 1].trim().slice(0, 100) + hits.push({ rel, line, snippet }) + } + } + return hits +} + +const MAX_LISTED_HITS = 40 + +function describeHits(hits) { + if (hits.length <= MAX_LISTED_HITS) { + return hits.map((h) => ` ${h.rel}:${h.line} ${h.snippet}`).join('\n') + } + const byFile = new Map() + for (const h of hits) byFile.set(h.rel, (byFile.get(h.rel) ?? 0) + 1) + return [...byFile.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 12) + .map(([f, n]) => ` ${n}\t${f}`) + .join('\n') } for (const rule of RULES) { - test(`style guard: ${rule.name} does not exceed baseline (${rule.baseline})`, () => { - const { total, byFile } = countMatches(rule) - const top = [...byFile.entries()] - .sort((a, b) => b[1] - a[1]) - .slice(0, 8) - .map(([f, n]) => ` ${n}\t${f}`) - .join('\n') + test(`style guard: ${rule.name} does not exceed baseline (${rule.baseline})`, (t) => { + const hits = findMatches(rule) assert.ok( - total <= rule.baseline, - `${rule.name}: ${total} occurrences > baseline ${rule.baseline}.\n${rule.why}\n${top}`, + hits.length <= rule.baseline, + `${rule.name}: ${hits.length} occurrences > baseline ${rule.baseline}.\n${rule.why}\n${describeHits(hits)}`, ) + if (hits.length < rule.baseline) { + t.diagnostic(`${rule.name}: ${hits.length} < baseline ${rule.baseline}; lower the baseline to ${hits.length}`) + } }) } diff --git a/frontend/src/components/SessionSidebarRow.vue b/frontend/src/components/SessionSidebarRow.vue index 76d811ad..0db5cf79 100644 --- a/frontend/src/components/SessionSidebarRow.vue +++ b/frontend/src/components/SessionSidebarRow.vue @@ -305,11 +305,18 @@ const confirmDangerAction = (): void => { .submenu_item:not(.submenu_item_batch) { &:hover, &:focus-within, &.submenu_item--menu-open { - .session-row-badge { opacity: 0; } .session-row-menu-wrap--badge .menu-more-wrap { opacity: 1; } } } +@media (hover: hover) { + .submenu_item:not(.submenu_item_batch) { + &:hover, &:focus-within, &.submenu_item--menu-open { + .session-row-badge { opacity: 0; } + } + } +} + @media (hover: none) { .session-row-menu-wrap { flex-basis: 24px; @@ -332,7 +339,6 @@ const confirmDangerAction = (): void => { position: static; flex: 0 0 16px; height: 24px; - opacity: 1 !important; } } diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index e3896454..b3a81dc7 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -5646,6 +5646,9 @@ export default { "serverDocumentation": "Original server documentation", "noServerDocumentation": "This MCP server's initialize result did not include instructions or serverInfo.description (both are optional). Tool text lives in each tool's description below.", "policyHint": "Tool and approval switches save immediately and survive directory refreshes.", + "columnTool": "Tool", + "columnEnabled": "Enabled", + "columnApproval": "Approval", "failed": "Could not load the tool directory", "setupProgress": "MCP setup steps", "connection": "Connection", diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index e12f6c7a..83e2ff0e 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -5646,6 +5646,9 @@ export default { "serverDocumentation": "サーバーの元の説明", "noServerDocumentation": "この MCP サーバーの initialize に instructions / serverInfo.description はありません(どちらも任意)。ツールの説明は下の各 description にあります。", "policyHint": "ツールの有効化と承認設定は即時保存され、一覧の更新後も維持されます。", + "columnTool": "ツール", + "columnEnabled": "有効", + "columnApproval": "承認", "failed": "ツール一覧を読み込めませんでした", "setupProgress": "MCP 設定の手順", "connection": "接続設定", diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 12f3c76d..86edccbb 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2422,6 +2422,9 @@ export default { "serverDocumentation": "서버 원본 설명", "noServerDocumentation": "이 MCP 서버의 initialize 응답에 instructions / serverInfo.description이 없습니다(둘 다 선택 필드). 도구 설명은 아래 각 도구의 description에 있습니다.", "policyHint": "도구 활성화 및 승인 설정은 즉시 저장되며 목록을 새로 고쳐도 유지됩니다.", + "columnTool": "도구", + "columnEnabled": "활성화", + "columnApproval": "승인", "failed": "도구 목록을 불러오지 못했습니다", "setupProgress": "MCP 설정 단계", "connection": "연결 설정", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index e7de097e..c4aab3bd 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2422,6 +2422,9 @@ export default { "serverDocumentation": "Исходная документация сервера", "noServerDocumentation": "Ответ initialize этого MCP-сервера не содержит instructions / serverInfo.description (оба поля необязательны). Текст инструментов — в description ниже.", "policyHint": "Настройки включения и подтверждения сохраняются сразу и не сбрасываются при обновлении каталога.", + "columnTool": "Инструмент", + "columnEnabled": "Вкл.", + "columnApproval": "Подтв.", "failed": "Не удалось загрузить каталог инструментов", "setupProgress": "Шаги настройки MCP", "connection": "Подключение", diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index b7f29e7b..2438463e 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2424,6 +2424,9 @@ export default { "serverDocumentation": "服务端原始说明", "noServerDocumentation": "该 MCP Server 的 initialize 未返回 instructions / serverInfo.description(均为可选字段)。工具说明在下方各工具的 description 里。", "policyHint": "工具开关与审批设置即时保存;刷新目录不会覆盖这些设置。", + "columnTool": "工具", + "columnEnabled": "启用", + "columnApproval": "需审批", "failed": "工具目录读取失败", "setupProgress": "MCP 配置步骤", "connection": "连接配置", diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index c5ea3b74..44157bf4 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -2424,6 +2424,9 @@ export default { "serverDocumentation": "伺服器端原始說明", "noServerDocumentation": "該 MCP Server 的 initialize 未返回 instructions / serverInfo.description(均為可選欄位)。工具說明在下方各工具的 description 裡。", "policyHint": "工具開關與審批設定即時儲存;重新整理目錄不會覆蓋這些設定。", + "columnTool": "工具", + "columnEnabled": "啟用", + "columnApproval": "需審批", "failed": "工具目錄讀取失敗", "setupProgress": "MCP 設定步驟", "connection": "連結設定", diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 4b8db23c..cd75f8c7 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -2178,7 +2178,7 @@ onBeforeRouteUpdate((to, from, next) => { flex-shrink: 0; margin: 0; padding: 3px 0 0; - font-size: 16px; + font-size: var(--app-text-xl); } .t-popconfirm__inner { diff --git a/frontend/src/views/settings/components/McpMetadataPanel.vue b/frontend/src/views/settings/components/McpMetadataPanel.vue index 1892acd9..1bab5ab6 100644 --- a/frontend/src/views/settings/components/McpMetadataPanel.vue +++ b/frontend/src/views/settings/components/McpMetadataPanel.vue @@ -3,24 +3,25 @@

{{ t('mcpMetadata.tools') }}

- - - {{ t(snapshot ? 'mcpMetadata.refresh' : 'mcpMetadata.fetch') }} - + + + + {{ t(snapshot ? 'mcpMetadata.refresh' : 'mcpMetadata.fetch') }} + +
-

{{ t('mcpMetadata.cacheHint') }}

- {{ t('mcpMetadata.toolCount', { count: snapshot.tools.length }) }} - {{ snapshot.server_name }} {{ snapshot.server_version }} - {{ t('mcpMetadata.syncedAt') }} {{ formatTime(snapshot.synced_at) }} + {{ t('mcpMetadata.toolCount', { count: snapshot.tools.length }) }} + {{ snapshot.server_name }} {{ snapshot.server_version }} + {{ t('mcpMetadata.syncedAt') }}{{ formatTime(snapshot.synced_at) }} {{ t('mcpMetadata.stale') }}

{{ t('mcpMetadata.notSynced') }}

@@ -205,11 +205,20 @@ onBeforeUnmount(() => { generation++; emit('busy', false); emit('synced', false) display: flex; flex-wrap: wrap; align-items: center; - gap: 4px 10px; + gap: 4px 0; margin: 4px 0 0; font-size: var(--app-text-sm); line-height: 1.4; - color: var(--td-text-color-secondary); + color: var(--td-text-color-placeholder); +} + +.snapshot-meta__item + .snapshot-meta__item::before { + content: '·'; + margin: 0 6px; +} + +.snapshot-meta > :not(.snapshot-meta__item) { + margin-left: 8px; } .snapshot-meta__help, diff --git a/frontend/src/views/settings/components/McpServiceDialog.vue b/frontend/src/views/settings/components/McpServiceDialog.vue index e8a0afe7..befed406 100644 --- a/frontend/src/views/settings/components/McpServiceDialog.vue +++ b/frontend/src/views/settings/components/McpServiceDialog.vue @@ -357,16 +357,18 @@
- - - {{ t('mcpMetadata.generateUsage') }} - + + + + {{ t('mcpMetadata.generateUsage') }} + +
- -

{{ t('mcpMetadata.generateHint') }}

{ .form-label { margin-bottom: 0; } } +.usage-textarea { + :deep(.t-textarea__inner) { + font-size: var(--app-text-md); + line-height: 1.65; + padding: 8px 10px; + } + + :deep(.t-textarea__info_wrapper), + :deep(.t-textarea__limit) { + font-size: var(--app-text-xs); + color: var(--td-text-color-placeholder); + } +} + .mcp-steps { display: flex; align-items: center; diff --git a/frontend/src/views/settings/components/McpToolsList.vue b/frontend/src/views/settings/components/McpToolsList.vue index 4b6e763c..532e2fad 100644 --- a/frontend/src/views/settings/components/McpToolsList.vue +++ b/frontend/src/views/settings/components/McpToolsList.vue @@ -6,76 +6,91 @@ -
+
+
+ + {{ t('mcpMetadata.columnTool') }} + + + + + +
-
- {{ tool.name }} - - - + +
+

{{ tool.description }}

-

{{ tool.description }}

-
-
@@ -168,10 +183,36 @@ onBeforeUnmount(() => { generation++; emit('busy', false) }) @@ -211,33 +250,45 @@ onBeforeUnmount(() => { generation++; emit('busy', false) }) .t-popup__content { padding: 0 !important; - width: 400px; + width: 380px; max-width: calc(100vw - 24px); - border-radius: var(--app-radius-md) !important; + border-radius: var(--app-radius-xl) !important; background: var(--td-bg-color-container) !important; - border: 1px solid var(--td-component-stroke) !important; - box-shadow: var(--td-shadow-2) !important; + border: 0.5px solid var(--td-component-stroke) !important; + box-shadow: + 0 0 0 0.5px rgba(0, 0, 0, 0.03), + 0 2px 4px rgba(0, 0, 0, 0.04), + 0 8px 24px rgba(0, 0, 0, 0.1) !important; + overflow: hidden; } } +:root[theme-mode='dark'] .mcp-tool-detail-popup .t-popup__content { + background: rgba(36, 36, 36, 0.92) !important; + border-color: rgba(255, 255, 255, 0.08) !important; +} + .tool-detail__tabs { - display: flex; - gap: 16px; - padding: 0 14px; - border-bottom: 1px solid var(--td-component-stroke); + display: inline-flex; + gap: 2px; + margin: 10px 12px 0; + padding: 2px; + border-radius: var(--app-radius-md); + background: var(--td-bg-color-secondarycontainer); } .tool-detail__tab { - margin-bottom: -1px; - padding: 10px 0 8px; + height: 24px; + padding: 0 10px; border: 0; - border-bottom: 2px solid transparent; + border-radius: var(--app-radius-sm); background: transparent; font: inherit; - font-size: var(--app-text-md); - line-height: 1.2; + font-size: var(--app-text-sm); + line-height: 24px; color: var(--td-text-color-secondary); cursor: pointer; + transition: background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease; } .tool-detail__tab:hover { @@ -247,20 +298,21 @@ onBeforeUnmount(() => { generation++; emit('busy', false) }) .tool-detail__tab.is-active { color: var(--td-text-color-primary); font-weight: 500; - border-bottom-color: var(--td-brand-color); + background: var(--td-bg-color-container); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); } .tool-detail__body { - padding: 12px 14px 14px; + padding: 10px 14px 14px; max-height: min(50vh, 360px); overflow: auto; } .tool-detail__desc { margin: 0; - font-size: var(--app-text-sm); + font-size: var(--app-text-md); line-height: 1.65; - color: var(--td-text-color-secondary); + color: var(--td-text-color-primary); white-space: pre-wrap; overflow-wrap: anywhere; } diff --git a/internal/agent/tools/mcp_oauth_test.go b/internal/agent/tools/mcp_oauth_test.go index cc0d8819..6d1ba98f 100644 --- a/internal/agent/tools/mcp_oauth_test.go +++ b/internal/agent/tools/mcp_oauth_test.go @@ -2,6 +2,7 @@ package tools import ( "context" + "encoding/json" "fmt" "net/http/httptest" "sync" @@ -14,6 +15,7 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/utils" + mcpgo "github.com/mark3labs/mcp-go/mcp" sdkserver "github.com/mark3labs/mcp-go/server" "github.com/stretchr/testify/require" ) @@ -79,6 +81,78 @@ func (g oauthRetryTestGate) RequestOAuthAndWait( return approval.Decision{Approved: true}, nil } +// approvedOAuthGate requires approval for every call, approves it, and then +// completes the OAuth prompt the way oauthRetryTestGate does. +type approvedOAuthGate struct { + oauthRetryTestGate + oauthPrompts *int +} + +func (approvedOAuthGate) NeedsApproval(context.Context, uint64, string, string) bool { return true } + +func (approvedOAuthGate) IsEnabled(context.Context, uint64, string, string) (bool, error) { + return true, nil +} + +func (approvedOAuthGate) RequestAndWait(context.Context, approval.PendingRequest) (approval.Decision, error) { + return approval.Decision{Approved: true}, nil +} + +func (g approvedOAuthGate) RequestOAuthAndWait( + ctx context.Context, req approval.OAuthPendingRequest, +) (approval.Decision, error) { + *g.oauthPrompts++ + return g.oauthRetryTestGate.RequestOAuthAndWait(ctx, req) +} + +// The approval step swaps in a ctx derived from ApprovalCtx; the OAuth prompt +// must still be offered afterwards instead of failing with "open settings". +func TestMCPToolOffersOAuthPromptAfterApproval(t *testing.T) { + utils.SetSSRFWhitelistFromRaw("127.0.0.1") + t.Cleanup(utils.ResetSSRFWhitelistForTest) + mcpServer := sdkserver.NewMCPServer("test", "1") + mcpServer.AddTool(mcpgo.NewTool("echo"), + func(context.Context, mcpgo.CallToolRequest) (*mcpgo.CallToolResult, error) { + return mcpgo.NewToolResultText("pong"), nil + }) + server := httptest.NewServer(sdkserver.NewStreamableHTTPServer(mcpServer, sdkserver.WithStateLess(true))) + t.Cleanup(server.Close) + service := &types.MCPService{ + ID: "svc-approval", + Name: "km", + Enabled: true, + TransportType: types.MCPTransportHTTPStreamable, + URL: &server.URL, + AuthConfig: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth}, + } + repo := &oauthRetryTestRepo{clients: map[string]*types.MCPOAuthClient{}, tokens: map[string]*types.MCPOAuthToken{}} + repo.registerClient(service.ID, "client-1") + manager := mcp.NewMCPManager(repo) + t.Cleanup(manager.Shutdown) + + alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"} + prompts := 0 + gate := approvedOAuthGate{ + oauthRetryTestGate: oauthRetryTestGate{authorized: func() { repo.saveToken(alice, service.ID) }}, + oauthPrompts: &prompts, + } + tool := NewMCPTool(service, &types.MCPTool{Name: "echo"}, manager, gate, 0) + + base := ctxForOAuthRetryTest(alice) + ctx := WithToolExecContext(base, &ToolExecContext{ + EventBus: event.NewEventBus(), + ToolCallID: "call-1", + UserID: alice.StorageID(), + ApprovalCtx: base, + ExecTimeout: 5 * time.Second, + }) + result, err := tool.Execute(ctx, json.RawMessage(`{}`)) + require.NoError(t, err) + require.Equal(t, 1, prompts, "the OAuth prompt must be offered after approval") + require.True(t, result.Success, result.Error) + require.Contains(t, result.Output, "pong") +} + func ctxForOAuthRetryTest(principal types.Principal) context.Context { ctx := context.WithValue(context.Background(), types.TenantIDContextKey, oauthRetryTestTenant) return types.WithPrincipal(ctx, principal) diff --git a/internal/agent/tools/mcp_tool.go b/internal/agent/tools/mcp_tool.go index 1b52451f..b381682d 100644 --- a/internal/agent/tools/mcp_tool.go +++ b/internal/agent/tools/mcp_tool.go @@ -166,9 +166,15 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too }, err } + // The post-approval ctx is derived from ApprovalCtx, which does not carry + // the exec metadata; read it once here so the OAuth prompt still works + // for tools that require approval. + execMeta, _ := ToolExecFromContext(ctx) + callWindowDerived := false + // Human approval gate for dangerous tools (issue #1173) if t.gate != nil { - if meta, ok := ToolExecFromContext(ctx); ok && meta != nil && meta.EventBus != nil { + if meta := execMeta; meta != nil && meta.EventBus != nil { tenantID, _ := types.TenantIDFromContext(ctx) if t.gate.NeedsApproval(ctx, tenantID, t.service.ID, t.mcpTool.Name) { // Use ApprovalCtx (round-level ctx WITHOUT defaultToolExecTimeout) so @@ -235,13 +241,14 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too freshCtx, freshCancel := context.WithTimeout(meta.ApprovalCtx, t.callToolTimeout(meta.ExecTimeout)) defer freshCancel() ctx = freshCtx + callWindowDerived = true } } } } isStdio := t.service.TransportType == types.MCPTransportStdio - meta, _ := ToolExecFromContext(ctx) + meta := execMeta oauthSess := oauthSessionFromToolExec(ctx, meta).withAuthWaitTimeout(t.authWaitTimeoutSeconds) toolCallID := "" if meta != nil { @@ -254,9 +261,8 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too // with a longer timeout were silently cancelled mid-flight even though the // transport layers honor the value. Re-derive the window from ApprovalCtx — // the round-level parent without the per-tool deadline. Skipped on the - // post-approval path, which already re-derived its window above and whose - // swapped ctx no longer carries the exec meta. - if meta != nil && meta.ApprovalCtx != nil { + // post-approval path, which already re-derived its window above. + if !callWindowDerived && meta != nil && meta.ApprovalCtx != nil { callCtx, callCancel := context.WithTimeout(meta.ApprovalCtx, t.callToolTimeout(meta.ExecTimeout)) defer callCancel() ctx = callCtx