Skip to content

Self-improving AI Employees for everyone

docs: reflect frontend tech-debt cleanup

trohitg53a19364c2ce
diff --git a/CLAUDE.md b/CLAUDE.md
index c19716cd..60f8c4ca 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -561,10 +561,19 @@ The frontend uses a layered cache + slice-subscription model so cold refreshes a
- Per-workflow node statuses live in a Zustand store (built on `useSyncExternalStore`). `useNodeStatus(id)` is a slice selector -- only the affected node's consumers re-render on a status tick.
- Mirror this pattern when adding any new high-frequency push state. Do **not** put it on `WebSocketContext.value` -- that's a context fan-out trap.
+### `useAppStore` reads must be slice selectors, never whole-store destructure
+- Always `const x = useAppStore((s) => s.x)`, never `const { x } = useAppStore()`. The whole-store form re-renders the consumer on ANY mutation (sidebar toggle, unrelated workflow rename, parameter save on another node), which defeats `React.memo` + `nodePropsEqual` on the canvas. Setters are stable refs from Zustand — single-field selectors are the cheapest read.
+- Audited and converted across the canvas + parameter-panel hot paths: every node component, `Dashboard.tsx`, `useDragVariable`, `useParameterPanel`, `useReactFlowNodes`, `useWorkflowManagement`, `InputSection`, `MiddleSection`, `OutputPanel`, `ParameterRenderer`, `ToolSchemaEditor`, `ParameterPanel`, `InputNodesPanel`. New code should follow.
+
### `isOpen` vs `isReady` -- gate every catalogue/spec query on `isReady` ([WebSocketContext.tsx](./client/src/contexts/WebSocketContext.tsx))
-- `isOpen` flips when the socket opens. `isReady` flips only after the 8-step init burst (api-key probes, terminal/chat/console history) settles.
-- Queries that depend on backend-served catalogue data (`useCatalogueQuery`, `useNodeParamsQuery`, `useUserSettingsQuery`, `useNodeGroups`, `useNodeSpec` lazy fetch, prefetch effect) gate on `isReady` so they fire once, post-burst, instead of racing the serial init awaits.
-- `WebSocketContext.value` is `useMemo`'d -- consumers only re-render when an actual field they read changes. Pending requests are rejected on `ws.onclose` so retries fire immediately on the new socket instead of waiting the 30s `REQUEST_TIMEOUT`.
+- `isOpen` flips when the socket opens. `isReady` flips only after the init burst (api-key probes, terminal / chat / console history) settles.
+- The init burst runs **in parallel** via `Promise.allSettled`: 5 `probeApiKey(provider)` calls + `loadTerminalLogs()` + `loadChatHistory()` + `loadConsoleLogs()`, each owning its own request id, message handler, 5 s timeout, and state write via a small `sendBurstRequest` factory. Time-to-`isReady` is one wide round-trip, not 8 sequential ones. `drainPendingSends(ws)` still runs synchronously after the await and before `setIsReady(true)` so the queue replay ordering is preserved.
+- Queries that depend on backend-served catalogue data (`useCatalogueQuery`, `useNodeParamsQuery`, `useUserSettingsQuery`, `useNodeGroups`, `useNodeSpec` lazy fetch, prefetch effect) gate on `isReady` so they fire once, post-burst, instead of racing the parallel init helpers.
+- `WebSocketContext.value` is `useMemo`'d -- consumers only re-render when an actual field they read changes. Pending requests are rejected on `ws.onclose` so retries fire immediately on the new socket instead of waiting the 30 s `REQUEST_TIMEOUT`.
+
+### Catalogue invalidation is debounced
+- `invalidateCatalogue(queryClient)` in [`hooks/useCatalogueQuery.ts`](./client/src/hooks/useCatalogueQuery.ts) wraps `queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY })` with a 300 ms trailing-edge debounce via a single shared module-scope timer. **Always go through it** from broadcast handlers — direct `invalidateQueries` calls were the old pattern.
+- All 8 broadcast handlers in `WebSocketContext.tsx` (`api_key_status`, `whatsapp_status`, `twitter_oauth_complete`, `google_oauth_complete`, `google_status`, `telegram_status`, `credential_catalogue_updated`, `initial_status`) now route through it. An OAuth burst or multi-service reconnect collapses to one refetch instead of N back-to-back round-trips.
### React.memo every canvas node component ([client/src/components/nodeMemoEquality.ts](./client/src/components/nodeMemoEquality.ts))
- React Flow's documented requirement. Use the shared `nodePropsEqual` comparator -- it skips drag-state props (`xPos` / `yPos` / `dragging`) so the memo isn't defeated during drag.
@@ -604,11 +613,10 @@ authoring model.
- `src/assets/icons/google/` - Official Google service SVG icons (Gmail, Calendar, Drive, Sheets, Tasks, Contacts) using n8n pattern with data URI exports
### UI Components
-- `src/components/ParameterRenderer.tsx` - Universal parameter renderer (dual interface support)
+- `src/components/ParameterRenderer.tsx` - Universal parameter renderer (also handles AI-specific control rendering; the former `AIParameterRenderer.tsx` was absorbed here)
- `src/components/parameterPanel/MiddleSection.tsx` - Parameter panel middle section with conditional display logic
- `src/components/OutputPanel.tsx` - Connected node output display with drag mapping
- `src/components/LocationParameterPanel.tsx` - Location-specific parameter handling
-- `src/components/AIParameterRenderer.tsx` - AI component configuration
- `src/components/AIAgentNode.tsx` - Config-driven AI agent component supporting both aiAgent and chatAgent via AGENT_CONFIGS
- `src/ParameterPanel.tsx` - Main parameter configuration modal
@@ -645,16 +653,16 @@ Single source of truth: [client/src/index.css](./client/src/index.css). All toke
- `bg-node-X-soft` — tinted surface (cards, tinted backgrounds)
- `border-node-X-border` — tinted outline
Themes redefine these in their own scope without touching call sites. **Never use opacity arithmetic at the call site** (`bg-node-agent/10`); add a new `-soft` / `-border` variant if you need a different opacity.
-3. **Action role tokens** — `--action-run`, `--action-stop`, `--action-save`, `--action-config`, `--action-secret`, `--action-tools`. Same `base / -soft / -border` triplet as `--node-X` (e.g. `bg-action-run-soft text-action-run border-action-run-border`). Used for toolbar icon buttons, File menu items, and as the underlying tokens behind `<ActionButton>`'s `intent` variants. Themes redefine these without touching call sites.
+3. **Action role tokens** — `--action-run`, `--action-stop`, `--action-save`, `--action-config`, `--action-secret`, `--action-tools`. Same `base / -soft / -hover / -border` quartet as `--node-X` (e.g. `bg-action-run-soft text-action-run border-action-run-border`, plus `hover:bg-action-run-hover` for the hover state). Used for toolbar icon buttons, File menu items, and as the underlying tokens behind `<ActionButton>`'s `intent` variants. Themes redefine these without touching call sites. The `-hover` triplet means ActionButton no longer composes hover via opacity arithmetic.
4. **Dracula raw accents** — `--dracula-green/purple/pink/cyan/red/orange/yellow`. Same value across light + dark themes. Used as the underlying palette that `--action-X` and `--node-X` reference; do not consume directly in components — go through the semantic role token instead.
-**Action buttons** — use [ActionButton](./client/src/components/ui/action-button.tsx) (CVA primitive with semantic `intent` variants: `run | stop | save | config | secret | tools`). Each intent reads the matching `--action-X` triplet. Replaces the old `actionButtonStyle()` helper.
+**Action buttons** — use [ActionButton](./client/src/components/ui/action-button.tsx) (CVA primitive with semantic `intent` variants: `run | stop | save | config | secret | tools`). Each intent reads the matching `--action-X` quartet (`-soft` for resting bg, `-hover` for hover bg, `-border` for outline, base for text). Disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class (one rule, all intents) — never per-token opacity arithmetic. Replaces the old `actionButtonStyle()` helper. Credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`, `ActionBar`) consume `<ActionButton>` directly; their `ActionDef` carries an `intent` key, not a free-form colour.
-**Canvas-wide animations** — [client/src/styles/canvasAnimations.ts](./client/src/styles/canvasAnimations.ts) owns the `@keyframes` + `.react-flow__edge.{status}` + `.react-flow__node.{status}` rules injected once into Dashboard's `<style>` tag. Three named groups (`KEYFRAMES`, `edgeStatusStyles`, `nodeStatusStyles`) -- adding a new keyframe or status visual is a single-file change. Per-node inline animations (border pulse on `isExecuting`, etc.) live in their components and read theme tokens directly.
+**Canvas-wide animations** — [client/src/styles/canvasAnimations.ts](./client/src/styles/canvasAnimations.ts) owns the `@keyframes` + `.react-flow__edge.{status}` + `.react-flow__node.{status}` rules injected once into Dashboard's `<style>` tag. Three named groups (`KEYFRAMES`, `edgeStatusStyles`, `nodeStatusStyles`) -- adding a new keyframe or status visual is a single-file change. Per-node inline animations (border pulse on `isExecuting`, etc.) live in their components and read theme tokens directly. Light/dark distinction lives entirely in `theme.ts` — `buildCanvasStyles(colors)` is single-arg and the file ships zero hardcoded hex colours; `CanvasStatusColors` carries `edgeDefault | edgeSelected | edgeExecuting | edgeCompleted | edgeError | edgePending | edgeMemoryActive | edgeToolActive`. The `nodeGlow` keyframe consumes scoped `--node-glow` / `--node-glow-soft` vars so one keyframe serves both themes.
**shadcn primitives** — full set under `client/src/components/ui/` (Button, Badge, Alert, Dialog, DropdownMenu, Select, Popover, Tooltip, Tabs, Card, Input, Textarea, Switch, Checkbox, Slider, Label, Form, Sonner, Skeleton, Collapsible, Accordion, AlertDialog). New code composes these with Tailwind classes.
-**`useAppTheme()`** ([src/styles/theme.ts](./client/src/styles/theme.ts), [src/hooks/useAppTheme.ts](./client/src/hooks/useAppTheme.ts)) is grandfathered for the canvas node components (`AIAgentNode`, `SquareNode`, `TriggerNode`, `StartNode`, `ToolkitNode`, `TeamMonitorNode`, `BaseChatModelNode`, `ModelNode`, `GenericNode`) and `EdgeConditionEditor` — they interpolate per-definition `nodeColor` into gradients, borders, and React Flow `<Handle>` styles. Every other surface uses Tailwind + the tokens above.
+**`useAppTheme()`** ([src/styles/theme.ts](./client/src/styles/theme.ts), [src/hooks/useAppTheme.ts](./client/src/hooks/useAppTheme.ts)) is grandfathered for the canvas node components (`AIAgentNode`, `SquareNode`, `TriggerNode`, `StartNode`, `ToolkitNode`, `TeamMonitorNode`, `GenericNode`) and `EdgeConditionEditor` — they interpolate per-definition `nodeColor` into gradients, borders, and React Flow `<Handle>` styles. Credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`) and the skill/tool editors (`SkillEditorModal`, `ToolSchemaEditor`) no longer call it — they compose `<ActionButton intent="...">` plus shadcn semantic tokens (`bg-warning/10`, `bg-accent/10`, `<Alert variant="destructive">`). Every other surface uses Tailwind + the tokens above.
**Theme switching** — `[data-theme="dark"]` + Tailwind's `.dark` class, both set by `App.tsx`'s `useEffect` on `isDarkMode`. See [docs-internal/frontend_architecture.md](./docs-internal/frontend_architecture.md#tokens--theming) for the full token table and migration patterns.
@@ -4118,18 +4126,21 @@ const isConfigHandle = (handle: string | null | undefined): boolean => {
return handle.startsWith('input-') && handle !== 'input-main';
};
-// Check if node is a config/auxiliary node
+// Check if node is a config/auxiliary node — reads the backend-derived
+// uiHint, not a frontend group-string heuristic.
const isConfigNode = (nodeType: string | undefined): boolean => {
+ if (!nodeType) return false;
const definition = resolveNodeDescription(nodeType);
- const groups = definition?.group || [];
- return groups.includes('memory') || groups.includes('tool');
+ return definition?.uiHints?.isConfigNode === true;
};
```
+The `isConfigNode` flag is **auto-derived on the backend** by `_derive_auto_ui_hints` in [`server/services/plugin/base.py`](./server/services/plugin/base.py): plugins whose `group` tuple contains `memory` or `tool` (the centralized `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`) automatically export `uiHints.isConfigNode: True`. Explicit `cls.ui_hints` always wins (merge order: auto-derived first, then `dict.update` with the plugin's declaration). Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name in `server/tests/test_node_spec.py`.
+
### Adding New Config Node Types
-1. Add 'memory' or 'tool' to node's `group` array in definition
-2. Use `input-<type>` naming for the target handle on parent node
-3. Input inheritance and filtering work automatically
+1. Put the plugin in `('memory',)` or `('tool',)` (or any tuple containing one of those). The backend auto-derivation does the rest — do NOT declare `isConfigNode` in `ui_hints` unless you want to override.
+2. Use `input-<type>` naming for the target handle on the parent node.
+3. Input inheritance and filtering work automatically — the frontend reads `definition.uiHints.isConfigNode`, never the group strings.
### Toolkit Sub-Node Execution Pattern
@@ -5236,4 +5247,7 @@ This function:
- **Google OAuth scope expansion**: Google's authorisation server legitimately returns a wider scope set than requested when the OAuth Client's "Data Access" page lists extra scopes (commonly `cloud-platform`) or when `include_granted_scopes` replays a previously-granted scope. `oauthlib` does strict set-equality and aborts with `Warning: Scope has changed`. As of 2026 (`google-auth-oauthlib` 1.2.4, `oauthlib` upstream issue #562 still open), no constructor flag, context manager, or `expected_scopes` argument exists — the documented relief is the env var. `services/google_oauth.py` sets `OAUTHLIB_RELAX_TOKEN_SCOPE=1` via `os.environ.setdefault` BEFORE the `google_auth_oauthlib.flow` import (oauthlib reads it once at parameters-module import; request-time setting races under uvicorn workers), paired with `warnings.filterwarnings(message=r"Scope has changed.*")` to keep the operator log clean. Long-term root cause: audit the Cloud Console Data Access page and remove `cloud-platform` if no handler uses it.
- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` and surface "JavaScript executor not running on localhost:3020. Start the dev runner or fall back to python_executor." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.
- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearChatMessages` / `clearConsoleLogs` / `sendChatMessage` so the callbacks don't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `chatMessages` / `consoleLogs` and refetches both when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard).
+- **Auto-derived `isConfigNode` uiHint**: `_derive_auto_ui_hints(group)` in `services/plugin/base.py` automatically sets `uiHints.isConfigNode: True` on any plugin whose `group` tuple contains `memory` or `tool` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`). Explicit `cls.ui_hints` always wins (merge order: auto first, then `dict.update`). Frontend `InputSection.tsx` and `OutputPanel.tsx` consume the flag via `definition?.uiHints?.isConfigNode === true` — the old `groups.includes('memory') || groups.includes('tool')` heuristic is gone. Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name. Adding a new auxiliary node type costs zero per-plugin code; opting out costs one line (`ui_hints = {"isConfigNode": False}`).
+- **`isMasterSkillEditor` uiHint replaces `node.type === 'masterSkill'` checks**: 6 frontend callsites (`Dashboard.tsx:98` component dispatch, `useAutoSkillEdges.ts` constant + edge filter, `MiddleSection.tsx` × 3) now read `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true` instead of comparing the type string. The `MasterSkillNode` plugin already declared the hint — no backend change. Renaming the plugin's `type` is now a single backend edit followed by a NodeSpec deploy; the frontend never needs to know the string.
+- **`--action-X-hover` triplet + ActionButton zero-arithmetic**: each of the 6 action roles (`run`/`stop`/`save`/`config`/`secret`/`tools`) now exposes a `-hover` variant (0.25 alpha) alongside the existing `-soft` (0.15) and `-border` (0.6). ActionButton's CVA reads `hover:bg-action-X-hover` directly; disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class. No per-token `/25`, `/40`, `/10` opacity arithmetic at any call site. Credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`) and the skill / tool-schema editors (`SkillEditorModal`, `ToolSchemaEditor`) consume `<ActionButton intent="...">` directly. `ActionDef` carries an `intent` key; the catalogue adapter maps server-sent `theme_color` palette strings to intents via `SERVER_COLOR_TO_INTENT`.
- never use emojis in prints
\ No newline at end of file
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 05cbae4d..aaf1d9bf 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -262,7 +262,7 @@ Rules:
|---|---|---|
| **shadcn semantic** | `background`, `foreground`, `card`, `popover`, `primary`, `secondary`, `muted`, `accent`, `destructive`, `success`, `warning`, `info`, `border`, `input`, `ring` | App-wide chrome, status colors, generic actions. Each rotates per theme. |
| **Node-type role** | `node-agent`, `node-model`, `node-skill`, `node-tool`, `node-trigger`, `node-workflow` (+ paired `-soft` and `-border` variants) | Anywhere a node type's identity should drive color: palette icons, parameter-panel sections, draggable variable cards, status badges, edge label tints. |
-| **Action role** | `action-run`, `action-stop`, `action-save`, `action-config`, `action-secret`, `action-tools` (+ paired `-soft` and `-border` variants) | Toolbar icon buttons, File menu items, and the underlying tokens behind `<ActionButton intent="...">`. Semantic role names (run / stop / save / ...), never palette colors. Themes redefine without touching call sites. |
+| **Action role** | `action-run`, `action-stop`, `action-save`, `action-config`, `action-secret`, `action-tools` (each with `-soft` resting bg, `-hover` hover bg, and `-border` outline variants) | Toolbar icon buttons, File menu items, and the underlying tokens behind `<ActionButton intent="...">`. Semantic role names (run / stop / save / ...), never palette colors. The `-hover` triplet means ActionButton's hover state composes via `hover:bg-action-X-hover` instead of opacity arithmetic; disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class. Themes redefine without touching call sites. |
| **Dracula raw** | `dracula-green`, `dracula-purple`, `dracula-pink`, `dracula-cyan`, `dracula-red`, `dracula-orange`, `dracula-yellow` | Constant across themes by design. Used as the underlying palette that `--action-X` and `--node-X` reference; do not consume directly in components. |
### No opacity arithmetic at call sites
@@ -410,10 +410,11 @@ This is the rule that keeps the data layer schema-driven instead of imperatively
| **TanStack Query** | Anything the server has authoritative state for. List / single-record / settings reads. Mutations that change server state. | `useWorkflowsQuery`, `useNodeParamsQuery`, `useUserSettingsQuery`, `useCatalogueQuery`, `useSaveWorkflowMutation`, `useSaveNodeParamsMutation`, `useSaveUserSettingsMutation` |
| **Zustand** | UI-only state that survives navigation. The active edit buffer for the current workflow. Sidebar/panel visibility flags. | `useAppStore.currentWorkflow` (mutable buffer), `sidebarVisible`, `proMode`, `renamingNodeId`, `useCredentialRegistry.selectedId` |
| **`useState` / `useReducer`** | Per-component transient state. Form-field drafts. Hover/focus. | text-input drafts, dropdown-open, inline-edit toggles |
-| **`WebSocketContext`** | Raw WS connection, `sendRequest`, push-only broadcast slices (workflow progress, android/whatsapp/twitter status, console/terminal logs). The provider value is `useMemo`'d so unrelated state changes do not re-render every consumer. Exposes `isOpen` (socket open) and `isReady` (post init-burst) -- gate catalogue/spec queries on `isReady` to avoid racing the serial init awaits. | `androidStatus`, `consoleLogs`, broadcast streams |
+| **`WebSocketContext`** | Raw WS connection, `sendRequest`, push-only broadcast slices (workflow progress, android/whatsapp/twitter status, console/terminal logs). The provider value is `useMemo`'d so unrelated state changes do not re-render every consumer. Exposes `isOpen` (socket open) and `isReady` (post init-burst) -- gate catalogue/spec queries on `isReady`. The init burst now runs **in parallel** via `Promise.allSettled` over named helpers (`probeApiKey`, `loadTerminalLogs`, `loadChatHistory`, `loadConsoleLogs`), each backed by a small `sendBurstRequest` factory that owns its own request id, message handler, and 5 s timeout. `drainPendingSends(ws)` still runs synchronously after the await and before `setIsReady(true)` so the queue replay ordering is preserved. Time-to-`isReady` is one wide round-trip rather than 8 sequential ones. Catalogue invalidation routes through `invalidateCatalogue(queryClient)` ([`hooks/useCatalogueQuery.ts`](../client/src/hooks/useCatalogueQuery.ts)) which debounces the refetch on a 300 ms trailing edge, so an oauth burst or multi-service reconnect collapses to one refetch instead of N. | `androidStatus`, `consoleLogs`, broadcast streams |
| **`stores/nodeStatusStore.ts`** (Zustand) | Per-workflow node-execution statuses -- moved out of WebSocketContext so a status tick does not cascade through the React tree. `useNodeStatus(id)` is a slice selector; only the affected node's consumers re-render. Mirror this pattern for any new high-frequency push state. | `allStatuses[workflowId][nodeId]`, `currentWorkflowId` |
**Hard rules:**
+- **Read Zustand stores via slice selectors, never whole-store destructure.** Always `const x = useAppStore((s) => s.x)`, never `const { x } = useAppStore()`. The whole-store form re-renders the consumer on ANY store mutation (sidebar toggle, unrelated workflow rename, parameter save on another node), which defeats `React.memo` + `nodePropsEqual` on the canvas. Setters are stable refs from Zustand — single-field selectors are the cheapest read. Audited and converted across the canvas + parameter-panel hot paths (every node component, `Dashboard.tsx`, `useDragVariable`, `useParameterPanel`, `useReactFlowNodes`, `useWorkflowManagement`, `InputSection`, `MiddleSection`, `OutputPanel`, `ParameterRenderer`, `ToolSchemaEditor`, `ParameterPanel`, `InputNodesPanel`).
- A list of server records (`workflows`, `nodeParameters`, `userSettings`, `credentialCatalogue`, `userSkills`, node output schemas) lives in TanStack Query. Never duplicate it in Zustand. Phase-1 follow-up commit `c3a7aa4` removed `savedWorkflows` from `useAppStore` for exactly this reason; Wave 3 commit `7706afb` did the same for `userSkills` in MasterSkillEditor.
- Imperative WebSocket request/response inside a component (`useEffect` + `sendRequest` + `setState`) is a code smell — wrap it in a `useQuery` hook. Inline the hook at the top of the consuming file when there's exactly one consumer (Wave 2/3 colocation rule); promote to `client/src/hooks/` when a second consumer appears. Phase-2 commit `b2b6fba` did this for `useParameterPanel` and `useOnboarding`; Wave 3 commits `2c5f227` / `7706afb` / `327f792` followed the same pattern inline inside MiddleSection / MasterSkillEditor / InputSection.
- After a mutation, **invalidate the corresponding query key**, don't manually patch a Zustand list or call a local refetch helper. Mutations that need it from non-React code use the `queryClient` singleton at [client/src/lib/queryClient.ts](../client/src/lib/queryClient.ts).
@@ -427,7 +428,7 @@ Wave 2 introduced two typed fields on `INodeTypeDescription` so panels and the i
### `uiHints` — per-node panel visibility flags
-Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts](../client/src/types/INodeProperties.ts)). Each flag is consumed by exactly one panel and defaults to `false` (the panel renders normally). 14 flags today:
+Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts](../client/src/types/INodeProperties.ts)). Each flag is consumed by exactly one panel and defaults to `false` (the panel renders normally). 15 flags today:
| Flag | Read by | Effect |
|---|---|---|
@@ -435,7 +436,7 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
| `hideOutputSection` | `ParameterPanel`, `OutputSection` | Skip the execution-results panel |
| `hideRunButton` | `ParameterPanel` | Hide the Run button (skill / memory / tool nodes) |
| `hasCodeEditor` | `MiddleSection` | Give the params block extra flex space for an embedded code editor |
-| `isMasterSkillEditor` | `MiddleSection` | Render the MasterSkillEditor split panel |
+| `isMasterSkillEditor` | `MiddleSection`, `Dashboard` (component dispatch), `useAutoSkillEdges` | Render the MasterSkillEditor split panel; route to `ToolkitNode` on the canvas; identify Master Skill aggregators in the auto-skill edge dispatcher |
| `isMemoryPanel` | `MiddleSection` | Render the memory markdown panel + token usage stats |
| `isToolPanel` | `MiddleSection` | Surface the ToolSchemaEditor for connected services |
| `isMonitorPanel` | `MiddleSection`, `ParameterPanel` | Render the team-monitor panel |
@@ -444,8 +445,9 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
| `isChatTrigger` | `ConsolePanel` | This node is a chat-message target |
| `isConsoleSink` | `ConsolePanel` | This node consumes console output (filter source) |
| `hasSkills` | Agent panels | Connect the connected-skills section |
+| `isConfigNode` | `InputSection`, `OutputPanel` | This node is auxiliary configuration — its panel inherits the parent's main inputs instead of showing direct upstream connections. **Auto-derived on the backend** by `_derive_auto_ui_hints` in [`server/services/plugin/base.py`](../server/services/plugin/base.py): plugins whose `group` tuple contains `memory` or `tool` get this for free. Explicit `cls.ui_hints` always wins. |
-Adding new panel behaviour: add a flag to `INodeUIHints`, annotate the relevant node definitions, read the flag in the panel. Don't add another `nodeDefinition.name === '…'` branch.
+Adding new panel behaviour: add a flag to `INodeUIHints`, annotate the relevant node definitions (or extend the auto-derivation rule on the backend), read the flag in the panel. Don't add another `nodeDefinition.name === '…'` branch — six such checks for `'masterSkill'` were retired in this round in favour of `uiHints.isMasterSkillEditor`. Pytest invariant `test_ui_hints_only_carry_known_flags` in `server/tests/test_node_spec.py` locks the flag set; new flags must be added there too.
### Node output shape — backend as single source of truth
@@ -480,8 +482,8 @@ The DIY widget registry (RHF + zod + a tester+rank dispatch) is modeled on n8n's
| File | When to use |
|---|---|
-| [client/src/components/ui/action-button.tsx](../client/src/components/ui/action-button.tsx) | Colored "soft" toolbar button (Run / Save / Cancel / Reset / Stop). One semantic `intent` prop (`run | stop | save | config | secret | tools`) drives bg/border/text against the matching `--action-X` triplet via static Tailwind classes. Replaces the `actionButtonStyle(color, isDisabled)` style helper that was copy-pasted across 4 files. |
-| [client/src/styles/canvasAnimations.ts](../client/src/styles/canvasAnimations.ts) | Canvas-wide CSS injected once into Dashboard's `<style>` tag. Three named groups (`KEYFRAMES`, `edgeStatusStyles`, `nodeStatusStyles`) for the React Flow edge/node status visuals -- adding a new keyframe or status class is a single-file change. |
+| [client/src/components/ui/action-button.tsx](../client/src/components/ui/action-button.tsx) | Colored "soft" toolbar button (Run / Save / Cancel / Reset / Stop). One semantic `intent` prop (`run | stop | save | config | secret | tools`) drives bg / border / text / hover against the matching `--action-X` quartet (`-soft`, `-hover`, `-border`, base) via static Tailwind classes — no opacity arithmetic. Disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class (one rule, all intents). Replaces the `actionButtonStyle(color, isDisabled)` style helper that was copy-pasted across 4 files. The credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`, `ActionBar`) and the skill / tool-schema editors all consume `<ActionButton>` directly; their `ActionDef` records carry an `intent` key, never a free-form colour. |
+| [client/src/styles/canvasAnimations.ts](../client/src/styles/canvasAnimations.ts) | Canvas-wide CSS injected once into Dashboard's `<style>` tag. Three named groups (`KEYFRAMES`, `edgeStatusStyles`, `nodeStatusStyles`) for the React Flow edge/node status visuals -- adding a new keyframe or status class is a single-file change. Light/dark distinction is encoded entirely in the `colors` arg coming from `theme.ts` -- `buildCanvasStyles(colors)` is single-arg with zero hardcoded hexes, and `CanvasStatusColors` carries the full set (`edgeDefault | edgeSelected | edgeExecuting | edgeCompleted | edgeError | edgePending | edgeMemoryActive | edgeToolActive`). The `nodeGlow` keyframe consumes scoped `--node-glow` / `--node-glow-soft` vars so one keyframe serves both themes. |
| [client/src/components/ui/alert-dialog.tsx](../client/src/components/ui/alert-dialog.tsx) | Confirmation / destructive-action modals. **Never hand-roll a `position: fixed; background: rgba(0,0,0,0.5)` backdrop** — use `<AlertDialog open onOpenChange>` with `AlertDialogHeader` / `AlertDialogDescription` / `AlertDialogFooter`. Focus trap, escape-to-close, and `role="alertdialog"` come from Radix. MiddleSection Clear Memory + Reset Skill dialogs are the canonical consumers (Wave 3 commit `61bf23c`). |
| [client/src/components/ui/sonner.tsx](../client/src/components/ui/sonner.tsx) | The `<Toaster />` mount — call `import { toast } from 'sonner'` directly at use sites; do not wrap. |
| [client/src/components/ui/Modal.tsx](../client/src/components/ui/Modal.tsx) | Composition primitive on top of shadcn `<Dialog>`. Owns the recurring "title bar with centered headerActions and a close button + size-constrained content panel" 8 panels share. Not an antd facade. For destructive confirmations prefer `AlertDialog` above. |
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index dc061cb1..38668db8 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -133,6 +133,7 @@ walker does on startup), these registrations happen automatically:
| Node class registration | `_NODE_CLASS_REGISTRY` | `BaseNode.__init_subclass__` on class definition |
| Metadata + Pydantic schemas | `NODE_METADATA`, `NODE_INPUT_MODELS`, `NODE_OUTPUT_SCHEMAS` | same |
| Handler dispatch | `_PLUGIN_HANDLERS` (merged into `NodeExecutor`) | same |
+| Auto-derived `uiHints.isConfigNode: True` | `NODE_METADATA[type]['uiHints']` | `_metadata_dict` runs `_derive_auto_ui_hints(cls.group)` for every plugin in a `('memory', 'tool')` group. Plugin `ui_hints = {...}` always wins. Tells the frontend that the node's panel inherits its parent's main inputs. See [plugin_system.md → Auto-derived uiHints](./plugin_system.md#auto-derived-uihints). |
| Credentials | `CREDENTIAL_REGISTRY` | `Credential.__init_subclass__` when `_credentials.py` is imported |
| Trigger registry + filter builders | `event_waiter.TRIGGER_REGISTRY`, `FILTER_BUILDERS` | back-fill from `TriggerNode` subclasses on first lookup |
| Temporal activity wrapper | `cls.as_activity()` | first call; pooled into the worker queue declared by `task_queue` |
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 6090235b..1bb585fb 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -118,7 +118,7 @@ class SpecializedAgentBase(ActionNode, abstract=True):
| `group` | Tuple of palette groupings (first is primary). |
| `component_kind` | Frontend dispatch: `square` / `trigger` / `agent` / `tool` / `model` / `start` / `generic`. |
| `handles` | React Flow handle topology (`input-main`, `output-main`, …). |
-| `ui_hints` | Dict of panel flags (`hasCodeEditor`, `isMemoryPanel`, …). |
+| `ui_hints` | Dict of panel flags (`hasCodeEditor`, `isMemoryPanel`, `isMasterSkillEditor`, `isToolPanel`, `hasSkills`, `isConfigNode`, …). See "Auto-derived uiHints" below — `isConfigNode` is set automatically for `('memory', 'tool')` group plugins. |
| `annotations` | Pipedream-style: `destructive` / `readonly` / `open_world`. |
| `credentials` | Tuple of `Credential` subclasses the node uses. |
| `Params` | Pydantic `BaseModel` — user-facing parameters. Used for both UI rendering and AI tool schemas. |
@@ -128,6 +128,39 @@ class SpecializedAgentBase(ActionNode, abstract=True):
| `retry_policy` | `RetryPolicy` dataclass (mirrors `temporalio.common.RetryPolicy`). |
| `start_to_close_timeout` / `heartbeat_timeout` | Per-node Temporal knobs. |
+### Auto-derived uiHints
+
+`BaseNode._metadata_dict` (`server/services/plugin/base.py`) calls
+`_derive_auto_ui_hints(cls.group)` to pre-populate panel-visibility
+flags from group membership before merging the plugin's explicit
+`cls.ui_hints`:
+
+```python
+ui_hints = _derive_auto_ui_hints(cls.group)
+ui_hints.update(cls.ui_hints)
+if ui_hints:
+ meta["uiHints"] = ui_hints
+```
+
+The auto-derivation rule today:
+
+| Trigger | Sets | Used by |
+|---|---|---|
+| Plugin's `group` tuple contains `"memory"` or `"tool"` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`) | `uiHints.isConfigNode = True` | Frontend `InputSection.tsx` and `OutputPanel.tsx` — tells the panel that this node is auxiliary configuration and should inherit the parent's main inputs instead of showing direct upstream connections |
+
+**Explicit always wins.** A plugin that wants to opt out of an
+auto-derived flag declares it explicitly: `ui_hints = {"isConfigNode": False}`.
+The merge order (auto first, then `dict.update` with the plugin's
+declaration) means explicit values overwrite auto-derived ones.
+
+**Adding a new auto-derivation rule.** Extend `_derive_auto_ui_hints`
+in `services/plugin/base.py`. The rule must be derivable from
+declared class attributes (group / kind / etc.) — never from runtime
+state. Add the new flag name to `INodeUIHints` in
+`client/src/types/INodeProperties.ts` and to the `known` set in
+`server/tests/test_node_spec.py::test_ui_hints_only_carry_known_flags`
+(the pytest invariant locks the flag set so unknown keys fail CI).
+
### Params schema conventions
**snake_case everywhere.** Field names are the JSON Schema keys, the UI
@@ -1075,6 +1108,30 @@ the per-file walkthrough.
| Lifecycle WebSocket commands | `make_lifecycle_handlers(prefix, source, extra=…)` | provider-specific extra handlers |
| Status refresh on WS connect | `make_status_refresh(source, status_key, broadcast_type)` | nothing — auto-derived from source |
| CLI subprocess invocation | `run_cli_command(binary=…, argv=…, credential=…)` | nothing — credential injection is automatic |
+| Credentials Modal panel | `server/config/credential_providers.json` (read by `services.credential_registry`) | one provider entry: name, category, color, `kind: "oauth"`, `icon_ref`, `status_hook`, `ws.{login,logout,status}` handler names, fields list, instructions string. Frontend modal renders it automatically — no React file edits. |
+| AI tool surface | `services/ai.py` `DEFAULT_TOOL_NAMES` + `DEFAULT_TOOL_DESCRIPTIONS` | one row per dual-purpose ActionNode mapping `<nodeType>` → `<snake_case_of_node_type>` |
+| Skill (LLM teaching markdown) | `server/skills/<agent>/<skill-name>/SKILL.md` (auto-discovered by `SkillLoader`) | the markdown itself, plus the linkage in `visuals.json` (`"<nodeType>": { ..., "skill": "<skill-name>" }`) |
+
+### Tool / skill / visuals naming contract
+
+Three coordinates have to agree for both the LLM tool dispatcher and
+the skill icon resolver to find their target:
+
+| Place | Form | Example |
+|---|---|---|
+| Plugin node `type` | camelCase | `stripeAction` |
+| `visuals.json` key | matches node `type` (camelCase) | `"stripeAction": { "icon": "asset:stripe", ... }` |
+| `services/ai.py` `DEFAULT_TOOL_NAMES[<type>]` | snake_case of node type | `"stripeAction": "stripe_action"` |
+| Skill `allowed-tools` token | matches the LLM tool name above | `allowed-tools: "stripe_action"` |
+
+`SkillLoader._parse_skill_metadata` runs each `allowed-tools` token
+through snake → camel and looks the result up in `visuals.json`.
+Mismatches silently break icon resolution — a skill with
+`allowed-tools: "stripe_cli"` would convert to `stripeCli` and find
+nothing in `visuals.json` even though the node `stripeAction` is
+registered. Stick to `<snake_case_of_node_type>` unless you're
+prepared to maintain alias entries in `visuals.json`. See
+[`server/skills/GUIDE.md → Tool naming`](../server/skills/GUIDE.md#tool-naming--snake_case--camelcase-contract).
### When to use the framework
diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.md
index 4bca2572..beb5c268 100644
--- a/docs-internal/ui_migration_plan.md
+++ b/docs-internal/ui_migration_plan.md
@@ -241,6 +241,31 @@ a shared `resolveIcon` + `resolveLibraryIcon` pair.
- Gmail / Calendar / Telegram / Twitter loadOptions loaders (Phase 4 registry is ready for the one-line registrations).
- ParameterRenderer → DIY widget registry (the capstone); now unblocked on backend since NodeSpec's `uiHints` carry widget routing.
+## Wave 12 — tech-debt cleanup (May 2026)
+
+Closes the surviving pre-Wave-11 tribal patterns and the perf hotspots six parallel exploration passes turned up. Plan: [`.claude/plans/properly-fix-the-tech-dreamy-tarjan.md`](../../.claude/plans/properly-fix-the-tech-dreamy-tarjan.md). Four batches, all four shipped.
+
+| Batch | What it delivers | Where |
+|---|---|---|
+| 1 — schema/uiHints migration | `_derive_auto_ui_hints(group)` in `BaseNode._metadata_dict` auto-sets `uiHints.isConfigNode: True` for every plugin in the centralized `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})` (explicit `cls.ui_hints` always wins via `dict.update`). 8 frontend string-compares retired: 6 `node.type === 'masterSkill'` checks → `uiHints.isMasterSkillEditor`; 2 `groups.includes('memory'\|'tool')` heuristics → `uiHints.isConfigNode`. New `isConfigNode` flag added to `INodeUIHints` and to the `test_ui_hints_only_carry_known_flags` invariant `known` set. | `services/plugin/base.py`, `Dashboard.tsx`, `useAutoSkillEdges.ts`, `MiddleSection.tsx`, `InputSection.tsx`, `OutputPanel.tsx`, `INodeProperties.ts`, `tests/test_node_spec.py` |
+| 2 — theme tokens | Added 6 `--action-X-hover` triplets (0.25 alpha) so ActionButton's hover state is a Tailwind utility (`hover:bg-action-run-hover`), not opacity arithmetic. Disabled state uses shadcn-idiomatic `disabled:opacity-50` on the base class. `ActionDef.themeColor: string` renamed to `ActionDef.intent: ActionButtonIntent`; the catalogue adapter maps server `theme_color` palette strings to intents via a `SERVER_COLOR_TO_INTENT` table. `OAuthConnect`, `EmailPanel`, `QrPairingPanel`, `ActionBar`, `SkillEditorModal`, `ToolSchemaEditor` migrated to `<ActionButton>` and dropped `useAppTheme()`. Dracula-in-functional-UI (warning boxes, error alerts, submit buttons) replaced by shadcn semantic tokens (`bg-warning/10`, `<Alert variant="destructive">`, `bg-accent/10`). Canvas animations parameterized: `CanvasStatusColors` extended with `edgePending`/`edgeMemoryActive`/`edgeToolActive`; two keyframes merged into one color-agnostic `nodeGlow`; `buildCanvasStyles(colors)` is single-arg with zero hardcoded hexes (light/dark difference now lives entirely in `theme.ts`). | `index.css`, `action-button.tsx`, `credentials/{primitives,panels,catalogueAdapter}.tsx`, `SkillEditorModal.tsx`, `ToolSchemaEditor.tsx`, `canvasAnimations.ts`, `theme.ts`, `Dashboard.tsx` |
+| 3 — `useAppStore` selector migration | Whole-store destructure (`useAppStore()`) audited and converted to per-field selectors (`useAppStore((s) => s.X)`) across every canvas node component, `Dashboard.tsx` (~20 fields), and 11 hooks/components in the parameter-panel hot path. Fixes a perf footgun where a sidebar toggle / unrelated workflow mutation re-rendered every canvas node, defeating `React.memo` + `nodePropsEqual`. | `Square/AIAgent/Trigger/Start/Toolkit/Generic/TeamMonitorNode.tsx`, `Dashboard.tsx`, `useDragVariable`, `useParameterPanel`, `useReactFlowNodes`, `useWorkflowManagement`, `Input/Middle/OutputSection`, `OutputPanel`, `ParameterRenderer`, `ToolSchemaEditor`, `ParameterPanel`, `InputNodesPanel` |
+| 4 — WebSocket reliability | Init-burst parallelized: 5 api-key probes + 3 history fetches inside `ws.onopen` collapsed into named helpers (`probeApiKey`, `loadTerminalLogs`, `loadChatHistory`, `loadConsoleLogs`) running together via `Promise.allSettled` over a shared `sendBurstRequest` factory. Time-to-`isReady` drops from ~8 × roundtrip serial to one wide roundtrip. `drainPendingSends(ws)` ordering preserved (still synchronous, before `setIsReady(true)`). New `invalidateCatalogue(queryClient)` helper with a 300 ms trailing-edge debounce; all 8 broadcast handlers in WebSocketContext (`api_key_status`, `whatsapp_status`, `twitter/google/telegram` oauth + status, `credential_catalogue_updated`, `initial_status`) route through it instead of calling `queryClient.invalidateQueries({ queryKey: CATALOGUE_QUERY_KEY })` directly. OAuth bursts / multi-service reconnects collapse to one refetch. | `WebSocketContext.tsx`, `useCatalogueQuery.ts` |
+
+**Wave 12 numbers:**
+- 8 frontend type-string callsites retired.
+- 6 inline-styled credential-modal buttons → `<ActionButton>`. 18 `bg-dracula-*` functional-UI usages → semantic tokens / `<ActionButton>`. 8 hardcoded hex colours in `canvasAnimations.ts` → theme-driven.
+- 19 whole-store `useAppStore()` callsites → per-field selectors.
+- 8 catalogue invalidation callsites → debounced helper.
+- 1 keyframe deduplicated (`nodeGlowDark` + `nodeGlowLight` → `nodeGlow`).
+- `tsc --noEmit` clean. 106/108 backend NodeSpec invariants green (the 2 deselected check `props["temperature"]["minimum"]` on aiAgent — a pre-existing Pydantic v2 / `Optional[float]` `anyOf` rendering issue unrelated to this batch).
+
+**Architectural delta (permanent):**
+- The frontend stopped string-comparing on node-type and group strings for visibility / behaviour decisions. All such decisions read backend `uiHints` flags. Group strings (`memory`, `tool`) live in exactly one place: `_CONFIG_NODE_GROUPS` on the backend.
+- ActionButton's CVA file is a pure role → token-name mapping. No opacity arithmetic, no per-token disabled overrides.
+- Canvas animations have no light/dark branch and no hardcoded hexes. The `colors` arg coming from `theme.ts` carries everything.
+- Catalogue invalidation has one debounced funnel; broadcast handlers don't call `queryClient.invalidateQueries` directly.
+
## Context
The MachinaOs frontend was coupled to Ant Design (40 files, 187-line theme file, `ConfigProvider` at root). Pre-migration audit + research docs (now deleted; see git history under commit `4cb3dd9` if needed) prescribed shadcn/ui (canonical components copied via CLI registry) + Radix primitives + Tailwind 4 + JSON Forms for a schema-driven inspector. Phase 0/1 commits (`2209dba`, `7ac69fe`) included hand-written primitives and a toast facade — those got deleted as part of corrected Phase 0 (`cdeebb4`).
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 2a9d59be..b3149938 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -314,6 +314,18 @@ Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folde
subclasses and auto-inject at execution time. Plugins that need the
injected key read `ctx.raw["_raw_parameters"]["api_key"]` — it's
stashed before Pydantic validation strips it.
+- **`isConfigNode` is auto-derived — don't declare it.** Plugins
+ whose `group` tuple contains `"memory"` or `"tool"` automatically
+ export `uiHints.isConfigNode: True` (set by `_derive_auto_ui_hints`
+ in `services/plugin/base.py`). The flag tells the frontend that the
+ node's parameter panel inherits its parent's main inputs instead
+ of showing direct upstream connections. If you genuinely want to
+ opt out, declare `ui_hints = {"isConfigNode": False}` — explicit
+ always wins via `dict.update`. Adding a new auto-derivation rule
+ goes in `_derive_auto_ui_hints`, not in individual plugins; new
+ uiHint flags must also be added to `INodeUIHints` in
+ `client/src/types/INodeProperties.ts` and to the `known` set in
+ `server/tests/test_node_spec.py::test_ui_hints_only_carry_known_flags`.
---