Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(credentials): AI provider icons, stored-key indicator, API key input
trohitg0947455aaedb
diff --git a/client/src/components/credentials/CredentialsPalette.tsx b/client/src/components/credentials/CredentialsPalette.tsxindex e2a29158..5ae7a467 100644--- a/client/src/components/credentials/CredentialsPalette.tsx+++ b/client/src/components/credentials/CredentialsPalette.tsx@@ -34,7 +34,7 @@ import React, {import { Command } from 'cmdk';import { GroupedVirtuoso } from 'react-virtuoso';import fuzzysort from 'fuzzysort';-import { Flex, Input } from 'antd';+import { Badge, Flex, Input } from 'antd';import { SearchOutlined } from '@ant-design/icons';import type { ProviderConfig, CategoryGroup } from './types';@@ -49,6 +49,8 @@ export interface CredentialsPaletteProps {categories: CategoryGroup[];selectedId: string | null;onSelect: (id: string) => void;+ /** Map of provider id → has stored/validated key. Drives the green status dot. */+ storedKeys?: Record<string, boolean>;/** Height of the scrollable list area. */height?: number | string;/** Optional placeholder for the search input. */@@ -175,9 +177,12 @@ const ProviderRow = memo<RowProps>(function ProviderRow({ provider, selected, on><Icon size={parseInt(theme.iconSize.sm)} /></Flex>- <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{provider.name}</span>+ {provider.stored && (+ <Badge status="success" />+ )}</Command.Item>);});diff --git a/client/src/components/credentials/catalogueAdapter.ts b/client/src/components/credentials/catalogueAdapter.tsindex b65f468b..5d92f9f6 100644--- a/client/src/components/credentials/catalogueAdapter.ts+++ b/client/src/components/credentials/catalogueAdapter.ts@@ -20,11 +20,11 @@import React from 'react';import { AI_PROVIDER_META } from '../icons/AIProviderIcons';-import { ApifyIcons } from '../../assets/icons/apify';-import { SearchIcons } from '../../assets/icons/search';-import { TelegramIcons } from '../../assets/icons/telegram';-import { GoogleIcons } from '../../assets/icons/google';-import { EmailIcons } from '../../assets/icons/email';+import { APIFY_ICON } from '../../assets/icons/apify';+import { BRAVE_SEARCH_ICON, SERPER_ICON, PERPLEXITY_ICON } from '../../assets/icons/search';+import { TELEGRAM_ICON } from '../../assets/icons/telegram';+import { GMAIL_ICON } from '../../assets/icons/google';+import { EMAIL_READ_ICON } from '../../assets/icons/email';import { WHATSAPP_CONNECT_ICON } from '../../nodeDefinitions/whatsappNodes';import { TWITTER_ICON } from '../../nodeDefinitions/twitterNodes';@@ -48,25 +48,17 @@ import type {} from '../../hooks/useCatalogueQuery';// ============================================================================-// Icon factories — duplicated from providers.tsx to keep this adapter-// self-contained. Keep in sync until providers.tsx is deleted in Phase 8.+// Icon factories — uses <img> with data URIs (the project standard from+// assets/icons/*/index.ts). No innerHTML, no dangerouslySetInnerHTML,+// no ref+useEffect. Every icon module already exports svgToDataUri'd+// constants; we import those directly and render as <img>.// ============================================================================interface IconProps {size: number;}-const fromRawSvg = (rawSvg: string): React.FC<IconProps> => {- const Comp: React.FC<IconProps> = ({ size }) => {- const ref = React.useRef<HTMLDivElement>(null);- React.useEffect(() => {- if (ref.current) ref.current.innerHTML = rawSvg;- }, []);- return React.createElement('div', { ref, style: { width: size, height: size } });- };- return Comp;-};-+/** Render a data:image/svg+xml URI as a sized <img>. Project standard. */const fromDataUri = (dataUri: string): React.FC<IconProps> => {const Comp: React.FC<IconProps> = ({ size }) =>React.createElement('img', {@@ -89,32 +81,23 @@ const fromEmoji = (emoji: string): React.FC<IconProps> => {return Comp;};-// Apify needs the root <svg> scaled to 100% of the wrapper.-const ApifyIconC: React.FC<IconProps> = ({ size }) => {- const scaled = ApifyIcons.apify.replace('<svg', '<svg width="100%" height="100%"');- return React.createElement('div', {- dangerouslySetInnerHTML: { __html: scaled },- style: { width: size, height: size },- });-};-// ============================================================================// Icon ref resolver//// JSON `icon_ref` values use a small DSL:-// "ai:openai" → AI_PROVIDER_META[openai].Icon-// "raw_svg:SearchIcons.brave" → fromRawSvg(SearchIcons.brave)-// "raw_svg:ApifyIcons.apify" → ApifyIconC (needs explicit scale)-// "data_uri:WHATSAPP_CONNECT_ICON" → fromDataUri(WHATSAPP_CONNECT_ICON)-// "emoji:📱" → fromEmoji('📱')+// "ai:openai" → AI_PROVIDER_META[openai].Icon (@lobehub/icons)+// "raw_svg:SearchIcons.brave" → <img> with pre-exported data URI (BRAVE_SEARCH_ICON)+// "data_uri:WHATSAPP_CONNECT_ICON" → <img> with data URI+// "emoji:📱" → <span> with emoji text// ============================================================================-const RAW_SVG_REGISTRY: Record<string, Record<string, string>> = {- SearchIcons,- TelegramIcons,- GoogleIcons,- EmailIcons,- ApifyIcons,+/** Map "Module.key" strings to already-converted data URIs from assets/icons/. */+const RAW_SVG_DATA_URIS: Record<string, Record<string, string>> = {+ SearchIcons: { brave: BRAVE_SEARCH_ICON, serper: SERPER_ICON, perplexity: PERPLEXITY_ICON },+ TelegramIcons: { telegram: TELEGRAM_ICON },+ GoogleIcons: { gmail: GMAIL_ICON },+ EmailIcons: { read: EMAIL_READ_ICON },+ ApifyIcons: { apify: APIFY_ICON },};const DATA_URI_REGISTRY: Record<string, string> = {@@ -163,12 +146,10 @@ function resolveIcon(iconRef: string | undefined, providerId: string): React.FC<return meta?.Icon ?? fallbackIcon(initial);}case 'raw_svg': {- // e.g. "SearchIcons.brave"+ // e.g. "SearchIcons.brave" → look up pre-exported data URIconst [module, key] = rest.split('.');- if (module === 'ApifyIcons' && key === 'apify') return ApifyIconC;- const svgMap = RAW_SVG_REGISTRY[module];- const svg = svgMap?.[key];- return svg ? fromRawSvg(svg) : fallbackIcon(initial);+ const uri = RAW_SVG_DATA_URIS[module]?.[key];+ return uri ? fromDataUri(uri) : fallbackIcon(initial);}case 'data_uri': {const uri = DATA_URI_REGISTRY[rest];@@ -303,6 +284,7 @@ export function rehydrateProvider(entry: ServerProviderConfig): ProviderConfig {hasDefaults: entry.has_defaults,hasRateLimits: entry.has_rate_limits,usageService: entry.usage_service,+ stored: entry.stored,};}diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsxindex 73d3401b..63138ff6 100644--- a/client/src/components/credentials/panels/ApiKeyPanel.tsx+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx@@ -3,7 +3,7 @@* Composes: Card header + ApiKeyInput. Config-driven, zero per-provider JSX.*/-import React from 'react';+import React, { useState, useEffect } from 'react';import { Alert, Card, Tag, Flex } from 'antd';import { CheckCircleOutlined } from '@ant-design/icons';import ApiKeyInput from '../../ui/ApiKeyInput';@@ -20,6 +20,26 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ cconst iconSize = parseInt(theme.iconSize.md);const tagOk = { backgroundColor: `${theme.dracula.green}25`, borderColor: `${theme.dracula.green}60`, color: theme.dracula.green };+ // Local state for the controlled input. antd Form.getFieldValue/setFieldValue+ // are snapshots that don't trigger re-renders — using them as a controlled+ // input's value prop causes typing to be silently rejected. useState is the+ // standard React pattern for controlled inputs.+ const [inputValue, setInputValue] = useState('');++ // Sync from the form when stored credentials load (useCredentialPanel+ // populates the form asynchronously via getStoredApiKey on mount).+ useEffect(() => {+ if (panel.stored && field) {+ const v = panel.form.getFieldValue(field.key);+ if (v) setInputValue(v);+ }+ }, [panel.stored, field, panel.form]);++ // Reset input when switching providers+ useEffect(() => {+ setInputValue('');+ }, [config.id]);+return (<Flex vertical gap={theme.spacing.xl} style={{ padding: theme.spacing.xl }}><Card size="small" styles={{ body: { padding: theme.spacing.lg } }}@@ -32,10 +52,10 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ c</Flex>}extra={panel.stored ? <Tag icon={<CheckCircleOutlined />} style={tagOk}>Connected</Tag> : null}>{field && <ApiKeyInput- value={panel.form.getFieldValue(field.key) || ''}- onChange={v => { panel.form.setFieldValue(field.key, v); panel.setStored(false); }}- onSave={() => panel.actions.validate(config.id, panel.form.getFieldValue(field.key)?.trim()).then(r => { if (r?.isValid) panel.setStored(true); })}- onDelete={panel.stored ? () => panel.actions.remove(config.id) : undefined}+ value={inputValue}+ onChange={v => { setInputValue(v); panel.form.setFieldValue(field.key, v); panel.setStored(false); }}+ onSave={() => panel.actions.validate(config.id, inputValue.trim()).then(r => { if (r?.isValid) panel.setStored(true); })}+ onDelete={panel.stored ? () => { panel.actions.remove(config.id); setInputValue(''); } : undefined}placeholder={field.placeholder}loading={panel.loading === 'validate'}isStored={panel.stored}diff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsindex e7e6a404..26831472 100644--- a/client/src/components/credentials/types.ts+++ b/client/src/components/credentials/types.ts@@ -110,6 +110,8 @@ export interface ProviderConfig {hasRateLimits?: boolean;/** Service key for API cost tracking section (twitter, google_workspace, google_maps). */usageService?: string;+ /** Server-resolved: whether a key/token exists in the credentials DB. */+ stored?: boolean;}// ============================================================================diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex 66e88ae0..dda7fdd4 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -102,6 +102,8 @@ export interface ServerProviderConfig {has_defaults?: boolean;has_rate_limits?: boolean;usage_service?: string;+ /** Server-resolved: whether a key/token is stored in the credentials DB. */+ stored?: boolean;}export interface CatalogueResponse {diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex fa322667..a676ba7e 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -21,7 +21,6 @@"category_label": "AI Providers","kind": "apiKey","has_defaults": true,- "icon_ref": "ai:${id}","fields": [{"key": "apiKey",@@ -37,6 +36,7 @@"extends": "_ai_base","name": "OpenAI","color": "dracula.green",+ "icon_ref": "ai:openai","fields": [{ "key": "apiKey", "placeholder": "sk-..." }]@@ -45,6 +45,7 @@"extends": "_ai_base","name": "Anthropic","color": "dracula.orange",+ "icon_ref": "ai:anthropic","fields": [{ "key": "apiKey", "placeholder": "sk-ant-..." }]@@ -53,6 +54,7 @@"extends": "_ai_base","name": "Gemini","color": "solarized.blue",+ "icon_ref": "ai:gemini","fields": [{ "key": "apiKey", "placeholder": "AIza..." }]@@ -61,6 +63,7 @@"extends": "_ai_base","name": "Groq","color": "dracula.red",+ "icon_ref": "ai:groq","fields": [{ "key": "apiKey", "placeholder": "gsk_..." }]@@ -69,6 +72,7 @@"extends": "_ai_base","name": "Cerebras","color": "dracula.orange",+ "icon_ref": "ai:cerebras","fields": [{ "key": "apiKey", "placeholder": "csk-..." }]@@ -77,6 +81,7 @@"extends": "_ai_base","name": "OpenRouter","color": "solarized.violet",+ "icon_ref": "ai:openrouter","fields": [{ "key": "apiKey", "placeholder": "sk-or-..." }]@@ -85,6 +90,7 @@"extends": "_ai_base","name": "DeepSeek","color": "dracula.cyan",+ "icon_ref": "ai:deepseek","fields": [{ "key": "apiKey", "placeholder": "sk-..." }]@@ -93,12 +99,14 @@"extends": "_ai_base","name": "Kimi","color": "dracula.purple",+ "icon_ref": "ai:kimi","fields": [{ "key": "apiKey", "placeholder": "sk-..." }]},"mistral": {"extends": "_ai_base",+ "icon_ref": "ai:mistral","name": "Mistral","color": "dracula.pink","fields": [diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 1dbd434f..207bc187 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -239,24 +239,48 @@ async def handle_get_all_tool_schemas(data: Dict[str, Any], websocket: WebSocket@ws_handler()async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Return the full credential provider catalogue.+ """Return the full credential provider catalogue with live stored-key status.- Response shape: {providers, categories, version}. The version is a- content-sha256 of the resolved payload; clients warm-start from- IndexedDB and only re-fetch when the version changes. Supports- Nango-style bulk fetch at modal-open time (one roundtrip, cached for- the app session via TanStack Query + experimental_createPersister).+ Response shape: {providers, categories, version}. Each provider includes+ a `stored: boolean` field indicating whether a key/token is present in the+ encrypted credentials database. The frontend renders this directly — no+ client-side credential checks needed."""from services.credential_registry import get_credential_registryregistry = get_credential_registry()- # Optional conditional fetch: if the client already has the current- # version in IndexedDB it can send `since` and get a 304-style response.since = data.get("since")version = registry.get_version()if since and since == version:return {"unchanged": True, "version": version}- return registry.get_catalogue()++ catalogue = registry.get_catalogue()++ # Enrich each provider with live stored-key status from AuthService.+ # This keeps credential state as a backend concern — the frontend is+ # purely a renderer with zero business logic about key existence.+ auth_service = container.auth_service()+ for provider in catalogue.get("providers", []):+ pid = provider.get("id", "")+ kind = provider.get("kind", "")+ status_hook = provider.get("status_hook")++ if status_hook:+ # Status-hook providers (whatsapp, android, twitter, google, telegram)+ # use OAuth tokens or special connection state.+ tokens = await auth_service.get_oauth_tokens(status_hook)+ provider["stored"] = tokens is not None+ elif kind == "apiKey":+ # API key providers — check encrypted credentials DB.+ provider["stored"] = await auth_service.has_valid_key(pid)+ elif kind == "oauth":+ # OAuth providers without a status_hook — check token storage.+ tokens = await auth_service.get_oauth_tokens(pid)+ provider["stored"] = tokens is not None+ else:+ provider["stored"] = False++ return catalogue# ============================================================================