Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(credentials): brand-name canonical alignment — catalogue key == cls.id == co-located SVG basename
trohitgcd6ba4eeb567
diff --git a/client/src/hooks/__tests__/useApiKeys.test.ts b/client/src/hooks/__tests__/useApiKeys.test.tsindex 4d51877b..11f31b5a 100644--- a/client/src/hooks/__tests__/useApiKeys.test.ts+++ b/client/src/hooks/__tests__/useApiKeys.test.ts@@ -156,10 +156,10 @@ describe('useApiKeys.saveApiKey', () => {let res: any;await act(async () => {- res = await result.current.saveApiKey('telegram_bot_token', '123:abc');+ res = await result.current.saveApiKey('telegram', '123:abc');});- expect(wsMock.saveApiKey).toHaveBeenCalledWith('telegram_bot_token', '123:abc');+ expect(wsMock.saveApiKey).toHaveBeenCalledWith('telegram', '123:abc');expect(res.isValid).toBe(true);});diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex cb1633e6..d1a6a638 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -192,13 +192,13 @@}},- "whatsapp_personal": {+ "whatsapp": {"name": "WhatsApp Personal","category": "social","category_label": "Social Media","color": "theme.categoryWhatsapp","kind": "qrPairing",- "icon_ref": "/api/schemas/credentials/whatsapp_personal/icon",+ "icon_ref": "/api/schemas/credentials/whatsapp/icon","status_hook": "whatsapp","has_rate_limits": true,"status_rows": [@@ -265,10 +265,10 @@"kind": "oauth","icon_ref": "/api/schemas/credentials/telegram/icon","status_hook": "telegram",- "_stored_check_note": "Telegram uses status_hook for runtime connection state but stores the bot token via api_key (telegram_bot_token), not OAuth. Override the catalogue handler's default get_oauth_tokens(status_hook) lookup so the connected/stored badge reflects bot-token presence.",+ "_stored_check_note": "Telegram uses status_hook for runtime connection state but stores the bot token via api_key (under the canonical 'telegram' id), not OAuth. Override the catalogue handler's default get_oauth_tokens(status_hook) lookup so the connected/stored badge reflects bot-token presence.","stored_check": {"type": "api_key",- "key": "telegram_bot_token"+ "key": "telegram"},"ws": {"login": "telegram_connect",@@ -277,7 +277,7 @@},"fields": [{- "key": "telegram_bot_token",+ "key": "telegram","label": "Bot Token","type": "password","secret": true,@@ -297,13 +297,13 @@"instructions": "Get a bot token from @BotFather on Telegram. To use the 'Self' recipient on telegramSend, either fill in your Chat ID below or DM your bot once after connecting."},- "gmail": {+ "google": {"name": "Google Workspace","category": "productivity","category_label": "Productivity","color": "theme.categoryAI","kind": "oauth",- "icon_ref": "/api/schemas/credentials/gmail/icon",+ "icon_ref": "/api/schemas/credentials/google/icon","status_hook": "google","usage_service": "google_workspace","ws": {diff --git a/server/credentials/icons/gmail.svg b/server/nodes/google/google.svgsimilarity index 100%rename from server/credentials/icons/gmail.svgrename to server/nodes/google/google.svgdiff --git a/server/nodes/telegram/_credentials.py b/server/nodes/telegram/_credentials.pyindex c3189973..629bd327 100644--- a/server/nodes/telegram/_credentials.py+++ b/server/nodes/telegram/_credentials.py@@ -19,7 +19,7 @@ _TELEGRAM_API = "https://api.telegram.org"class TelegramCredential(ApiKeyCredential):- id = "telegram_bot_token"+ id = "telegram"display_name = "Telegram Bot"category = "Social"key_name = "" # not used — python-telegram-bot takes the token directlydiff --git a/server/nodes/telegram/_service.py b/server/nodes/telegram/_service.pyindex dbcd5a43..0a9d12fd 100644--- a/server/nodes/telegram/_service.py+++ b/server/nodes/telegram/_service.py@@ -30,7 +30,7 @@ Public surface (consumed by `_handlers.py`, `telegram_send.py`,handlers.Auth lookups go through :class:`TelegramCredential.resolve` (lifted from-the per-key ``auth.get_api_key("telegram_bot_token")`` / ``..._owner_chat_id``+the per-key ``auth.get_api_key("telegram")`` / ``..._owner_chat_id``calls scattered across the previous handler/router code). The credentialclass stays declarative — :class:`ApiKeyCredential` does the heavy lifting,this service just consumes the resolved dict.@@ -165,7 +165,7 @@ class TelegramService(ServiceSingleton):# =========================================================================async def has_stored_token(self) -> bool:- """Whether `telegram_bot_token` is persisted in auth credentials."""+ """Whether the `telegram` bot-token credential is persisted in auth."""try:secrets = await TelegramCredential.resolve()return bool(secrets.get("api_key"))@@ -175,17 +175,16 @@ class TelegramService(ServiceSingleton):async def connect(self, token: Optional[str] = None) -> Dict[str, Any]:"""Connect to Telegram with bot token and start polling.- When ``token`` is omitted, falls back to the stored- ``telegram_bot_token`` credential — matches the Twitter/Google- OAuth pattern where the frontend saves credentials first and then- calls connect.+ When ``token`` is omitted, falls back to the stored ``telegram``+ bot-token credential — matches the Twitter/Google OAuth pattern+ where the frontend saves credentials first and then calls connect.Idempotent: if already connected, returns success without tearingdown the working bot. See the in-line comment block for the racethis guards against."""# Resolve credentials via the declarative class instead of raw- # ``auth.get_api_key("telegram_bot_token")`` / ``..._owner_chat_id``+ # ``auth.get_api_key("telegram")`` / ``..._owner_chat_id``# lookups. Keeps the credential id in one place.secrets: Dict[str, Any] = {}if not token:diff --git a/server/credentials/icons/telegram.svg b/server/nodes/telegram/telegram.svgsimilarity index 100%rename from server/credentials/icons/telegram.svgrename to server/nodes/telegram/telegram.svgdiff --git a/server/nodes/telegram/telegram_send.py b/server/nodes/telegram/telegram_send.pyindex 0d075b52..1d64d86b 100644--- a/server/nodes/telegram/telegram_send.py+++ b/server/nodes/telegram/telegram_send.py@@ -1,9 +1,10 @@"""Telegram Send — Wave 11.C migration.Workflow-only ActionNode (no AI-tool exposure). The Telegram bot-token lives in ``auth_service`` under ``telegram_bot_token``. Plugin-delegates to the legacy ``handle_telegram_send`` handler during-thin-migration; 11.E converts to a declarative ``TelegramCredential``.+token lives in ``auth_service`` under the ``telegram`` credential id+(was ``telegram_bot_token`` pre-rename). Plugin delegates to the+legacy ``handle_telegram_send`` handler during thin-migration; 11.E+converts to a declarative ``TelegramCredential``."""from __future__ import annotationsdiff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.pyindex 1dd86a4d..1767cb21 100644--- a/server/nodes/whatsapp/__init__.py+++ b/server/nodes/whatsapp/__init__.py@@ -26,6 +26,7 @@ from services.ws_handler_registry import (register_ws_handlers,)+from ._credentials import WhatsAppCredential # noqa: F401 — side-effect registerfrom ._events import ( # noqa: F401 — re-exported for callersbroadcast_whatsapp_history_synced,broadcast_whatsapp_message,diff --git a/server/nodes/whatsapp/_credentials.py b/server/nodes/whatsapp/_credentials.pynew file mode 100644index 00000000..ffa23239--- /dev/null+++ b/server/nodes/whatsapp/_credentials.py@@ -0,0 +1,44 @@+"""WhatsApp Personal credential stub.++WhatsApp's "personal" connection is QR-paired session-based — the bot+binary (``edgymeow``) handles the WebSocket session lifecycle and there's+no API key / OAuth token to store. The credential class exists only so+``CREDENTIAL_REGISTRY`` can resolve the ``whatsapp`` provider+key (for catalogue icon lookup via+:meth:`services.plugin.credential.Credential.get_icon_path`). It does+NOT implement ``resolve()`` — connection-state queries go through the+``whatsapp_status`` WebSocket flow + the QR-pairing UI, not through+``auth_service.get_*``.++See ``server/config/credential_providers.json`` (entry+``whatsapp``) for the catalogue-level declaration of the QR+pairing UI / status rows / actions. This module's only job is to make+the icon endpoint find ``credential_whatsapp.svg`` co-located+in this folder.+"""++from __future__ import annotations++from services.plugin.credential import Credential+++class WhatsAppCredential(Credential):+ """Catalogue stub for the QR-paired WhatsApp Personal connection.++ Not an :class:`ApiKeyCredential` / :class:`OAuth2Credential` —+ WhatsApp's pairing is session-based and managed entirely by the+ :class:`~nodes.whatsapp._runtime.WhatsAppRuntime` supervisor ++ WebSocket handlers. The class is registered into+ ``CREDENTIAL_REGISTRY`` purely to give the catalogue icon endpoint+ (``GET /api/schemas/credentials/whatsapp/icon``) a class+ to call :meth:`get_icon_path` on. ``resolve()`` is never called+ because no node plugin declares this credential in its+ ``credentials`` tuple — the connection is implicit, mediated by+ ``services.whatsapp_service`` and the runtime supervisor.+ """++ id = "whatsapp"+ display_name = "WhatsApp Personal"+ auth = "custom"+ category = "Social"+ docs_url = "https://faq.whatsapp.com/general/about-linked-devices"diff --git a/server/credentials/icons/whatsapp_personal.svg b/server/nodes/whatsapp/whatsapp.svgsimilarity index 100%rename from server/credentials/icons/whatsapp_personal.svgrename to server/nodes/whatsapp/whatsapp.svgdiff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex f13de7c1..e94d2c85 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -367,13 +367,12 @@ async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSo# Declarative per-provider override for the "stored" check.# Lets Telegram (kind=oauth + status_hook but actual storage# is api_key for the bot token) signal that "stored" should- # be ``has_valid_key("telegram_bot_token")`` rather than the- # default ``get_oauth_tokens(status_hook)`` lookup. Other- # providers don't declare ``stored_check`` and keep the- # original kind/status_hook-based logic untouched -- so- # Google's saved client_secret (password field) does NOT- # flip the connected dot before the user actually completes- # the OAuth flow.+ # be ``has_valid_key("telegram")`` rather than the default+ # ``get_oauth_tokens(status_hook)`` lookup. Other providers+ # don't declare ``stored_check`` and keep the original+ # kind/status_hook-based logic untouched -- so Google's saved+ # client_secret (password field) does NOT flip the connected+ # dot before the user actually completes the OAuth flow.stored_check = provider.get("stored_check")if stored_check and stored_check.get("type") == "api_key":provider["stored"] = await auth_service.has_valid_key(stored_check.get("key", pid))diff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.pyindex e6beee88..73fb9c4e 100644--- a/server/services/plugin/credential.py+++ b/server/services/plugin/credential.py@@ -186,26 +186,27 @@ class Credential:# ---- F7: credential icon resolution -----------------------------## Mirrors :func:`nodes._visuals.get_plugin_icon_path` for credentials.- # The frontend credential modal currently reads ``cls.icon`` strings- # of the form ``"asset:<key>"`` and looks up bundled SVGs in- # ``client/src/assets/icons/``. F7 moves those icons backend-side:- # the endpoint ``GET /api/schemas/credentials/{provider}/icon``- # serves the SVG, and ``cls.icon`` can be updated to either an- # explicit URL or left empty (the metadata projection layer fills in- # the URL automatically when an icon file exists).+ # The frontend credential modal reads ``cls.icon`` strings of the+ # form ``"asset:<key>"`` / ``"lobehub:<brand>"`` / emoji, OR fetches+ # the SVG from the backend via ``GET /api/schemas/credentials/{provider}/icon``.+ #+ # Plugin-folder canonical convention (brand-name files):+ # ``server/nodes/<plugin>/<cls.id>.svg``+ #+ # The credential icon lives directly inside its owner plugin's+ # folder, named after the credential's brand (e.g.+ # ``server/nodes/telegram/telegram.svg``). Distinguished from node+ # icons by the absence of the ``icon`` / ``icon_<type>`` prefix —+ # node icons follow that convention (see+ # ``nodes/_visuals.py::get_plugin_icon_path``), credential icons+ # don't. No ambiguity.## Resolution order:- # 1. ``server/credentials/icons/<id>.svg`` — central catalogue- # (preferred — provider icons are scope-agnostic; one shared- # location avoids duplicating brand SVGs across plugin folders- # when a provider's credential serves multiple plugins, e.g.- # Google Workspace's 6 nodes share one ``google`` credential).- # 2. ``<credential_class_folder>/credential_<id>.svg`` — co-located- # fallback for plugin-scoped credentials (rare; useful when the- # icon is tightly coupled to a specific plugin folder).- # 3. ``None`` — no backend icon; frontend falls back to whatever- # ``cls.icon`` declares (``asset:<key>`` / ``lobehub:<brand>`` /- # ``data:`` / emoji).+ # 1. ``<plugin_folder>/<cls.id>.svg`` — co-located brand-name file.+ # 2. ``server/credentials/icons/<cls.id>.svg`` — legacy central+ # catalogue (pre-Wave 11.K; new credentials should ship the icon+ # inside their plugin folder).+ # 3. ``None`` — no backend icon; frontend falls back to ``cls.icon``.@classmethoddef get_icon_path(cls) -> Optional["Path"]:@@ -220,23 +221,23 @@ class Credential:if not cls.id:return None- # 1. Central catalogue- # ``server/`` resolves from this file's path: services/plugin/credential.py- # -> services/plugin/.. -> services/.. -> server/.+ # 1. Co-located in the plugin folder, brand-name basename.+ try:+ cred_file = _Path(inspect.getfile(cls)).resolve()+ except (TypeError, OSError):+ cred_file = None+ if cred_file is not None:+ co_located = cred_file.parent / f"{cls.id}.svg"+ if co_located.exists():+ return co_located++ # 2. Legacy central catalogue. ``server/`` resolves from this+ # file: services/plugin/credential.py -> services/.. -> server/.server_root = _Path(__file__).resolve().parent.parent.parentcentral = server_root / "credentials" / "icons" / f"{cls.id}.svg"if central.exists():return central- # 2. Co-located fallback- try:- cred_file = _Path(inspect.getfile(cls)).resolve()- except (TypeError, OSError):- return None- co_located = cred_file.parent / f"credential_{cls.id}.svg"- if co_located.exists():- return co_located-return None@classmethoddiff --git a/server/tests/credentials/test_auth_service.py b/server/tests/credentials/test_auth_service.pyindex 57a29a67..4b21612e 100644--- a/server/tests/credentials/test_auth_service.py+++ b/server/tests/credentials/test_auth_service.py@@ -27,13 +27,13 @@ class TestApiKeyOps:assert await auth_service.get_stored_models("openai") == ["gpt-4", "gpt-3.5"]async def test_store_with_empty_models_for_non_llm_keys(self, auth_service):- # Pattern C: save-only API keys (telegram_bot_token, android_remote, etc.)+ # Pattern C: save-only API keys (telegram, android_remote, etc.)ok = await auth_service.store_api_key(- "telegram_bot_token", "123:abc", models=[]+ "telegram", "123:abc", models=[])assert ok is True- assert await auth_service.get_api_key("telegram_bot_token") == "123:abc"- assert await auth_service.get_stored_models("telegram_bot_token") == []+ assert await auth_service.get_api_key("telegram") == "123:abc"+ assert await auth_service.get_stored_models("telegram") == []async def test_store_requires_models_keyword(self, auth_service):# Invariant 7: store_api_key takes `models` as required argument.diff --git a/server/tests/credentials/test_credential_broadcasts.py b/server/tests/credentials/test_credential_broadcasts.pyindex e79e09f6..6197c2a5 100644--- a/server/tests/credentials/test_credential_broadcasts.py+++ b/server/tests/credentials/test_credential_broadcasts.py@@ -293,11 +293,11 @@ class TestCredentialRuntimeFailureBroadcast:asyncio.get_event_loop().run_until_complete(broadcaster.broadcast_credential_event(event_type="credential.api_key.runtime_failed",- provider="telegram_bot_token",+ provider="telegram",workflow_id="wf-test",reason="missing",node_id="telegramSend-1",- error="No API key for 'telegram_bot_token'.",+ error="No API key for 'telegram'.",))@@ -307,10 +307,10 @@ class TestCredentialRuntimeFailureBroadcast:envelope = payload["data"]assert envelope["specversion"] == "1.0"assert envelope["type"] == "credential.api_key.runtime_failed"- assert envelope["subject"] == "telegram_bot_token"+ assert envelope["subject"] == "telegram"assert envelope["workflow_id"] == "wf-test"data = envelope["data"]- assert data["provider"] == "telegram_bot_token"+ assert data["provider"] == "telegram"assert data["reason"] == "missing"assert data["node_id"] == "telegramSend-1"assert "error" in datadiff --git a/server/tests/credentials/test_websocket_handlers.py b/server/tests/credentials/test_websocket_handlers.pyindex a863efd9..bd3e7a3d 100644--- a/server/tests/credentials/test_websocket_handlers.py+++ b/server/tests/credentials/test_websocket_handlers.py@@ -178,7 +178,7 @@ class TestSaveApiKey:result = await _call(ws_module.handle_save_api_key,{- "provider": "telegram_bot_token",+ "provider": "telegram","api_key": "123:abc","models": [],},@@ -189,7 +189,7 @@ class TestSaveApiKey:# No model fetch (Pattern C)patched_container.ai.fetch_models.assert_not_called()- stored = await patched_container.auth.get_api_key("telegram_bot_token")+ stored = await patched_container.auth.get_api_key("telegram")assert stored == "123:abc"async def test_save_strips_whitespace_and_lowercases_provider(diff --git a/server/tests/test_credential_icon.py b/server/tests/test_credential_icon.pyindex 5d18e097..166fe808 100644--- a/server/tests/test_credential_icon.py+++ b/server/tests/test_credential_icon.py@@ -106,11 +106,11 @@ class TestEndpointResolution:def test_well_known_providers_registered(self):"""Sanity check that the registry includes the providers the- endpoint will eventually serve icons for. Uses actual credential- ids (telegram registers as ``telegram_bot_token``, not- ``telegram`` — the id matches the secret-store key, not the- brand)."""- well_known = {"apify", "stripe", "telegram_bot_token", "twitter", "google"}+ endpoint will eventually serve icons for. Credential ids match+ the catalogue keys (and brand names): ``telegram`` (bot token),+ ``google`` (Google Workspace), ``whatsapp`` (QR-paired session),+ etc."""+ well_known = {"apify", "stripe", "telegram", "twitter", "google", "whatsapp"}registered = set(CREDENTIAL_REGISTRY.keys())missing = well_known - registeredassert not missing, f"Expected credentials not registered: {missing}"