Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(security): redact config secrets and restrict agent imports (#555)
Call White72c7a9ede836
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 39d12cf56..53810e457 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -289,6 +289,87 @@ def test_config_to_payload_redacts_remote_access_secrets_and_save_preserves_themassert updated.remote_access.vibe_cloud.session_secret == "session-secret"+def test_config_to_payload_redacts_platform_and_gateway_secrets_and_save_preserves_them(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ payload = _full_config_payload()+ payload["slack"] = {+ **payload["slack"],+ "bot_token": "xoxb-secret-token",+ "app_token": "xapp-secret-token",+ "signing_secret": "slack-signing-secret",+ }+ payload["telegram"] = {+ "bot_token": "123456:telegram-secret",+ "webhook_secret_token": "telegram-webhook-secret",+ "require_mention": True,+ "forum_auto_topic": True,+ "use_webhook": True,+ }+ payload["lark"] = {+ "app_id": "cli_lark_id",+ "app_secret": "lark-secret",+ "require_mention": False,+ "domain": "feishu",+ }+ payload["wechat"] = {+ "bot_token": "wechat-secret",+ "base_url": "https://ilinkai.weixin.qq.com",+ "cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",+ "require_mention": False,+ }+ payload["gateway"] = {+ "relay_url": "https://relay.example",+ "workspace_token": "workspace-secret",+ "client_id": "client-id",+ "client_secret": "client-secret",+ }++ created = api.save_config(payload)+ redacted = api.config_to_payload(created)++ assert redacted["slack"]["bot_token_length"] == len("xoxb-secret-token")+ assert redacted["slack"]["has_bot_token"] is True+ assert "bot_token" not in redacted["slack"]+ assert redacted["slack"]["has_app_token"] is True+ assert "app_token" not in redacted["slack"]+ assert redacted["slack"]["has_signing_secret"] is True+ assert "signing_secret" not in redacted["slack"]+ assert redacted["discord"]["has_bot_token"] is True+ assert "bot_token" not in redacted["discord"]+ assert redacted["telegram"]["has_bot_token"] is True+ assert "bot_token" not in redacted["telegram"]+ assert redacted["telegram"]["has_webhook_secret_token"] is True+ assert "webhook_secret_token" not in redacted["telegram"]+ assert redacted["lark"]["app_id"] == "cli_lark_id"+ assert redacted["lark"]["has_app_secret"] is True+ assert "app_secret" not in redacted["lark"]+ assert redacted["wechat"]["has_bot_token"] is True+ assert "bot_token" not in redacted["wechat"]+ assert redacted["gateway"]["has_workspace_token"] is True+ assert "workspace_token" not in redacted["gateway"]+ assert redacted["gateway"]["has_client_secret"] is True+ assert "client_secret" not in redacted["gateway"]++ included = api.config_to_payload(created, include_secrets=True)+ assert included["slack"]["bot_token"] == "xoxb-secret-token"+ assert included["gateway"]["client_secret"] == "client-secret"++ redacted["show_duration"] = False+ updated = api.save_config(redacted)++ assert updated.slack.bot_token == "xoxb-secret-token"+ assert updated.slack.app_token == "xapp-secret-token"+ assert updated.slack.signing_secret == "slack-signing-secret"+ assert updated.discord.bot_token == "discord-token-1234567890"+ assert updated.telegram.bot_token == "123456:telegram-secret"+ assert updated.telegram.webhook_secret_token == "telegram-webhook-secret"+ assert updated.lark.app_secret == "lark-secret"+ assert updated.wechat.bot_token == "wechat-secret"+ assert updated.gateway is not None+ assert updated.gateway.workspace_token == "workspace-secret"+ assert updated.gateway.client_secret == "client-secret"++def test_save_config_accepts_slack_disable_link_unfurl(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex c9935b7ba..538efdeac 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -2257,6 +2257,21 @@ def test_telegram_auth_test_returns_response(monkeypatch):assert result["response"]["username"] == "vibe_remote_bot"+def test_telegram_auth_test_uses_stored_token_when_request_omits_secret(monkeypatch):+ async def fake_get_me(bot_token: str, proxy_url: str | None = None):+ assert bot_token == "123456:stored-token"+ assert proxy_url is None+ return {"id": 1, "username": "stored_bot"}++ monkeypatch.setattr(api, "_telegram_get_me", fake_get_me)+ monkeypatch.setattr(api, "_stored_platform_secret", lambda platform, field: "123456:stored-token")++ result = api.telegram_auth_test("")++ assert result["ok"] is True+ assert result["response"]["username"] == "stored_bot"++def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")chat_discovery.remember_chat("telegram", "-1001", name="Core Group", native_type="supergroup")@@ -2441,6 +2456,35 @@ def test_vibe_agent_import_reports_unreadable_file_as_client_error(tmp_path, monapi.import_vibe_agents({"file": str(missing_file), "backend": "codex"})+def test_vibe_agent_import_rejects_non_markdown_direct_file(tmp_path, monkeypatch):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ secret_file = tmp_path / "config.json"+ secret_file.write_text('{"token":"secret"}', encoding="utf-8")++ with pytest.raises(ValueError, match=r"Markdown \(\.md\) file"):+ api.import_vibe_agents({"file": str(secret_file), "backend": "codex"})+++def test_vibe_agent_import_rejects_markdown_without_agent_frontmatter(tmp_path, monkeypatch):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ notes_file = tmp_path / "private-notes.md"+ notes_file.write_text("# Private notes\n\nnon-agent content\n", encoding="utf-8")++ with pytest.raises(ValueError, match="frontmatter with a name field"):+ api.import_vibe_agents({"file": str(notes_file), "backend": "codex"})+++def test_vibe_agent_import_allows_uppercase_markdown_extension(tmp_path, monkeypatch):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ agent_file = tmp_path / "Reviewer.MD"+ agent_file.write_text("---\nname: reviewer\n---\nReview carefully.\n", encoding="utf-8")++ result = api.import_vibe_agents({"file": str(agent_file), "backend": "codex"})++ assert result["ok"] is True+ assert result["imported"][0]["name"] == "reviewer"++def test_vibe_agent_import_skips_invalid_global_agent_file(tmp_path, monkeypatch):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))valid_file = tmp_path / "valid.md"diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 41104143a..3b1b2d312 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -6,6 +6,7 @@ from starlette.websockets import WebSocketDisconnectfrom vibe import ui_serverfrom vibe.ui_server import app+from tests.test_api_save_config_merge import _full_config_payloadfrom tests.ui_server_test_helpers import csrf_headers@@ -248,6 +249,70 @@ def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch,assert not paths.get_config_path().exists(), "GET must not persist a config file"+def test_config_routes_redact_platform_and_gateway_secrets(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ payload = _full_config_payload()+ payload["slack"] = {+ **payload["slack"],+ "bot_token": "xoxb-route-secret",+ "app_token": "xapp-route-secret",+ "signing_secret": "slack-route-secret",+ }+ payload["telegram"] = {+ "bot_token": "123456:telegram-route-secret",+ "webhook_secret_token": "telegram-webhook-route-secret",+ "require_mention": True,+ "forum_auto_topic": True,+ "use_webhook": True,+ }+ payload["lark"] = {+ "app_id": "cli_route_lark_id",+ "app_secret": "lark-route-secret",+ "require_mention": False,+ "domain": "feishu",+ }+ payload["wechat"] = {+ "bot_token": "wechat-route-secret",+ "base_url": "https://ilinkai.weixin.qq.com",+ "cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",+ "require_mention": False,+ }+ payload["gateway"] = {+ "relay_url": "https://relay.example",+ "workspace_token": "workspace-route-secret",+ "client_id": "client-id",+ "client_secret": "client-route-secret",+ }++ client = app.test_client()+ response = client.post("/api/config", json=payload, headers=csrf_headers(client))++ assert response.status_code == 200+ saved = response.get_json()+ fetched = client.get("/api/config").get_json()+ for data in (saved, fetched):+ assert data["slack"]["has_bot_token"] is True+ assert data["slack"]["has_app_token"] is True+ assert data["slack"]["has_signing_secret"] is True+ assert "bot_token" not in data["slack"]+ assert "app_token" not in data["slack"]+ assert "signing_secret" not in data["slack"]+ assert data["discord"]["has_bot_token"] is True+ assert "bot_token" not in data["discord"]+ assert data["telegram"]["has_bot_token"] is True+ assert data["telegram"]["has_webhook_secret_token"] is True+ assert "bot_token" not in data["telegram"]+ assert "webhook_secret_token" not in data["telegram"]+ assert data["lark"]["has_app_secret"] is True+ assert "app_secret" not in data["lark"]+ assert data["wechat"]["has_bot_token"] is True+ assert "bot_token" not in data["wechat"]+ assert data["gateway"]["has_workspace_token"] is True+ assert data["gateway"]["has_client_secret"] is True+ assert "workspace_token" not in data["gateway"]+ assert "client_secret" not in data["gateway"]++def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):ui_dist = tmp_path / "dist"assets_dir = ui_dist / "assets"diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 95b3345a8..9a5770be3 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -14,6 +14,7 @@ import { Summary } from './steps/Summary';import { useApi } from '../context/ApiContext';import clsx from 'clsx';import { getEnabledPlatforms, getPrimaryPlatform, platformSupportsChannels } from '../lib/platforms';+import { withoutConfiguredSecretMarker, withSecretDraft, withSecretDrafts } from '../lib/secretFields';import { WizardChrome } from './visual';const buildConfigPayload = (data: any) => {@@ -30,34 +31,37 @@ const buildConfigPayload = (data: any) => {version: 'v2',slack: {// Preserve all existing slack fields- ...data.slack,+ ...withSecretDrafts(data.slack, {+ bot_token: data.slack?.bot_token,+ app_token: data.slack?.app_token,+ }),// Override only the fields that setup modifies- bot_token: data.slack?.bot_token || '',- app_token: data.slack?.app_token || '',require_mention: data.slack?.require_mention || false,},discord: {- ...data.discord,- bot_token: data.discord?.bot_token || '',+ ...withSecretDraft(data.discord, 'bot_token', data.discord?.bot_token),require_mention: data.discord?.require_mention || false,},telegram: {- ...data.telegram,- bot_token: data.telegram?.bot_token || '',+ ...withSecretDraft(data.telegram, 'bot_token', data.telegram?.bot_token),require_mention: data.telegram?.require_mention ?? true,forum_auto_topic: data.telegram?.forum_auto_topic ?? true,use_webhook: data.telegram?.use_webhook ?? false,},- lark: {- ...data.lark,- app_id: data.lark?.app_id || '',- app_secret: data.lark?.app_secret || '',- domain: data.lark?.domain || 'feishu',- require_mention: data.lark?.require_mention || false,- },+ lark: (() => {+ const lark = data.lark || {};+ const appId = lark.app_id || '';+ const appIdChanged = Boolean(lark.original_app_id && appId && appId !== lark.original_app_id);+ const base = appIdChanged ? withoutConfiguredSecretMarker(lark, 'app_secret') : lark;+ return {+ ...withSecretDraft(base, 'app_secret', lark.app_secret),+ app_id: appId,+ domain: lark.domain || 'feishu',+ require_mention: lark.require_mention || false,+ };+ })(),wechat: {- ...data.wechat,- bot_token: data.wechat?.bot_token || '',+ ...withSecretDraft(data.wechat, 'bot_token', data.wechat?.bot_token),base_url: data.wechat?.base_url || 'https://ilinkai.weixin.qq.com',cdn_base_url: data.wechat?.cdn_base_url || 'https://novac2c.cdn.weixin.qq.com/c2c',require_mention: data.wechat?.require_mention || false,diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsxindex aee4c9cc4..dec8b2abe 100644--- a/ui/src/components/settings/SettingsPlatformsPage.tsx+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx@@ -75,14 +75,14 @@ export const SettingsPlatformsPage: React.FC = () => {setRestartPhase('saving');try {try {- await api.saveConfig(nextData);+ const savedConfig = await api.saveConfig(nextData);+ setConfig(savedConfig);} catch {// Surface save failures to the user instead of letting the rejection// propagate as an unhandled async error from the click handler.showToast(t('common.saveFailed'), 'error');return;}- setConfig((prev: any) => ({ ...(prev || {}), ...nextData }));closeAll();setRestartPhase('restarting');try {@@ -406,4 +406,3 @@ const PlatformConfigEmbed: React.FC<{}return null;};-diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 4838a235b..54b3b2eb2 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -21,6 +21,7 @@ import { DirectoryBrowser } from '../ui/directory-browser';import { useNavigate } from 'react-router-dom';import clsx from 'clsx';import { getEnabledPlatforms, platformSupportsChannels } from '../../lib/platforms';+import { hasUsableSecret } from '../../lib/secretFields';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';import { CompactSelect, SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';@@ -311,6 +312,15 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst larkAppId = config.lark?.app_id || data.lark?.app_id || '';const larkAppSecret = config.lark?.app_secret || data.lark?.app_secret || '';const larkDomain = config.lark?.domain || data.lark?.domain || 'feishu';+ const hasChannelCredentials = (platformId: string, source: any = config) => {+ if (platformId === 'lark') {+ return Boolean(source.lark?.app_id && hasUsableSecret(source.lark, 'app_secret'));+ }+ if (platformId === 'slack') return hasUsableSecret(source.slack, 'bot_token', source.slackBotToken);+ if (platformId === 'discord') return hasUsableSecret(source.discord, 'bot_token');+ if (platformId === 'telegram') return hasUsableSecret(source.telegram, 'bot_token');+ return false;+ };const clearRefreshFollowups = () => {refreshFollowupVersionRef.current += 1;@@ -419,7 +429,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB};const loadGuilds = async () => {- if (!botToken) return;+ if (!botToken && !hasChannelCredentials('discord')) return;try {const result = await api.discordGuilds(botToken);if (result.ok) {@@ -468,8 +478,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst loadChannels = async (all?: boolean, force = false) => {const requestVersion = nextChannelRequestVersion();if (platform === 'lark') {- if (!larkAppId || !larkAppSecret) return;- } else if (!botToken) {+ if (!larkAppId || !hasChannelCredentials('lark')) return;+ } else if (!botToken && !hasChannelCredentials(platform)) {return;}const isAll = all ?? browseAll;@@ -579,12 +589,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBuseEffect(() => {if (platform === 'lark') {- if (larkAppId && larkAppSecret) {+ if (larkAppId && hasChannelCredentials('lark')) {loadChannels();}return;}- if (!botToken) return;+ if (!botToken && !hasChannelCredentials(platform)) return;if (platform === 'discord') {loadGuilds();if (selectedGuild) {@@ -593,7 +603,17 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB} else {loadChannels();}- }, [botToken, platform, selectedGuild, larkAppId, larkAppSecret]);+ }, [+ botToken,+ platform,+ selectedGuild,+ larkAppId,+ larkAppSecret,+ config.slack?.has_bot_token,+ config.discord?.has_bot_token,+ config.telegram?.has_bot_token,+ config.lark?.has_app_secret,+ ]);useEffect(() => {if (config.agents?.claude?.enabled) {@@ -778,14 +798,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst appId = config.lark?.app_id || '';const appSecret = config.lark?.app_secret || '';const domain = config.lark?.domain || 'feishu';- if (appId && appSecret) {+ if (appId && hasChannelCredentials('lark')) {const result = await api.larkChats(appId, appSecret, domain, force);recordRefreshMeta(p, result);refreshing = Boolean(result.refreshing);if (result.ok) channelsList = result.channels || [];}} else if (p === 'telegram') {- if (config.telegram?.bot_token) {+ if (hasChannelCredentials('telegram')) {const result = await api.telegramChats(false);if (result.ok) channelsList = result.channels || [];}@@ -793,7 +813,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBconst allowlist = getDiscordGuildAllowlist(settings);const guildId = allowlist[0] || selectedGuildIdsRef.current[0] || selectedGuild;const token = config.discord?.bot_token || '';- if (guildId && token) {+ if (guildId && hasChannelCredentials('discord')) {const result = await api.discordChannels(token, guildId, force);recordRefreshMeta(p, result);refreshing = Boolean(result.refreshing);@@ -802,8 +822,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB}}} else if (p === 'slack') {- if (config.slack?.bot_token) {- const result = await api.slackChannels(config.slack.bot_token, false, force);+ if (hasChannelCredentials('slack')) {+ const result = await api.slackChannels(config.slack?.bot_token || '', false, force);recordRefreshMeta(p, result);refreshing = Boolean(result.refreshing);if (result.ok) channelsList = result.channels || [];@@ -840,10 +860,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBisPage,pageTab,config.slack?.bot_token,+ config.slack?.has_bot_token,config.discord?.bot_token,+ config.discord?.has_bot_token,config.telegram?.bot_token,+ config.telegram?.has_bot_token,config.lark?.app_id,config.lark?.app_secret,+ config.lark?.has_app_secret,]);// When the user picks a per-platform tab, sync pagePlatform so existing flow loads itdiff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsxindex 4356fa95d..89a4f1876 100644--- a/ui/src/components/steps/DiscordConfig.tsx+++ b/ui/src/components/steps/DiscordConfig.tsx@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';+import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';@@ -44,7 +45,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBaconst { t } = useTranslation();const api = useApi();const { showToast } = useToast();- const [botToken, setBotToken] = useState(data.discord?.bot_token || '');+ const [botToken, setBotToken] = useState(secretInputValue(data.discord, 'bot_token'));const [proxyUrl, setProxyUrl] = useState(data.discord?.proxy_url || '');const [checking, setChecking] = useState(false);const [applying, setApplying] = useState(false);@@ -68,16 +69,16 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa}, [botToken]);useEffect(() => {- if (botToken && !expandedSteps[4]) {+ if ((botToken || hasUsableSecret(data.discord, 'bot_token')) && !expandedSteps[4]) {setExpandedSteps((prev) => ({ ...prev, 4: true }));}- }, [botToken, expandedSteps]);+ }, [botToken, data.discord, expandedSteps]);const isValid = useMemo(() => {- if (!botToken) return false;+ if (!botToken) return hasUsableSecret(data.discord, 'bot_token');if (authResult?.ok) return true;- return Boolean(data.discord?.bot_token && botToken === data.discord?.bot_token);- }, [botToken, authResult, data.discord?.bot_token]);+ return false;+ }, [botToken, authResult, data.discord]);const runAuthTest = async () => {setChecking(true);@@ -92,7 +93,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa};const loadGuilds = async () => {- if (!botToken) return;+ if (!botToken && !hasUsableSecret(data.discord, 'bot_token')) return;try {const result = await api.discordGuilds(botToken);if (result.ok) {@@ -144,7 +145,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBaconst completedCount = [!!clientId,- Boolean(authResult?.ok || (data.discord?.bot_token && botToken === data.discord?.bot_token)),+ Boolean(authResult?.ok || hasUsableSecret(data.discord, 'bot_token', botToken)),!!inviteUrl,isValid,].filter(Boolean).length;@@ -152,8 +153,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBaconst buildSubmitData = () => ({platform: 'discord',discord: {- ...(data.discord || {}),- bot_token: botToken,+ ...withSecretDraft(data.discord, 'bot_token', botToken),proxy_url: proxyUrl || undefined,},discordGuildAllowlist: selectedGuilds,@@ -338,7 +338,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBavariant="brand"size="sm"onClick={runAuthTest}- disabled={!botToken || checking}+ disabled={(!botToken && !hasUsableSecret(data.discord, 'bot_token')) || checking}>{checking ? <RefreshCw size={14} className="animate-spin" /> : <Shield size={14} strokeWidth={2.25} />}{t('discordConfig.validateToken')}diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsxindex 077a38968..307401f46 100644--- a/ui/src/components/steps/LarkConfig.tsx+++ b/ui/src/components/steps/LarkConfig.tsx@@ -20,6 +20,12 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';+import {+ hasConfiguredSecret,+ secretInputValue,+ withoutConfiguredSecretMarker,+ withSecretDraft,+} from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';@@ -74,7 +80,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, emconst { showToast } = useToast();const [domain, setDomain] = useState<'feishu' | 'lark'>(data.lark?.domain || 'feishu');const [appId, setAppId] = useState(data.lark?.app_id || '');- const [appSecret, setAppSecret] = useState(data.lark?.app_secret || '');+ const [appSecret, setAppSecret] = useState(secretInputValue(data.lark, 'app_secret'));const [proxyUrl, setProxyUrl] = useState(data.lark?.proxy_url || '');const [checking, setChecking] = useState(false);const [applying, setApplying] = useState(false);@@ -95,6 +101,11 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, emconst permissionsUrl = appBase ? `${appBase}/auth` : '';const eventsUrl = appBase ? `${appBase}/event` : '';const versionUrl = appBase ? `${appBase}/version` : '';+ const originalAppId = data.lark?.original_app_id || data.lark?.app_id || '';+ const appIdChanged = Boolean(originalAppId && appId && appId !== originalAppId);+ const canReuseStoredSecret =+ !appSecret && !appIdChanged && Boolean(appId) && appId === originalAppId && hasConfiguredSecret(data.lark, 'app_secret');+ const hasCredentialSecret = Boolean(appSecret || canReuseStoredSecret);useEffect(() => {setAuthResult(null);@@ -102,11 +113,11 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em}, [appId, appSecret]);useEffect(() => {- if (appId && appSecret && !expandedSteps[2]) {+ if (appId && hasCredentialSecret && !expandedSteps[2]) {setExpandedSteps((prev) => ({ ...prev, 2: true }));}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [appId, appSecret]);+ }, [appId, appSecret, hasCredentialSecret]);useEffect(() => {return () => {@@ -116,15 +127,11 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em}, []);const isValid = useMemo(() => {- if (!appId || !appSecret) return false;+ if (!appId || !hasCredentialSecret) return false;if (authResult?.ok) return true;- return Boolean(- data.lark?.app_id &&- data.lark?.app_secret &&- appId === data.lark?.app_id &&- appSecret === data.lark?.app_secret- );- }, [appId, appSecret, authResult, data.lark?.app_id, data.lark?.app_secret]);+ if (canReuseStoredSecret) return true;+ return Boolean(data.lark?.app_secret && appSecret === data.lark.app_secret && appId === originalAppId);+ }, [appId, appSecret, authResult, canReuseStoredSecret, data.lark?.app_secret, hasCredentialSecret, originalAppId]);const runAuthTest = async () => {setChecking(true);@@ -151,7 +158,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em};const loadChats = async () => {- if (!appId || !appSecret) return;+ if (!appId || !hasCredentialSecret) return;try {const result = await api.larkChats(appId, appSecret, domain);if (result.ok) {@@ -194,9 +201,12 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, emconst buildSubmitData = () => ({platform: 'lark',lark: {- ...(data.lark || {}),+ ...withSecretDraft(+ appIdChanged ? withoutConfiguredSecretMarker(data.lark, 'app_secret') : data.lark,+ 'app_secret',+ appSecret+ ),app_id: appId,- app_secret: appSecret,domain,proxy_url: proxyUrl || undefined,},@@ -319,7 +329,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, emvariant="brand"size="sm"onClick={runAuthTest}- disabled={!appId || !appSecret || checking}+ disabled={!appId || !hasCredentialSecret || checking}>{checking ? <RefreshCw size={14} className="animate-spin" /> : <Shield size={14} strokeWidth={2.25} />}{t('larkConfig.validateCredentials')}diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsxindex 60308bc36..7586bdde9 100644--- a/ui/src/components/steps/PlatformSelection.tsx+++ b/ui/src/components/steps/PlatformSelection.tsx@@ -11,6 +11,7 @@ import {getPrimaryPlatform,WORKBENCH_PLATFORM_ID,} from '../../lib/platforms';+import { hasUsableSecret, secretInputValue } from '../../lib/secretFields';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { Button } from '../ui/button';import { Input } from '../ui/input';@@ -40,25 +41,26 @@ type ValidationState = 'idle' | 'success' | 'error';const buildInitialCredentialDraft = (data: any) => ({slack: {...(data.slack || {}),- bot_token: data.slack?.bot_token || data.slackBotToken || '',- app_token: data.slack?.app_token || data.slackAppToken || '',+ bot_token: secretInputValue(data.slack, 'bot_token') || data.slackBotToken || '',+ app_token: secretInputValue(data.slack, 'app_token') || data.slackAppToken || '',},discord: {...(data.discord || {}),- bot_token: data.discord?.bot_token || '',+ bot_token: secretInputValue(data.discord, 'bot_token'),client_id: data.discord?.client_id || data.discord_client_id || '',},telegram: {require_mention: true,forum_auto_topic: true,...(data.telegram || {}),- bot_token: data.telegram?.bot_token || '',+ bot_token: secretInputValue(data.telegram, 'bot_token'),},lark: {domain: 'feishu',...(data.lark || {}),app_id: data.lark?.app_id || '',- app_secret: data.lark?.app_secret || '',+ original_app_id: data.lark?.original_app_id || data.lark?.app_id || '',+ app_secret: secretInputValue(data.lark, 'app_secret'),},wechat: {...(data.wechat || {}),@@ -154,10 +156,10 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe};const canValidate = () => {- if (activeCredentialPlatform === 'slack') return Boolean(activeCredential.bot_token);- if (activeCredentialPlatform === 'discord') return Boolean(activeCredential.bot_token);- if (activeCredentialPlatform === 'telegram') return Boolean(activeCredential.bot_token);- if (activeCredentialPlatform === 'lark') return Boolean(activeCredential.app_id && activeCredential.app_secret);+ if (activeCredentialPlatform === 'slack') return hasUsableSecret(activeCredential, 'bot_token');+ if (activeCredentialPlatform === 'discord') return hasUsableSecret(activeCredential, 'bot_token');+ if (activeCredentialPlatform === 'telegram') return hasUsableSecret(activeCredential, 'bot_token');+ if (activeCredentialPlatform === 'lark') return Boolean(activeCredential.app_id && hasUsableSecret(activeCredential, 'app_secret'));return false;};diff --git a/ui/src/components/steps/SlackConfig.tsx b/ui/src/components/steps/SlackConfig.tsxindex a13384b8e..9b061db87 100644--- a/ui/src/components/steps/SlackConfig.tsx+++ b/ui/src/components/steps/SlackConfig.tsx@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';+import { hasUsableSecret, secretInputValue, withSecretDrafts } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';@@ -27,8 +28,8 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,const { t } = useTranslation();const api = useApi();const { showToast } = useToast();- const [botToken, setBotToken] = useState(data.slack?.bot_token || data.slackBotToken || '');- const [appToken, setAppToken] = useState(data.slack?.app_token || data.slackAppToken || '');+ const [botToken, setBotToken] = useState(secretInputValue(data.slack, 'bot_token') || data.slackBotToken || '');+ const [appToken, setAppToken] = useState(secretInputValue(data.slack, 'app_token') || data.slackAppToken || '');const [proxyUrl, setProxyUrl] = useState(data.slack?.proxy_url || '');const [checking, setChecking] = useState(false);const [applying, setApplying] = useState(false);@@ -41,7 +42,12 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,// Collapsible states for each stepconst [expandedSteps, setExpandedSteps] = useState<Record<number, boolean>>({ 1: true, 2: false, 3: false, 4: false });- const isValid = useMemo(() => botToken.startsWith('xoxb-') && appToken.startsWith('xapp-'), [botToken, appToken]);+ const isValid = useMemo(+ () =>+ (botToken ? botToken.startsWith('xoxb-') : hasUsableSecret(data.slack, 'bot_token')) &&+ (appToken ? appToken.startsWith('xapp-') : hasUsableSecret(data.slack, 'app_token')),+ [appToken, botToken, data.slack]+ );useEffect(() => {void loadManifest();@@ -50,18 +56,18 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,// Auto-expand next step when token is entereduseEffect(() => {- if (botToken.startsWith('xoxb-') && !expandedSteps[3]) {+ if ((botToken.startsWith('xoxb-') || (!botToken && hasUsableSecret(data.slack, 'bot_token'))) && !expandedSteps[3]) {setExpandedSteps((prev) => ({ ...prev, 2: false, 3: true }));}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [botToken]);+ }, [botToken, data.slack]);useEffect(() => {- if (appToken.startsWith('xapp-') && !expandedSteps[4]) {+ if ((appToken.startsWith('xapp-') || (!appToken && hasUsableSecret(data.slack, 'app_token'))) && !expandedSteps[4]) {setExpandedSteps((prev) => ({ ...prev, 3: false, 4: true }));}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [appToken]);+ }, [appToken, data.slack]);const loadManifest = async () => {setManifestLoading(true);@@ -99,6 +105,7 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,};const runAuthTest = async () => {+ if (!botToken && !hasUsableSecret(data.slack, 'bot_token')) return;setChecking(true);try {const result = await api.slackAuthTest(botToken, proxyUrl);@@ -116,13 +123,16 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,const completedCount = [!!manifest, // step 1 done as soon as manifest is available (best heuristic without backend signal)- botToken.startsWith('xoxb-'),- appToken.startsWith('xapp-'),+ botToken.startsWith('xoxb-') || (!botToken && hasUsableSecret(data.slack, 'bot_token')),+ appToken.startsWith('xapp-') || (!appToken && hasUsableSecret(data.slack, 'app_token')),Boolean(authResult?.ok),].filter(Boolean).length;const buildSubmitData = () => ({- slack: { ...data.slack, bot_token: botToken, app_token: appToken, proxy_url: proxyUrl || undefined },+ slack: {+ ...withSecretDrafts(data.slack, { bot_token: botToken, app_token: appToken }),+ proxy_url: proxyUrl || undefined,+ },mode: 'self_host',});@@ -299,7 +309,11 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,variant="brand"size="sm"onClick={runAuthTest}- disabled={!botToken || !appToken || checking}+ disabled={+ (!botToken && !hasUsableSecret(data.slack, 'bot_token')) ||+ (!appToken && !hasUsableSecret(data.slack, 'app_token')) ||+ checking+ }>{checking ? <RefreshCw size={14} className="animate-spin" /> : <Shield size={14} strokeWidth={2.25} />}{t('slackConfig.validateTokens')}@@ -401,7 +415,7 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,variant="brand"size="default"onClick={() =>- onNext({ slack: { ...data.slack, bot_token: botToken, app_token: appToken, proxy_url: proxyUrl || undefined }, mode: 'self_host' })+ onNext(buildSubmitData())}disabled={!isValid}className="flex-1 sm:flex-none"diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex 687ecdac2..ec7acd79d 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -18,6 +18,7 @@ import { useStatus } from '../../context/StatusContext';import { useToast } from '../../context/ToastContext';import { copyTextToClipboard } from '../../lib/utils';import { getEnabledPlatforms, getPrimaryPlatform } from '../../lib/platforms';+import { withoutConfiguredSecretMarker, withSecretDraft, withSecretDrafts } from '../../lib/secretFields';import { EyebrowBadge, WizardCard } from '../visual';import { ToggleSwitch } from '../settings/SettingsPrimitives';import { Button } from '../ui/button';@@ -395,33 +396,36 @@ const buildConfigPayload = (data: any) => {mode: data.mode || 'self_host',version: 'v2',slack: {- ...data.slack,- bot_token: data.slack?.bot_token || '',- app_token: data.slack?.app_token || '',+ ...withSecretDrafts(data.slack, {+ bot_token: data.slack?.bot_token,+ app_token: data.slack?.app_token,+ }),require_mention: data.slack?.require_mention || false,},discord: {- ...data.discord,- bot_token: data.discord?.bot_token || '',+ ...withSecretDraft(data.discord, 'bot_token', data.discord?.bot_token),require_mention: data.discord?.require_mention || false,},telegram: {- ...data.telegram,- bot_token: data.telegram?.bot_token || '',+ ...withSecretDraft(data.telegram, 'bot_token', data.telegram?.bot_token),require_mention: data.telegram?.require_mention ?? true,forum_auto_topic: data.telegram?.forum_auto_topic ?? true,use_webhook: data.telegram?.use_webhook ?? false,},- lark: {- ...data.lark,- app_id: data.lark?.app_id || '',- app_secret: data.lark?.app_secret || '',- domain: data.lark?.domain || 'feishu',- require_mention: data.lark?.require_mention || false,- },+ lark: (() => {+ const lark = data.lark || {};+ const appId = lark.app_id || '';+ const appIdChanged = Boolean(lark.original_app_id && appId && appId !== lark.original_app_id);+ const base = appIdChanged ? withoutConfiguredSecretMarker(lark, 'app_secret') : lark;+ return {+ ...withSecretDraft(base, 'app_secret', lark.app_secret),+ app_id: appId,+ domain: lark.domain || 'feishu',+ require_mention: lark.require_mention || false,+ };+ })(),wechat: {- ...data.wechat,- bot_token: data.wechat?.bot_token || '',+ ...withSecretDraft(data.wechat, 'bot_token', data.wechat?.bot_token),base_url: data.wechat?.base_url || '',require_mention: data.wechat?.require_mention || false,},diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsxindex 250f777ad..470ae2747 100644--- a/ui/src/components/steps/TelegramConfig.tsx+++ b/ui/src/components/steps/TelegramConfig.tsx@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';+import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/secretFields';import { copyTextToClipboard } from '../../lib/utils';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';@@ -39,7 +40,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, onconst { t } = useTranslation();const api = useApi();const { showToast } = useToast();- const [botToken, setBotToken] = useState(data.telegram?.bot_token || '');+ const [botToken, setBotToken] = useState(secretInputValue(data.telegram, 'bot_token'));const [proxyUrl, setProxyUrl] = useState(data.telegram?.proxy_url || '');const [requireMention, setRequireMention] = useState(data.telegram?.require_mention ?? true);const [forumAutoTopic, setForumAutoTopic] = useState(data.telegram?.forum_auto_topic ?? true);@@ -55,7 +56,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on});const [copiedCommand, setCopiedCommand] = useState<string | null>(null);- const hasSavedToken = Boolean(data.telegram?.bot_token && botToken === data.telegram?.bot_token);+ const hasSavedToken = !botToken && hasUsableSecret(data.telegram, 'bot_token');useEffect(() => {setAuthResult(null);@@ -68,7 +69,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on}, [authResult?.ok, hasSavedToken, expandedSteps]);const isValid = useMemo(() => {- if (!botToken) return false;+ if (!botToken) return hasSavedToken;if (authResult?.ok) return true;return hasSavedToken;}, [authResult, botToken, hasSavedToken]);@@ -104,7 +105,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on};const completedCount = [- Boolean(botToken),+ hasUsableSecret(data.telegram, 'bot_token', botToken),isValid,Boolean(copiedCommand),expandedSteps[4],@@ -132,8 +133,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, onconst buildSubmitData = () => ({platform: 'telegram',telegram: {- ...(data.telegram || {}),- bot_token: botToken,+ ...withSecretDraft(data.telegram, 'bot_token', botToken),proxy_url: proxyUrl || undefined,require_mention: requireMention,forum_auto_topic: forumAutoTopic,@@ -238,7 +238,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, onvariant="brand"size="sm"onClick={runAuthTest}- disabled={!botToken || checking}+ disabled={(!botToken && !hasUsableSecret(data.telegram, 'bot_token')) || checking}>{checking ? <RefreshCw size={14} className="animate-spin" /> : <Shield size={14} strokeWidth={2.25} />}{t('telegramConfig.validateToken')}diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsxindex a7b0b01da..80315efe8 100644--- a/ui/src/components/steps/WeChatConfig.tsx+++ b/ui/src/components/steps/WeChatConfig.tsx@@ -14,6 +14,7 @@ import {import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';+import { hasUsableSecret, secretInputValue, withSecretDraft } from '../../lib/secretFields';import { EmbeddedConfigShell, EyebrowBadge, WizardCard } from '../visual';import { ProxyUrlField } from '../shared/ProxyUrlField';import { Button } from '../ui/button';@@ -41,7 +42,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBack>('idle');const [qrCodeUrl, setQrCodeUrl] = useState<string>('');const [message, setMessage] = useState<string>('');- const [botToken, setBotToken] = useState<string>(data.wechat?.bot_token || '');+ const [botToken, setBotToken] = useState<string>(secretInputValue(data.wechat, 'bot_token'));const [baseUrl, setBaseUrl] = useState<string>(data.wechat?.base_url || '');const [proxyUrl, setProxyUrl] = useState<string>(data.wechat?.proxy_url || '');const [starting, setStarting] = useState(false);@@ -121,11 +122,11 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBackif (autoStartedRef.current) return;if (starting) return;if (loginState !== 'idle') return;- if (data.wechat?.bot_token) return;+ if (hasUsableSecret(data.wechat, 'bot_token')) return;autoStartedRef.current = true;void startLogin();- }, [loginState, startLogin, starting, data.wechat?.bot_token]);+ }, [loginState, startLogin, starting, data.wechat]);const startPolling = (key: string) => {stopPolling();@@ -177,8 +178,8 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBackvoid pollOnce();};- const canProceed = !!botToken;- const isAlreadyBound = loginState === 'idle' && !!botToken;+ const canProceed = hasUsableSecret(data.wechat, 'bot_token', botToken);+ const isAlreadyBound = loginState === 'idle' && !botToken && hasUsableSecret(data.wechat, 'bot_token');const getStepState = () => {if (isAlreadyBound) return { step: 3, scanning: false, connected: true };@@ -198,8 +199,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({ data, onNext, onBackconst buildSubmitData = () => ({platform: 'wechat',wechat: {- ...(data.wechat || {}),- bot_token: botToken,+ ...withSecretDraft(data.wechat, 'bot_token', botToken),base_url: baseUrl,proxy_url: proxyUrl || undefined,},diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex a0d8c9a9e..9bb700f94 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -106,17 +106,17 @@ export type ApiContextType = {providerId: string,modelId: string,) => Promise<OpencodeMutationResult>;- slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;- slackChannels: (botToken: string, browseAll?: boolean, force?: boolean) => Promise<any>;+ slackAuthTest: (botToken?: string, proxyUrl?: string) => Promise<any>;+ slackChannels: (botToken?: string, browseAll?: boolean, force?: boolean) => Promise<any>;slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;- discordAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;- discordGuilds: (botToken: string) => Promise<any>;- discordChannels: (botToken: string, guildId: string, force?: boolean) => Promise<any>;- telegramAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;+ discordAuthTest: (botToken?: string, proxyUrl?: string) => Promise<any>;+ discordGuilds: (botToken?: string) => Promise<any>;+ discordChannels: (botToken: string | undefined, guildId: string, force?: boolean) => Promise<any>;+ telegramAuthTest: (botToken?: string, proxyUrl?: string) => Promise<any>;telegramChats: (includePrivate?: boolean) => Promise<any>;- larkAuthTest: (appId: string, appSecret: string, domain?: string, proxyUrl?: string) => Promise<any>;- larkChats: (appId: string, appSecret: string, domain?: string, force?: boolean) => Promise<any>;- larkTempWsStart: (appId: string, appSecret: string, domain?: string) => Promise<any>;+ larkAuthTest: (appId: string, appSecret?: string, domain?: string, proxyUrl?: string) => Promise<any>;+ larkChats: (appId: string, appSecret?: string, domain?: string, force?: boolean) => Promise<any>;+ larkTempWsStart: (appId: string, appSecret?: string, domain?: string) => Promise<any>;larkTempWsStop: () => Promise<any>;wechatStartLogin: () => Promise<any>;wechatPollLogin: (sessionKey: string) => Promise<any>;diff --git a/ui/src/lib/platforms.ts b/ui/src/lib/platforms.tsindex 022f69f75..02aed8984 100644--- a/ui/src/lib/platforms.ts+++ b/ui/src/lib/platforms.ts@@ -208,7 +208,7 @@ export const platformHasCredentials = (data: any, platform: string): boolean =>if (!platformConfig || credentialFields.length === 0) {return false;}- return credentialFields.every((field) => !!platformConfig?.[field]);+ return credentialFields.every((field) => !!platformConfig?.[field] || !!platformConfig?.[`has_${field}`]);};export const hasConfiguredPlatformCredentials = (data: any): boolean =>diff --git a/ui/src/lib/secretFields.ts b/ui/src/lib/secretFields.tsnew file mode 100644index 000000000..e20f78ecb--- /dev/null+++ b/ui/src/lib/secretFields.ts@@ -0,0 +1,49 @@+type SecretSection = Record<string, any> | null | undefined;++export const hasConfiguredSecret = (section: SecretSection, field: string): boolean =>+ Boolean(section?.[`has_${field}`]);++export const secretInputValue = (section: SecretSection, field: string): string => {+ const value = section?.[field];+ return typeof value === 'string' ? value : '';+};++export const hasUsableSecret = (section: SecretSection, field: string, draftValue?: string): boolean =>+ Boolean(draftValue) || hasConfiguredSecret(section, field);++export const withSecretDraft = (+ section: SecretSection,+ field: string,+ draftValue: string | null | undefined+): Record<string, any> => {+ const next = { ...(section || {}) };+ const value = typeof draftValue === 'string' ? draftValue.trim() : '';+ if (value) {+ delete next[`has_${field}`];+ delete next[`${field}_length`];+ next[field] = draftValue;+ } else if (hasConfiguredSecret(section, field)) {+ delete next[field];+ } else {+ delete next[`has_${field}`];+ delete next[`${field}_length`];+ next[field] = '';+ }+ return next;+};++export const withSecretDrafts = (+ section: SecretSection,+ drafts: Record<string, string | null | undefined>+): Record<string, any> =>+ Object.entries(drafts).reduce(+ (current, [field, value]) => withSecretDraft(current, field, value),+ { ...(section || {}) }+ );++export const withoutConfiguredSecretMarker = (section: SecretSection, field: string): Record<string, any> => {+ const next = { ...(section || {}) };+ delete next[`has_${field}`];+ delete next[`${field}_length`];+ return next;+};diff --git a/vibe/api.py b/vibe/api.pyindex 661448b8c..71d40ebd1 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -70,6 +70,17 @@ logger = logging.getLogger(__name__)_OPENCODE_OPTIONS_CACHE: dict[str, dict] = {}_OPENCODE_OPTIONS_TTL_SECONDS = 30.0++_PLATFORM_SECRET_FIELDS: dict[str, tuple[str, ...]] = {+ "slack": ("bot_token", "app_token", "signing_secret"),+ "discord": ("bot_token",),+ "telegram": ("bot_token", "webhook_secret_token"),+ "lark": ("app_secret",),+ "wechat": ("bot_token",),+}+_GATEWAY_SECRET_FIELDS = ("workspace_token", "client_secret")++def _parse_agent_import_file(path: Path, *, backend: str):try:return parse_agent_file(path, backend=backend)@@ -77,6 +88,32 @@ def _parse_agent_import_file(path: Path, *, backend: str):raise ValueError(f"Unable to read or parse agent import file: {exc}") from exc+def _validate_direct_agent_import_path(path: Path) -> Path:+ try:+ resolved = path.resolve(strict=False)+ except OSError as exc:+ raise ValueError(f"Unable to validate agent import file: {exc}") from exc+ if resolved.suffix.lower() != ".md":+ raise ValueError("Agent import file must be a Markdown (.md) file")+ try:+ raw = resolved.read_text(encoding="utf-8")+ except (OSError, UnicodeError) as exc:+ raise ValueError(f"Unable to read or parse agent import file: {exc}") from exc+ lines = raw.splitlines()+ if not lines or lines[0].strip() != "---":+ raise ValueError("Agent import file must include YAML frontmatter with a name field")+ end_idx = next((idx for idx, line in enumerate(lines[1:], start=1) if line.strip() == "---"), -1)+ if end_idx < 0:+ raise ValueError("Agent import file must include YAML frontmatter with a name field")+ try:+ header = yaml.safe_load("\n".join(lines[1:end_idx])) or {}+ except yaml.YAMLError as exc:+ raise ValueError(f"Unable to read or parse agent import file: {exc}") from exc+ if not isinstance(header, dict) or not str(header.get("name") or "").strip():+ raise ValueError("Agent import file must include YAML frontmatter with a name field")+ return resolved++def _enabled_agent_backends_from_config(config: Optional[V2Config] = None) -> list[str]:try:cfg = config or load_config()@@ -584,6 +621,36 @@ def _strip_agent_auth_fields(payload: dict) -> dict:return {**payload, "agents": cleaned_agents}+def _strip_preserved_config_secrets(payload: dict) -> dict:+ """Drop redacted secret placeholders from generic config saves.++ ``GET /api/config`` now returns ``has_<field>`` metadata instead of+ plaintext platform and gateway secrets. Older UI paths may still round-trip+ an empty string for such a field; when the metadata says the secret is+ already configured, an empty submitted value means "unchanged", not "clear".+ """+ if not isinstance(payload, dict):+ return payload+ cleaned = dict(payload)+ for config_key, fields in _PLATFORM_SECRET_FIELDS.items():+ section = cleaned.get(config_key)+ if not isinstance(section, dict):+ continue+ next_section = dict(section)+ for field in fields:+ if next_section.get(f"has_{field}") is True and not next_section.get(field):+ next_section.pop(field, None)+ cleaned[config_key] = next_section+ gateway = cleaned.get("gateway")+ if isinstance(gateway, dict):+ next_gateway = dict(gateway)+ for field in _GATEWAY_SECRET_FIELDS:+ if next_gateway.get(f"has_{field}") is True and not next_gateway.get(field):+ next_gateway.pop(field, None)+ cleaned["gateway"] = next_gateway+ return cleaned++def _mark_explicit_audio_asr_enabled(payload: dict) -> dict:"""Record explicit ASR enablement changes from config API payloads.@@ -605,6 +672,7 @@ def save_config(payload: dict) -> V2Config:raise ValueError("Config payload must be an object")payload = _strip_agent_auth_fields(payload)+ payload = _strip_preserved_config_secrets(payload)payload = _mark_explicit_audio_asr_enabled(payload)with CONFIG_LOCK:@@ -682,6 +750,23 @@ def _agent_payload(raw: dict, *, include_secrets: bool) -> dict:return payload+def _project_secret_fields(payload: dict | None, fields: tuple[str, ...], *, include_secrets: bool) -> dict | None:+ if payload is None:+ return None+ projected = dict(payload)+ for field in fields:+ value = projected.get(field)+ if isinstance(value, str):+ projected[f"has_{field}"] = bool(value)+ projected[f"{field}_length"] = len(value)+ else:+ projected[f"has_{field}"] = False+ projected[f"{field}_length"] = 0+ if not include_secrets:+ projected.pop(field, None)+ return projected++def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dict:from config.platform_registry import platform_descriptorsfrom modules.agents.catalog import agent_backend_catalog_payload@@ -689,7 +774,12 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dicplatform_payload = {}for descriptor in platform_descriptors():descriptor_config = descriptor.get_config(config)- platform_payload[descriptor.config_key] = descriptor_config.__dict__.copy() if descriptor_config else None+ raw = descriptor_config.__dict__.copy() if descriptor_config else None+ platform_payload[descriptor.config_key] = _project_secret_fields(+ raw,+ _PLATFORM_SECRET_FIELDS.get(descriptor.config_key, ()),+ include_secrets=include_secrets,+ )if isinstance(platform_payload.get("discord"), dict):platform_payload["discord"].pop("guild_allowlist", None)platform_payload["discord"].pop("guild_denylist", None)@@ -715,7 +805,11 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic"claude": _agent_payload(config.agents.claude.__dict__, include_secrets=include_secrets),"codex": _agent_payload(config.agents.codex.__dict__, include_secrets=include_secrets),},- "gateway": config.gateway.__dict__ if config.gateway else None,+ "gateway": _project_secret_fields(+ config.gateway.__dict__ if config.gateway else None,+ _GATEWAY_SECRET_FIELDS,+ include_secrets=include_secrets,+ ),"ui": config.ui.__dict__,"remote_access": {"provider": config.remote_access.provider,@@ -1025,7 +1119,8 @@ def import_vibe_agents(payload: dict) -> dict:if name or import_all:raise ValueError("name and all are only valid with from")backend = validate_agent_backend(str(payload.get("backend") or ""))- candidates.append(_parse_agent_import_file(Path(file_path).expanduser(), backend=backend))+ path = _validate_direct_agent_import_path(Path(file_path).expanduser())+ candidates.append(_parse_agent_import_file(path, backend=backend))else:if source not in {"claude", "codex", "opencode"}:raise ValueError("from must be one of: claude, codex, opencode")@@ -1237,7 +1332,28 @@ def check_cli_exec(path: str) -> dict:return {"ok": True}+def _stored_platform_config(platform: str) -> Any | None:+ try:+ config = load_config()+ except FileNotFoundError:+ return None+ return getattr(config, platform, None)+++def _stored_platform_secret(platform: str, field: str) -> str:+ platform_config = _stored_platform_config(platform)+ value = getattr(platform_config, field, "") if platform_config else ""+ return value if isinstance(value, str) else ""+++def _stored_platform_field(platform: str, field: str, default: str = "") -> str:+ platform_config = _stored_platform_config(platform)+ value = getattr(platform_config, field, default) if platform_config else default+ return value if isinstance(value, str) else default++def slack_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:+ bot_token = bot_token or _stored_platform_secret("slack", "bot_token")try:from slack_sdk.web import WebClientfrom vibe.proxy import resolve_proxy@@ -1253,6 +1369,7 @@ def slack_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:def list_channels(bot_token: str, browse_all: bool = False, force: bool = False) -> dict:from core import chat_discovery+ bot_token = bot_token or _stored_platform_secret("slack", "bot_token")return chat_discovery.channels_response("slack",bot_token=bot_token,@@ -1345,6 +1462,7 @@ def discord_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:async def discord_auth_test_async(bot_token: str, proxy_url: str | None = None) -> dict:+ bot_token = bot_token or _stored_platform_secret("discord", "bot_token")try:data = await _discord_api_get_async(bot_token, "users/@me", proxy_url=proxy_url)return {"ok": True, "response": data}@@ -1359,6 +1477,7 @@ def telegram_auth_test(bot_token: str, proxy_url: str | None = None) -> dict:async def telegram_auth_test_async(bot_token: str, proxy_url: str | None = None) -> dict:+ bot_token = bot_token or _stored_platform_secret("telegram", "bot_token")try:from vibe.proxy import resolve_proxy@@ -1384,6 +1503,7 @@ def discord_list_guilds(bot_token: str) -> dict:async def discord_list_guilds_async(bot_token: str) -> dict:+ bot_token = bot_token or _stored_platform_secret("discord", "bot_token")try:data = await _discord_api_get_async(bot_token, "users/@me/guilds")return {"ok": True, "guilds": data}@@ -1409,6 +1529,7 @@ def discord_list_channels(bot_token: str, guild_id: str, force: bool = False) ->from storage.settings_service import make_scope_id+ bot_token = bot_token or _stored_platform_secret("discord", "bot_token")parent_scope_id = make_scope_id("discord", "guild", guild_id)return chat_discovery.channels_response("discord",@@ -6320,6 +6441,9 @@ def lark_auth_test(domain: str = "feishu",proxy_url: str | None = None,) -> dict:+ app_id = app_id or _stored_platform_field("lark", "app_id")+ app_secret = app_secret or _stored_platform_secret("lark", "app_secret")+ domain = domain or _stored_platform_field("lark", "domain", "feishu")from vibe.proxy import resolve_proxyproxy = resolve_proxy(proxy_url)@@ -6344,6 +6468,9 @@ async def lark_auth_test_async((``lark-oapi``) has no proxy hook and bypasses it — that limitation issurfaced by ``modules/im/feishu.py`` once at adapter init."""+ app_id = app_id or _stored_platform_field("lark", "app_id")+ app_secret = app_secret or _stored_platform_secret("lark", "app_secret")+ domain = domain or _stored_platform_field("lark", "domain", "feishu")from vibe.proxy import resolve_proxyproxy = resolve_proxy(proxy_url)@@ -6359,6 +6486,9 @@ async def lark_auth_test_async(def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu", force: bool = False) -> dict:from core import chat_discovery+ app_id = app_id or _stored_platform_field("lark", "app_id")+ app_secret = app_secret or _stored_platform_secret("lark", "app_secret")+ domain = domain or _stored_platform_field("lark", "domain", "feishu")return chat_discovery.channels_response("lark",app_id=app_id,@@ -6618,6 +6748,9 @@ def lark_temp_ws_start(app_id: str, app_secret: str, domain: str = "feishu") ->"""Start a temporary WebSocket connection so the Feishu console shows the long-connection option."""global _temp_ws_client, _temp_ws_thread+ app_id = app_id or _stored_platform_field("lark", "app_id")+ app_secret = app_secret or _stored_platform_secret("lark", "app_secret")+ domain = domain or _stored_platform_field("lark", "domain", "feishu")with _temp_ws_lock:# Stop any existing temp connection first_stop_temp_ws_internal()