Skip to content

Self-improving AI Employees for everyone

fix(skills): resolve brand icons in master skill display + typed CloudEvents

trohitg08f1c9ec79b7
diff --git a/CLAUDE.md b/CLAUDE.md
index ea27bba3..3193d342 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -846,7 +846,7 @@ The Master Skill node uses a custom split-panel editor (`MasterSkillEditor.tsx`)
- Default folder: `assistant`
**Icon Resolution Priority:**
-Skill icons resolve via the central `visuals.json` registry — see "Icon + color — central `visuals.json` registry" below. The pre-Wave-10 `skillNodes.ts` + `getNodeDefaults()` helper that did per-skill icon overrides on the frontend was retired; icons + colours now live exclusively in [`server/nodes/visuals.json`](./server/nodes/visuals.json) and SKILL.md frontmatter for orphan skills (no node target).
+Skill icons resolve through the same chain as the teaching node (mirrors `BaseNode._metadata_dict`): per-plugin `<plugin>/icon.svg` (or `<plugin>/icon_<type>.svg`) served as `/api/schemas/nodes/<type>/icon` → [`server/nodes/visuals.json`](./server/nodes/visuals.json) entry (emoji or `lobehub:<brand>`). Color falls through per-plugin `<plugin>/meta.json` then `visuals.json`. Resolution lives in [`server/services/skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py) which calls `nodes._visuals.get_plugin_icon_path` / `get_plugin_meta` / `get_icon` / `get_color`. The pre-Wave-10 `skillNodes.ts` + `getNodeDefaults()` helper that did per-skill icon overrides on the frontend was retired; icons + colours now live exclusively on disk (per-plugin folder) with `visuals.json` as the fallback registry, and SKILL.md frontmatter is read only for orphan skills (no node target).
**Keyboard Handling:**
The editor uses a native DOM `addEventListener('keydown')` on a wrapper div (via `useRef`) to `stopPropagation()` for Ctrl/Meta key events. This prevents React Flow's document-level `useKeyPress` hook from intercepting Ctrl+A (select all) and other Ctrl shortcuts inside the textarea. React synthetic `stopPropagation()` is insufficient because React Flow uses native `document.addEventListener`.
@@ -5200,7 +5200,7 @@ This function:
- Source: https://github.com/trohitg/whatsapp-rpc
- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.
- **Workflow Export/Import with Parameters**: Exported workflow JSON includes a `nodeParameters` field containing all node configuration (provider, model, prompt, skillsConfig, etc.) fetched from the database at export time. On import, embedded `nodeParameters` are saved back to the database. `sanitizeNodes()` in `workflowExport.ts` still strips `node.data` to UI-only fields (`label`, `disabled`, `condition`). A `parameterSanitizer.ts` utility exists for credential stripping but is currently disabled (pass-through). Old exports without `nodeParameters` import cleanly (backward compatible). Key files: `client/src/utils/workflowExport.ts`, `client/src/utils/parameterSanitizer.ts`, `client/src/Dashboard.tsx` (export/import handlers), `server/services/example_loader.py`.
-- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution: node definition (SVG) > SKILL.md metadata (emoji) > fallback. Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor.
+- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
- **Example Workflows**: Auto-load example workflows from `workflows/` folder on first use. Uses `UserSettings.examples_loaded` flag to track import status. Supports anonymous users (`user_id="default"`). Reuses existing `database.save_workflow()` for import. Embedded `nodeParameters` in example JSON files are saved to the database on import. See "Example Workflows" section for details.
- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using Ant Design Steps/Card/Button/Typography. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 3020 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. Handlers in `server/services/handlers/code.py` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).
@@ -5228,6 +5228,7 @@ This function:
- **Typed openai exception → NodeUserError**: `execute_chat` / `execute_agent` / `execute_chat_agent` in `services/ai.py` each have **one** `except openai.OpenAIError as e` block that re-raises `NodeUserError(str(e)) from e`. The openai SDK's typed exception hierarchy — `BadRequestError` (400, e.g. `n_keep > n_ctx` overflow), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RateLimitError` (429), `APIConnectionError` (server unreachable), `APITimeoutError` — IS the user-correctable contract. `BaseNode.execute()` catches `NodeUserError` and logs at WARN with one line, no stacktrace. The plain `except Exception` block keeps the full-traceback path for real bugs. Zero string matching, zero flag plumbing, zero classification helpers. The `frontend toast` reads `response.message ?? response.error` so both clean envelopes (validator-style) and uncaught-error envelopes (handler-wrapper-style) surface a useful message.
- **Plugin extraction (Wave 11.I)**: every plugin's WS handlers, OAuth client, FastAPI router, and lifecycle service live entirely under `nodes/<plugin>/`. Eight plugin domains migrated this round (whatsapp / twitter / google-workspace / android / browser / email / code / credential-validation-scaffold for maps+apify+ollama+lmstudio) follow the telegram pattern. `routers/websocket.py` shrunk from ~3,785 to ~2,977 LOC (-808). Three plugin routers (`routers/twitter.py`, `routers/google.py`, `routers/android.py`) moved into `nodes/<plugin>/_router.py` and mount via the plugin-router loop in `main.py`; the explicit `app.include_router(<plugin>.router)` calls and `from routers import <plugin>` imports in `main.py` are gone. **`register_router(router, name=...)` is the new sibling helper to `register_ws_handlers` (same file: `services/ws_handler_registry.py`)** — six generic registries total now (ws_handlers, router, filter_builder, trigger_precheck, service_refresh, output_schema). **`Credential.validate(data) -> dict` + `Credential._probe(api_key) -> ProbeResult` is the new shared validator scaffold** in `services/plugin/credential.py` — replaces the per-router `_SPECIAL_PROVIDER_VALIDATORS` dict; one `_LLMApiKey._probe` method serves all 9 cloud LLM providers, dedicated `_probe` overrides handle Maps + Apify, `_LocalLLM.validate` overrides for Ollama / LM Studio's 2-storage edge case. **`tests/test_plugin_self_containment.py` locks the contract** with 7 invariant classes (forbidden-imports / no-router-outside-nodes / per-plugin self-registration / registry-API sanity / stale-paths-absent / main.py-does-not-mount / WS_HANDLERS-non-empty); same `inspect.getsource` introspection style as `test_credential_broadcasts.py`. Wire format unchanged — frontend WS message-type strings (`whatsapp_status`, `twitter_oauth_login`, `google_oauth_status`, `android_relay_connect`, etc.) and HTTP route paths (`/api/twitter/callback`, `/api/google/callback`, `/api/android/*`) are byte-identical post-migration.
- **Typed CloudEvents factory pattern for new broadcasts** (b6aecd3): every new server→FE broadcast follows the recipe locked by `broadcast_credential_event` and `broadcast_agent_progress`. (1) Add a typed classmethod on `WorkflowEvent` (`services/events/envelope.py`) — convention: `source = "machinaos://services/<area>"`, `type = "<area>.<event>"`, `subject = <primary entity id>`, `workflow_id` extension if scoped. (2) Add a `broadcaster.broadcast_<area>_<event>(...)` method on `StatusBroadcaster` that builds the envelope and emits via `broadcast({type: "<wire_key>", data: event.model_dump(mode="json")})`. Wire key is typically the event topic with dots → underscores (`agent.progress` → `agent_progress`). (3) FE handler in `WebSocketContext.tsx` switch routes the wire key, parses `data` as `WorkflowEvent<TInner>`, writes the inner payload to whichever store consumes it (`nodeStatusStore` for per-node state, etc.). (4) Add a parity test in `tests/test_status_broadcasts.py` via `inspect.getsource` introspection. **Forbidden**: emitting raw-dict payloads through `update_node_status` for any new event type — that channel is allowlisted via `_LEGACY_RAW_DICT_CALLSITES` and the allowlist is closed.
+- **Plugin-folder location for plugin-specific CloudEvents factories** (RFC §6.4): when a typed event is owned by one plugin (telegram, whatsapp, android, email, google, master_skill, agent_builder, webhook_trigger, chat_trigger, agent), the factory + `broadcast_<event>` wrapper live in [`server/nodes/<plugin>/_events.py`](./server/nodes), NOT on `WorkflowEvent` / `StatusBroadcaster` directly. Telegram's [`_events.py`](./server/nodes/telegram/_events.py) is the canonical template — `broadcast_telegram_status` constructs the envelope via a plain factory function and calls `get_status_broadcaster().broadcast(...)` itself. Latest example: [`server/nodes/skill/master_skill/_events.py`](./server/nodes/skill/master_skill/_events.py) (`broadcast_skill_lifecycle("created" \| "updated" \| "deleted" \| "content_saved", name=..., **data_extra)`) — replaces four raw-dict broadcasts in `handle_create_user_skill` / `handle_update_user_skill` / `handle_delete_user_skill` / `handle_save_skill_content` (the last one was previously silent). FE routes wire key `skill_lifecycle` to invalidate `userSkills` + `folderSkills` queries and drop the `skillContent` cache on delete + content_saved so the Master Skill panel refreshes live across every connected client. Cross-cutting events (credential, workflow_lifecycle, agent_progress, node_parameters_updated) keep their `WorkflowEvent` classmethods + `StatusBroadcaster` wrappers — only plugin-scoped events move to the plugin folder.
- **Operator-metadata fields in credential panels** (f746ddf): when a credential panel needs a non-credential follow-up field (e.g. Telegram bot token + owner chat id), declare it as a second entry in the provider's `fields` array in `server/config/credential_providers.json`. The first field stays the validate/connect target; subsequent fields render below as plain text inputs via `SecondaryFieldRow` in `ApiKeyPanel.tsx` (shadcn `Input` + `Label` + `<ActionButton intent="save">`). Each field carries an optional `help` slot (`FieldDef.help` / `ServerFieldDef.help`) for always-visible explanatory text under the input. Save writes via `panel.actions.save(field.key, value)` → `auth_service.store_api_key` (which is permissive about provider string). The credential class must declare the new key in `extra_fields` (`Credential` subclass attribute) so the storage layer accepts it. Reference: `telegram_owner_chat_id` field.
- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.
- **Supervisor Job Object loud-failure (machina/tree.py + supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in `machina/pyproject.toml` carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / pnpm / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index b2f941a3..0a908f88 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -729,6 +729,29 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
break;
}
+ case 'skill_lifecycle': {
+ // CloudEvents-typed skill registry lifecycle from
+ // server/nodes/skill/master_skill/_events.py. Stages
+ // `skill.created` / `.updated` / `.deleted` invalidate the
+ // user-skills + folder-skills caches so the Master Skill
+ // panel and any agent's Connected Skills view refresh
+ // across every connected client. `skill.content_saved`
+ // and `.deleted` also drop the per-skill content cache so
+ // the next read re-fetches fresh instructions.
+ const event = data as WorkflowEvent<{
+ name?: string;
+ is_builtin?: boolean;
+ skill?: unknown;
+ }>;
+ const name = event?.data?.name || event?.subject;
+ void queryClient.invalidateQueries({ queryKey: ['userSkills'] });
+ void queryClient.invalidateQueries({ queryKey: ['folderSkills'] });
+ if (name && (event?.type?.endsWith('.content_saved') || event?.type?.endsWith('.deleted'))) {
+ queryClient.removeQueries({ queryKey: ['skillContent', name] });
+ }
+ break;
+ }
+
case 'android_status':
setAndroidStatus(data || defaultAndroidStatus);
break;
diff --git a/server/nodes/skill/master_skill/_events.py b/server/nodes/skill/master_skill/_events.py
new file mode 100644
index 00000000..47390586
--- /dev/null
+++ b/server/nodes/skill/master_skill/_events.py
@@ -0,0 +1,82 @@
+"""CloudEvents factories + broadcaster wrappers for skill lifecycle.
+
+Per RFC plugin_authoring_rfc.md §6.4: plugin-specific factories live in
+the plugin folder. This file owns every skill-mutation wire frame so
+``routers/websocket.py`` (and any future caller) doesn't hand-build
+envelopes with drifting shapes.
+
+Wire-format key: ``skill_lifecycle`` — the frontend's
+``WebSocketContext`` routes on this key and invalidates the
+``userSkills`` / ``folderSkills`` / ``skillContent`` TanStack queries
+so the Master Skill panel and any agent's Connected Skills view pick
+up changes live across every connected client.
+
+Replaces four legacy raw-dict broadcasts:
+ - ``{type: "user_skill_created", skill: ..., timestamp: ...}``
+ - ``{type: "user_skill_updated", skill: ..., timestamp: ...}``
+ - ``{type: "user_skill_deleted", name: ..., timestamp: ...}``
+ - (silent — ``save_skill_content`` previously emitted nothing)
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Mapping, Optional
+
+from services.events.envelope import WorkflowEvent
+
+
+_WIRE_KEY = "skill_lifecycle"
+
+SkillStage = Literal["created", "updated", "deleted", "content_saved"]
+
+
+def skill_lifecycle_event(
+ stage: SkillStage,
+ *,
+ name: str,
+ data: Optional[Mapping[str, Any]] = None,
+) -> WorkflowEvent:
+ """Build the CloudEvents v1.0 envelope for a skill-registry change.
+
+ ``subject`` carries the skill name (the canonical identifier
+ consumers key on); ``data`` carries the full skill record for
+ ``created`` / ``updated`` and the minimal ``{name}`` for ``deleted``
+ and ``content_saved``. ``content_saved`` additionally carries
+ ``is_builtin`` so the FE can distinguish SKILL.md vs database
+ writes without re-querying.
+ """
+ return WorkflowEvent(
+ source="machinaos://nodes/master_skill",
+ type=f"com.machinaos.skill.{stage}",
+ subject=name,
+ data=dict(data) if data else {"name": name},
+ )
+
+
+async def broadcast_skill_lifecycle(
+ stage: SkillStage,
+ *,
+ name: str,
+ **data_extra: Any,
+) -> None:
+ """Emit a CloudEvents-typed ``skill.<stage>`` envelope.
+
+ Single source of truth for every skill-mutation wire frame —
+ callers pass the stage + name + any extra fields and this wrapper
+ handles envelope construction and broadcast.
+ """
+ from services.status_broadcaster import get_status_broadcaster
+
+ broadcaster = get_status_broadcaster()
+ event = skill_lifecycle_event(stage, name=name, data=data_extra or None)
+ await broadcaster.broadcast({
+ "type": _WIRE_KEY,
+ "data": event.model_dump(mode="json"),
+ })
+
+
+__all__ = [
+ "SkillStage",
+ "broadcast_skill_lifecycle",
+ "skill_lifecycle_event",
+]
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index d87b3071..dd80d7e8 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1458,27 +1458,9 @@ async def handle_delete_api_key(data: Dict[str, Any], websocket: WebSocket) -> D
return await store.run(data.get("request_id"), _do_delete)
-# ============================================================================
-# Claude OAuth Handlers
-# ============================================================================
-
-@ws_handler()
-async def handle_claude_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Initiate Claude OAuth in isolated session."""
- from services.claude_oauth import initiate_claude_oauth
- return await initiate_claude_oauth()
-
-
-@ws_handler()
-async def handle_claude_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Check Claude OAuth credentials status via ``claude auth status``."""
- from services.claude_oauth import claude_auth_status
- has_token = await claude_auth_status()
- return {"success": True, "has_token": has_token}
-
-
-# NOTE: `cli_login` / `cli_auth_status` handlers are owned by
-# `services/cli_agent/_handlers.py` and self-registered into
+# NOTE: claude / codex auth WS handlers (`claude_code_login`,
+# `claude_code_logout`, `claude_code_auth_status`, `codex_cli_*`) are
+# owned by `services/cli_agent/_handlers.py` and self-registered into
# `services.ws_handler_registry` on package import — no entries needed
# here. See `services/cli_agent/__init__.py`.
@@ -1932,6 +1914,10 @@ async def handle_save_skill_content(data: Dict[str, Any], websocket: WebSocket)
# Clear cache so next load gets fresh content
skill_loader.clear_cache()
+ from nodes.skill.master_skill._events import broadcast_skill_lifecycle
+ await broadcast_skill_lifecycle(
+ "content_saved", name=skill_name, is_builtin=True,
+ )
logger.info(f"[Skills] Updated built-in skill: {skill_name}")
return {
"success": True,
@@ -1950,6 +1936,10 @@ async def handle_save_skill_content(data: Dict[str, Any], websocket: WebSocket)
instructions=new_instructions
)
if updated:
+ from nodes.skill.master_skill._events import broadcast_skill_lifecycle
+ await broadcast_skill_lifecycle(
+ "content_saved", name=skill_name, is_builtin=False,
+ )
logger.info(f"[Skills] Updated user skill: {skill_name}")
return {
"success": True,
@@ -2107,8 +2097,9 @@ async def handle_get_user_skill(data: Dict[str, Any], websocket: WebSocket) -> D
@ws_handler("name", "display_name", "instructions")
async def handle_create_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Create a new user skill."""
+ from nodes.skill.master_skill._events import broadcast_skill_lifecycle
+
database = container.database()
- broadcaster = get_status_broadcaster()
skill = await database.create_user_skill(
name=data["name"],
@@ -2124,12 +2115,7 @@ async def handle_create_user_skill(data: Dict[str, Any], websocket: WebSocket) -
)
if skill:
- # Broadcast skill created to all clients
- await broadcaster.broadcast({
- "type": "user_skill_created",
- "skill": skill,
- "timestamp": time.time()
- })
+ await broadcast_skill_lifecycle("created", name=data["name"], skill=skill)
return {"skill": skill, "timestamp": time.time()}
return {"success": False, "error": f"Failed to create skill. Name '{data['name']}' may already exist."}
@@ -2137,8 +2123,9 @@ async def handle_create_user_skill(data: Dict[str, Any], websocket: WebSocket) -
@ws_handler("name")
async def handle_update_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Update an existing user skill."""
+ from nodes.skill.master_skill._events import broadcast_skill_lifecycle
+
database = container.database()
- broadcaster = get_status_broadcaster()
skill = await database.update_user_skill(
name=data["name"],
@@ -2154,12 +2141,7 @@ async def handle_update_user_skill(data: Dict[str, Any], websocket: WebSocket) -
)
if skill:
- # Broadcast skill updated to all clients
- await broadcaster.broadcast({
- "type": "user_skill_updated",
- "skill": skill,
- "timestamp": time.time()
- })
+ await broadcast_skill_lifecycle("updated", name=data["name"], skill=skill)
return {"skill": skill, "timestamp": time.time()}
return {"success": False, "error": f"Skill '{data['name']}' not found"}
@@ -2167,18 +2149,14 @@ async def handle_update_user_skill(data: Dict[str, Any], websocket: WebSocket) -
@ws_handler("name")
async def handle_delete_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Delete a user skill."""
+ from nodes.skill.master_skill._events import broadcast_skill_lifecycle
+
database = container.database()
- broadcaster = get_status_broadcaster()
deleted = await database.delete_user_skill(data["name"])
if deleted:
- # Broadcast skill deleted to all clients
- await broadcaster.broadcast({
- "type": "user_skill_deleted",
- "name": data["name"],
- "timestamp": time.time()
- })
+ await broadcast_skill_lifecycle("deleted", name=data["name"])
logger.info(f"[Skills] Deleted user skill: {data['name']}")
return {"success": True, "deleted": True, "name": data["name"], "timestamp": time.time()}
return {"success": False, "error": f"Skill '{data['name']}' not found"}
diff --git a/server/services/skill_loader.py b/server/services/skill_loader.py
index 2ef25ef2..d22fd2ff 100644
--- a/server/services/skill_loader.py
+++ b/server/services/skill_loader.py
@@ -165,17 +165,29 @@ class SkillLoader:
if 'allowed-tools' in frontmatter:
allowed_tools = frontmatter['allowed-tools'].split()
- # Resolve icon + color from the target node via central handler.
- # `allowed-tools` uses snake_case; node `type` is camelCase.
- from nodes._visuals import get_icon, get_color
+ # Resolve icon + color from the target node, mirroring
+ # ``BaseNode._metadata_dict``'s chain so skills inherit whichever
+ # icon source the teaching node uses:
+ # 1. ``<plugin>/icon.svg`` or ``<plugin>/icon_<type>.svg`` →
+ # ``/api/schemas/nodes/<type>/icon`` URL (wire format
+ # consumed by frontend ``resolveIcon``)
+ # 2. ``visuals.json`` entry (emoji or ``lobehub:<brand>``)
+ # Color: ``<plugin>/meta.json`` first, then ``visuals.json``.
+ # ``allowed-tools`` uses snake_case; node ``type`` is camelCase.
+ from nodes._visuals import (
+ get_color, get_icon, get_plugin_icon_path, get_plugin_meta,
+ )
meta_in = dict(frontmatter.get('metadata') or {})
for tok in allowed_tools:
cam = tok if "_" not in tok else (
tok.split("_")[0] + "".join(p.title() for p in tok.split("_")[1:])
)
for candidate in (cam, tok):
- icon = get_icon(candidate)
- color = get_color(candidate)
+ if get_plugin_icon_path(candidate) is not None:
+ icon = f"/api/schemas/nodes/{candidate}/icon"
+ else:
+ icon = get_icon(candidate)
+ color = get_plugin_meta(candidate, "color") or get_color(candidate)
if icon or color:
if icon:
meta_in['icon'] = icon