Skip to content

Self-improving AI Employees for everyone

refactor(client): delete 1,663 lines of unreachable UI modules

trohitg3c1b031a7d34
diff --git a/CLAUDE.md b/CLAUDE.md
index 1e9b3a97..7079e90a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -549,7 +549,7 @@ The frontend uses a layered cache + slice-subscription model so cold refreshes a
### `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.
+- Audited and converted across the canvas + parameter-panel hot paths: every node component, `Dashboard.tsx`, `useDragVariable`, `useParameterPanel`, `useReactFlowNodes`, `useWorkflowManagement`, `InputSection`, `MiddleSection`, `OutputPanel`, `ParameterRenderer`, `ParameterPanel`. 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 init burst (api-key probes, terminal / chat / console history) settles.
@@ -622,7 +622,6 @@ AI model nodes route through `SquareNode` via `Dashboard.tsx`'s `COMPONENT_BY_KI
- `src/hooks/useParameterPanel.ts` - Parameter management via WebSocket
- `src/services/executionService.ts` - Node execution via WebSocket (`executeNodeViaWebSocket`)
- `src/hooks/useApiKeys.ts` - API key management via WebSocket
-- `src/hooks/useAndroidOperations.ts` - Android device operations via WebSocket
- `src/hooks/useWhatsApp.ts` - WhatsApp operations via WebSocket
- `src/hooks/useDragAndDrop.ts` - Drag-and-drop functionality (palette → canvas, `application/reactflow`)
- `src/hooks/useDragWorkspaceFile.ts` - Drag a workspace file onto another node's parameter (`workspaceFile` payload); mirrors `useDragVariable`'s dual-MIME contract — `application/json` for the structured payload, `text/plain` for the bare path
@@ -1440,7 +1439,7 @@ All pricing in `server/config/pricing.json` (user-editable):
### Frontend Display
-`CredentialsModal.renderApiUsagePanel()` shows per-service usage and costs.
+`credentials/sections/ApiUsageSection.tsx` shows per-service API usage and costs; `LlmUsageSection.tsx` shows per-provider token usage. Both read **precomputed** costs (`SUM(APIUsageMetric.cost)` / `TokenUsageMetric`) — neither reads `config/pricing.json`, which is consumed only server-side by `PricingService` at execution time.
## AI Agent Tool System
@@ -1561,11 +1560,15 @@ service_id_map = {
The former `androidTool` gateway node (single `android_device` tool aggregating multiple Android service nodes, n8n Sub-Node / LangChain Toolkit pattern) no longer exists. Android service nodes connect straight to `input-tools`, and sub-node exclusion keys solely on AI-agent config handles (`input-context` / `input-tools` / `input-skill` / `input-teammates`) — the `TOOLKIT_NODE_TYPES` constant was deleted along with all its usage sites. Legacy `service -> androidTool -> agent` graphs are rewritten on load by `services/workflow_migrations.normalize_legacy_android_toolkit`.
### Tool Schemas (per-service customization)
-Custom LLM-visible schemas for Android service tools persist in the `tool_schemas` table and are read by the AI service at execution time. (The `ToolSchemaEditor.tsx` UI component shipped with the retired Android Toolkit node and was removed with it; the `useToolSchema` hook, WebSocket handlers, and database CRUD remain.)
+Custom LLM-visible schemas for Android service tools persist in the `tool_schemas` table and are read by the AI service at execution time.
+
+**The write path has no reachable entry point — this is a known gap, not a design.** `ToolSchemaEditor.tsx` shipped with the retired Android Toolkit node and was removed with it; the `useToolSchema` client hook was its only consumer and was deleted in turn once it had zero importers. The WebSocket handlers and database CRUD remain, but nothing reachable calls `save_tool_schema` any more: no REST route writes the table and no server-internal code calls `database.save_tool_schema` outside the WS handler itself. So rows can only survive from before the editor was removed, or be written by hand.
+
+The **read** path is live and load-bearing — do not delete it as "unused". [`services/ai.py`](./server/services/ai.py) fetches the stored row during tool construction and overrides `tool_name` / `tool_description` / `connected_services` from it, and `_build_schema_from_config` turns `schema_config["fields"]` into the actual LLM-visible tool schema. Restoring an editor means giving `save_tool_schema` a caller again; it does not require touching the read side.
#### Architecture
```
-useToolSchema Hook (WebSocket CRUD)
+(no client writer — see above)
↓
Database (tool_schemas table)
↓
@@ -1575,7 +1578,6 @@ useToolSchema Hook (WebSocket CRUD)
#### Key Files
| File | Description |
|------|-------------|
-| `client/src/hooks/useToolSchema.ts` | WebSocket hook for schema CRUD operations |
| `server/models/database.py` | `ToolSchema` SQLModel table definition |
| `server/core/database.py` | Database CRUD methods for tool schemas |
| `server/routers/websocket.py` | WebSocket handlers for schema operations |
@@ -2517,11 +2519,8 @@ Hook for API key management via WebSocket:
const { validateApiKey, getStoredKey, saveApiKey, deleteApiKey } = useApiKeys();
```
-### useAndroidOperations (`client/src/hooks/useAndroidOperations.ts`)
-Hook for Android device operations via WebSocket:
-```typescript
-const { getDevices, executeAction, setupDevice, isConnected, deviceStatus } = useAndroidOperations();
-```
+### Android operations (no dedicated hook)
+Android work goes through the WebSocket context directly — `getAndroidDevices` / `executeAndroidAction` / `androidStatus` off `useWebSocket()`, or a raw `sendRequest('android_relay_connect', …)`. A `useAndroidOperations` hook once wrapped those context methods; every live surface bypassed it, so it was deleted.
### useParameterPanel (`client/src/hooks/useParameterPanel.ts`)
Hook for parameter management via WebSocket:
@@ -2740,7 +2739,7 @@ This function:
- **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.
- **`outputMode: "terminal"` uiHint — spec-driven CLI output rendering**: the output panel (`components/output/OutputPanel.tsx`, the active renderer — `ui/OutputDisplayPanel.tsx` is legacy/unimported) renders string responses through ReactMarkdown by default, which whitespace-collapses CLI text. CLI-wrapper plugins (`githubAction`, `vercelAction`, `shell`) declare `ui_hints = {"outputMode": "terminal"}`; the panel resolves the spec via `useNodeSpec(selectedNode?.type)` and renders their text in a `<pre>` on the per-theme `--code-*` surface, routes wholly-JSON strings to the JSON tree via the shared `tryParseJson` (`utils/formatters.ts`), and surfaces object/array `result` payloads (server-side-parsed CLI JSON; arrays survive `unwrap` un-peeled) in the Response section. Pair with the `_shape` convention: parsed JSON in `result` OR text in `stdout` — never both — empty keys omitted. Locked by `client/src/components/__tests__/OutputPanel.test.tsx` (render tests: real `\n`/`\t` preserved) + the uiHints known-set in `test_node_spec.py`. Cache note: nodeSpecs are session-sticky (`staleTime: FOREVER`, revision-busted at page load) — after a backend restart a hard browser reload is needed before new uiHints reach an open canvas.
-- **`--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`.
+- **`--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 editor (`MasterSkillEditor`) 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`.
- **Credentials: DB as single source of truth + symmetric broadcasts + cache dedup**: `CredentialsDatabase` (encrypted SQLite) is canonical; every other layer is a derived cache with explicit invalidation. Backend `AuthService._memory_cache + _models_cache` collapsed into one `_api_key_cache: Dict[str, ApiKeyCacheEntry]` dataclass — single write/evict site. Per RFC 9700 (OAuth 2.0 BCP, 2024) the `_oauth_cache` no longer carries `refresh_token`; new `get_oauth_refresh_token(provider, customer)` reads from the encrypted DB on every call. `validate_api_key`, `save_api_key`, `delete_api_key`, `twitter_logout`, `google_logout` now broadcast symmetrically: `update_api_key_status` (in-memory map) + `broadcast_credential_event(...)` (refetch signal) wrapping `WorkflowEvent` (CloudEvents v1.0 from `services/events/envelope.py`, the same envelope the Wave 12 EventSource framework uses). The dead-letter `credential_catalogue_updated` event is finally emitted by the backend. Frontend retired the 200-LOC `client/src/components/credentials/providers.tsx` static fallback — `useCatalogueQuery` is the only source; cold-boot renders `<Skeleton>`, server-unreachable shows an explicit error state. `ApiKeyStatus.hasKey` mirror dropped (duplicated catalogue's `provider.stored`); two new selector hooks (`useProviderStored`, `useStoredProviderCount`) read the catalogue. Pytest invariant `test_credential_broadcasts.py` (14 tests) locks the broadcast contract via `inspect.getsource` introspection + the CloudEvents v1.0 envelope shape + AuthService DB-write-then-cache-update ordering + the no-refresh-token-in-cache rule.
- **Local-LLM provider routing + per-model context**: Ollama and LM Studio are first-class providers (12 total for agents: 10 cloud + 2 local). Provider detection is driven by `detect_ai_provider` in `server/constants.py` plus the `provider` Literal in `nodes/agent/{ai_agent,chat_agent,_specialized}.py` — both MUST list `ollama` / `lmstudio` or chat-model nodes / agent dropdowns silently fall through to `'openai'` and `execute_chat` calls api.openai.com with the placeholder key. The validator at `nodes/model/_local_validator.py` probes via the official SDKs (`ollama.AsyncClient.ps()` for typed `ProcessResponse.Model`, `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo`) — reads only typed fields (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`, plus Ollama's `details.{family,parameter_size,quantization_level}`). No regex, no Modelfile-parameters parsing, no `/api/show` modelinfo dict-key hunting. Per-model params persist in `EncryptedAPIKey.models["model_params"]` (via `save_api_key(model_params=...)`) AND in `model_registry.json` via `register_local_model()` — sync `get_context_length()` / `get_max_output_tokens()` find real values without async DB lookups, and entries survive process restart. `is_model_valid_for_provider` returns `True` for open-world providers (`openrouter` / `ollama` / `lmstudio`) so local model names like `qwen/qwen3.6-27b` aren't rejected by the cloud-style pattern check. Runtime path uses `OpenAIProvider(base_url={user_proxy_url}, api_key="ollama")` — traffic stays on `localhost`.
- **Typed SDK error → `LLMError` → `NodeUserError`**: Native providers normalize SDK failures into structured `LLMError` values carrying category, retryability, HTTP status, provider code, request ID, and retry-after metadata. `ChatUnifier` translates them at the execution boundary into a user-safe `NodeUserError`; `BaseNode.execute()` logs that at WARN with one line and no stack trace. Unexpected exceptions retain the full-traceback path. In-process agent turns retry only errors marked retryable, while Temporal owns activity retries and disables the inner retry loop.
diff --git a/client/src/components/PricingConfigModal.tsx b/client/src/components/PricingConfigModal.tsx
deleted file mode 100644
index b2ce56ee..00000000
--- a/client/src/components/PricingConfigModal.tsx
+++ /dev/null
@@ -1,375 +0,0 @@
-/**
- * PricingConfigModal - View and edit pricing configuration
- * Displays LLM and API pricing in a tree view with inline editing
- */
-
-import React, { useState, useEffect, useCallback } from 'react';
-import { Loader2, RefreshCw, Save, DollarSign } from 'lucide-react';
-
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import {
- Accordion,
- AccordionItem,
- AccordionTrigger,
- AccordionContent,
-} from '@/components/ui/accordion';
-import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
-import { toast } from 'sonner';
-import Modal from './ui/Modal';
-import { ActionButton } from './ui/action-button';
-import { usePricing, PricingConfig, LLMPricing } from '../hooks/usePricing';
-
-// ============================================================================
-// TYPES
-// ============================================================================
-
-interface Props {
- visible: boolean;
- onClose: () => void;
-}
-
-// ============================================================================
-// HELPER COMPONENTS
-// ============================================================================
-
-interface MoneyInputProps {
- value: number | undefined;
- onChange: (v: number) => void;
- widthClass?: string;
- min?: number;
- step?: number;
-}
-
-const MoneyInput: React.FC<MoneyInputProps> = ({ value, onChange, widthClass = 'w-20', min = 0, step = 0.01 }) => (
- <div className={`relative ${widthClass}`}>
- <span className="pointer-events-none absolute top-1/2 left-2 -translate-y-1/2 text-xs text-muted-foreground">
- $
- </span>
- <Input
- type="number"
- min={min}
- step={step}
- value={value ?? ''}
- onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
- className="h-7 pl-5 pr-1 text-xs"
- />
- </div>
-);
-
-interface LLMModelRowProps {
- model: string;
- pricing: LLMPricing;
- onChange: (field: keyof LLMPricing, value: number) => void;
-}
-
-const LLMModelRow: React.FC<LLMModelRowProps> = ({ model, pricing, onChange }) => (
- <div
- className={`flex items-center gap-3 border-b border-border px-3 py-2 ${
- model === '_default' ? 'bg-node-agent-soft' : ''
- }`}
- >
- <div
- className={`flex-1 font-mono text-[13px] ${
- model === '_default' ? 'text-node-agent' : 'text-foreground'
- }`}
- >
- {model === '_default' ? 'Default' : model}
- </div>
- <div className="flex items-center gap-2">
- <span className="text-[11px] text-muted-foreground">Input:</span>
- <MoneyInput value={pricing.input} onChange={(v) => onChange('input', v)} />
- <span className="text-[11px] text-muted-foreground">Output:</span>
- <MoneyInput value={pricing.output} onChange={(v) => onChange('output', v)} />
- {pricing.cache_read !== undefined && (
- <>
- <span className="text-[11px] text-muted-foreground">Cache:</span>
- <MoneyInput value={pricing.cache_read} onChange={(v) => onChange('cache_read', v)} widthClass="w-[72px]" />
- </>
- )}
- {pricing.reasoning !== undefined && (
- <>
- <span className="text-[11px] text-muted-foreground">Reasoning:</span>
- <MoneyInput value={pricing.reasoning} onChange={(v) => onChange('reasoning', v)} />
- </>
- )}
- </div>
- </div>
-);
-
-interface APIPricingRowProps {
- operation: string;
- price: number;
- onChange: (value: number) => void;
-}
-
-const APIPricingRow: React.FC<APIPricingRowProps> = ({ operation, price, onChange }) => {
- // Skip metadata keys
- if (operation.startsWith('_')) return null;
-
- return (
- <div className="flex items-center justify-between border-b border-border px-3 py-2">
- <div className="font-mono text-[13px] text-foreground">
- {operation}
- </div>
- <MoneyInput value={price} onChange={onChange} widthClass="w-24" step={0.001} />
- </div>
- );
-};
-
-// ============================================================================
-// MAIN COMPONENT
-// ============================================================================
-
-const PricingConfigModal: React.FC<Props> = ({ visible, onClose }) => {
- const { getPricingConfig, savePricingConfig, isConnected } = usePricing();
-
- const [config, setConfig] = useState<PricingConfig | null>(null);
- const [loading, setLoading] = useState(false);
- const [saving, setSaving] = useState(false);
- const [isDirty, setIsDirty] = useState(false);
-
- // Load config on mount
- const loadConfig = useCallback(async () => {
- if (!isConnected) return;
- setLoading(true);
- try {
- const data = await getPricingConfig();
- setConfig(data);
- setIsDirty(false);
- } catch (error) {
- toast.error('Failed to load pricing config');
- } finally {
- setLoading(false);
- }
- }, [getPricingConfig, isConnected]);
-
- useEffect(() => {
- if (visible) {
- loadConfig();
- }
- }, [visible, loadConfig]);
-
- // Save config
- const handleSave = useCallback(async () => {
- if (!config) return;
- setSaving(true);
- try {
- const success = await savePricingConfig(config);
- if (success) {
- toast.success('Pricing config saved');
- setIsDirty(false);
- } else {
- toast.error('Failed to save pricing config');
- }
- } catch (error) {
- toast.error('Failed to save pricing config');
- } finally {
- setSaving(false);
- }
- }, [config, savePricingConfig]);
-
- // Update LLM pricing
- const updateLLMPricing = useCallback((
- provider: string,
- model: string,
- field: keyof LLMPricing,
- value: number
- ) => {
- if (!config) return;
- setConfig(prev => {
- if (!prev) return prev;
- const updated = { ...prev };
- if (!updated.llm[provider]) updated.llm[provider] = {};
- if (!updated.llm[provider][model]) {
- updated.llm[provider][model] = { input: 0, output: 0 };
- }
- updated.llm[provider][model] = { ...updated.llm[provider][model], [field]: value };
- return updated;
- });
- setIsDirty(true);
- }, [config]);
-
- // Update API pricing
- const updateAPIPricing = useCallback((
- service: string,
- operation: string,
- value: number
- ) => {
- if (!config) return;
- setConfig(prev => {
- if (!prev) return prev;
- const updated = { ...prev };
- if (!updated.api[service]) updated.api[service] = {};
- (updated.api[service] as Record<string, number>)[operation] = value;
- return updated;
- });
- setIsDirty(true);
- }, [config]);
-
- // Render LLM tab
- const renderLLMTab = () => {
- if (!config?.llm) return null;
-
- const providers = Object.keys(config.llm).sort();
-
- return (
- <Accordion type="multiple" defaultValue={providers.slice(0, 2)} className="bg-transparent">
- {providers.map((provider) => {
- const models = config.llm[provider];
- const modelNames = Object.keys(models).sort((a, b) => {
- if (a === '_default') return 1;
- if (b === '_default') return -1;
- return a.localeCompare(b);
- });
-
- return (
- <AccordionItem key={provider} value={provider}>
- <AccordionTrigger>
- <span className="font-medium capitalize">
- {provider}
- <span className="ml-2 text-xs text-muted-foreground">
- ({modelNames.length} models)
- </span>
- </span>
- </AccordionTrigger>
- <AccordionContent>
- <div className="px-3 py-1 text-[11px] text-muted-foreground">
- Prices in USD per million tokens (MTok)
- </div>
- {modelNames.map((model) => (
- <LLMModelRow
- key={model}
- model={model}
- pricing={models[model]}
- onChange={(field, value) => updateLLMPricing(provider, model, field, value)}
- />
- ))}
- </AccordionContent>
- </AccordionItem>
- );
- })}
- </Accordion>
- );
- };
-
- // Render API tab
- const renderAPITab = () => {
- if (!config?.api) return null;
-
- const services = Object.keys(config.api).sort();
-
- return (
- <Accordion type="multiple" defaultValue={services} className="bg-transparent">
- {services.map((service) => {
- const operations = config.api[service];
- const opNames = Object.keys(operations).filter((k) => !k.startsWith('_')).sort();
- const description = (operations as Record<string, string | number>)._description as string | undefined;
- const source = (operations as Record<string, string | number>)._source as string | undefined;
-
- return (
- <AccordionItem key={service} value={service}>
- <AccordionTrigger>
- <span className="font-medium capitalize">
- {service}
- <span className="ml-2 text-xs text-muted-foreground">
- ({opNames.length} operations)
- </span>
- </span>
- </AccordionTrigger>
- <AccordionContent>
- {description && (
- <div className="px-3 py-1 pb-2 text-xs text-muted-foreground">
- {description}
- {source && (
- <a
- href={source}
- target="_blank"
- rel="noopener noreferrer"
- className="ml-2 text-info"
- >
- Source
- </a>
- )}
- </div>
- )}
- <div className="px-3 py-1 text-[11px] text-muted-foreground">
- Prices in USD per resource/request
- </div>
- {opNames.map((operation) => (
- <APIPricingRow
- key={operation}
- operation={operation}
- price={(operations as Record<string, number>)[operation]}
- onChange={(value) => updateAPIPricing(service, operation, value)}
- />
- ))}
- </AccordionContent>
- </AccordionItem>
- );
- })}
- </Accordion>
- );
- };
-
- return (
- <Modal
- isOpen={visible}
- onClose={onClose}
- title="Pricing Configuration"
- maxWidth="700px"
- maxHeight="85vh"
- headerActions={
- <div className="flex gap-2">
- <Button size="sm" variant="outline" onClick={loadConfig} disabled={loading}>
- {loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
- Reload
- </Button>
- <ActionButton intent="save" onClick={handleSave} disabled={!isDirty || saving}>
- {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
- Save
- </ActionButton>
- </div>
- }
- >
- <div className="p-4">
- {loading ? (
- <div className="flex items-center justify-center p-10">
- <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
- </div>
- ) : config ? (
- <>
- {/* Version info */}
- <div className="mb-4 flex items-center justify-between rounded-md bg-bg-panel px-3 py-2">
- <div className="flex items-center gap-2">
- <DollarSign className="h-4 w-4 text-warning" />
- <span className="text-muted-foreground">
- Version: <strong className="text-foreground">{config.version}</strong>
- </span>
- </div>
- <span className="text-xs text-muted-foreground">
- Last updated: {config.last_updated}
- </span>
- </div>
-
- {/* Tabs */}
- <Tabs defaultValue="llm">
- <TabsList>
- <TabsTrigger value="llm">LLM Pricing</TabsTrigger>
- <TabsTrigger value="api">API Pricing</TabsTrigger>
- </TabsList>
- <TabsContent value="llm">{renderLLMTab()}</TabsContent>
- <TabsContent value="api">{renderAPITab()}</TabsContent>
- </Tabs>
- </>
- ) : (
- <div className="p-10 text-center text-muted-foreground">
- {isConnected ? 'Failed to load config' : 'Not connected'}
- </div>
- )}
- </div>
- </Modal>
- );
-};
-
-export default PricingConfigModal;
diff --git a/client/src/components/SkillEditorModal.tsx b/client/src/components/SkillEditorModal.tsx
deleted file mode 100644
index ab9dfaf6..00000000
--- a/client/src/components/SkillEditorModal.tsx
+++ /dev/null
@@ -1,408 +0,0 @@
-/* eslint-disable react-hooks/incompatible-library -- react-hook-form's watch()
- cannot be memoized safely; the compiler (>= 1.0.0) skips this component
- rather than miscompiling it, so the warning is advisory. Not true before
- 1.0.0 — do not downgrade. */
-import React, { useEffect } from 'react';
-import { useForm } from 'react-hook-form';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { z } from 'zod';
-import Modal from './ui/Modal';
-import CodeEditor from './ui/CodeEditor';
-import { useWebSocket } from '../contexts/WebSocketContext';
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@/components/ui/form';
-import { Input } from '@/components/ui/input';
-import { Textarea } from '@/components/ui/textarea';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select';
-import { Button } from '@/components/ui/button';
-import { ActionButton } from '@/components/ui/action-button';
-import { Alert, AlertDescription } from '@/components/ui/alert';
-import { Switch } from '@/components/ui/switch';
-
-// ---------------------------------------------------------------------------
-// Schema (one source of truth for type, defaults, and validation).
-// ---------------------------------------------------------------------------
-
-const userSkillSchema = z.object({
- id: z.number().optional(),
- name: z
- .string()
- .min(1, 'Internal name is required')
- .regex(/^[a-z0-9-]+$/, 'Use lowercase letters, digits, and hyphens only'),
- display_name: z.string().min(1, 'Display name is required'),
- description: z.string().min(1, 'Description is required'),
- instructions: z.string().min(1, 'Instructions are required'),
- allowed_tools: z.array(z.string()).default([]),
- category: z.string().default('custom'),
- icon: z.string().default('star'),
- color: z.string().default('#6366F1'),
- is_active: z.boolean().default(true),
-});
-
-export type UserSkill = z.infer<typeof userSkillSchema>;
-
-const DEFAULT_SKILL: UserSkill = userSkillSchema.parse({
- name: '',
- display_name: '',
- description: '',
- instructions: `# My Custom Skill
-
-## Capabilities
-- Describe what this skill can do
-- List the main functions
-
-## Usage
-Explain when and how the Zeenie should use this skill.
-
-## Examples
-
-**User**: "Example request"
-**Action**: Describe what the skill does in response
-`,
-});
-
-const CATEGORY_OPTIONS = [
- { value: 'custom', label: 'Custom' },
- { value: 'communication', label: 'Communication' },
- { value: 'productivity', label: 'Productivity' },
- { value: 'automation', label: 'Automation' },
- { value: 'integration', label: 'Integration' },
- { value: 'utility', label: 'Utility' },
-];
-
-const ICON_OPTIONS = [
- { value: 'star', label: 'Star' },
- { value: 'sparkles', label: 'Sparkles' },
- { value: 'brain', label: 'Brain' },
- { value: 'code', label: 'Code' },
- { value: 'globe', label: 'Globe' },
- { value: 'chat', label: 'Chat' },
- { value: 'calendar', label: 'Calendar' },
- { value: 'settings', label: 'Settings' },
-];
-
-const COLOR_OPTIONS = [
- '#6366F1', '#8B5CF6', '#EC4899', '#EF4444',
- '#F59E0B', '#10B981', '#3B82F6', '#06B6D4',
-];
-
-interface SkillEditorModalProps {
- isOpen: boolean;
- onClose: () => void;
- skill?: UserSkill | null;
- onSave?: (skill: UserSkill) => void;
-}
-
-const SkillEditorModal: React.FC<SkillEditorModalProps> = ({
- isOpen,
- onClose,
- skill,
- onSave,
-}) => {
- const { sendRequest } = useWebSocket();
- const [activeTab, setActiveTab] = React.useState<'details' | 'instructions'>('details');
- const [submitError, setSubmitError] = React.useState<string | null>(null);
-
- const form = useForm({
- resolver: zodResolver(userSkillSchema),
- defaultValues: skill ?? DEFAULT_SKILL,
- mode: 'onSubmit',
- });
-
- // Reset form when modal opens or the edited skill changes.
- useEffect(() => {
- if (!isOpen) return;
- form.reset(skill ?? DEFAULT_SKILL);
- setSubmitError(null);
- }, [isOpen, skill, form]);
-
- const handleDisplayNameChange = (value: string) => {
- form.setValue('display_name', value, { shouldValidate: false, shouldDirty: true });
- // Auto-derive internal name only for new skills (no id).
- if (!form.getValues('id')) {
- const derived = value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
- form.setValue('name', derived, { shouldValidate: false, shouldDirty: true });
- }
- };
-
- const onSubmit = async (values: UserSkill) => {
- setSubmitError(null);
- try {
- const messageType = values.id ? 'update_user_skill' : 'create_user_skill';
- const response = await sendRequest<{ success?: boolean; skill?: UserSkill; error?: string }>(
- messageType,
- { ...values, allowed_tools: values.allowed_tools.join(',') },
- );
- if (response?.success) {
- onSave?.(response.skill ?? values);
- onClose();
- } else {
- setSubmitError(response?.error || 'Failed to save skill');
- }
- } catch (err: any) {
- setSubmitError(err?.message || 'Failed to save skill');
- }
- };
-
- const isSaving = form.formState.isSubmitting;
- const isExisting = !!form.watch('id');
- const tabBaseClass =
- 'px-4 py-2 text-sm font-medium border-b-2 border-transparent transition-colors';
- const tabActiveClass = 'border-primary text-foreground';
- const tabInactiveClass = 'text-muted-foreground hover:text-foreground';
-
- return (
- <Modal
- isOpen={isOpen}
- onClose={onClose}
- title={isExisting ? 'Edit Skill' : 'Create Skill'}
- maxWidth="700px"
- maxHeight="85vh"
- >
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="flex h-full flex-col"
- >
- {/* Tabs */}
- <div className="flex border-b border-border bg-background">
- <button
- type="button"
- className={`${tabBaseClass} ${activeTab === 'details' ? tabActiveClass : tabInactiveClass}`}
- onClick={() => setActiveTab('details')}
- >
- Details
- </button>
- <button
- type="button"
- className={`${tabBaseClass} ${activeTab === 'instructions' ? tabActiveClass : tabInactiveClass}`}
- onClick={() => setActiveTab('instructions')}
- >
- Instructions
- </button>
- </div>
-
- <div className="flex-1 overflow-auto p-4">
- {activeTab === 'details' && (
- <div className="flex flex-col gap-4">
- <FormField
- control={form.control}
- name="display_name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Display Name *</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="My Custom Skill"
- onChange={(e) => handleDisplayNameChange(e.target.value)}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Internal Name *</FormLabel>
- <FormControl>
- <Input
- {...field}
- placeholder="my-custom-skill"
- readOnly={isExisting}
- className={isExisting ? 'opacity-70' : undefined}
- onChange={(e) =>
- field.onChange(e.target.value.toLowerCase().replace(/\s+/g, '-'))
- }
- />
- </FormControl>
- <FormDescription>Used internally to identify the skill.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description *</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- rows={3}
- placeholder="A short description of what this skill does..."
- />
- </FormControl>
- <FormDescription>
- Shown in the skill registry to help the agent decide when to use it.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <div className="flex gap-4">
- <FormField
- control={form.control}
- name="category"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Category</FormLabel>
- <Select onValueChange={field.onChange} value={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {CATEGORY_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="color"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Color</FormLabel>
- <div className="flex flex-wrap gap-1">
- {COLOR_OPTIONS.map((color) => (
- <button
- key={color}
- type="button"
- onClick={() => field.onChange(color)}
- className="h-7 w-7 rounded cursor-pointer"
- style={{
- backgroundColor: color,
- border: field.value === color ? '2px solid white' : 'none',
- boxShadow: field.value === color ? `0 0 0 2px ${color}` : 'none',
- }}
- />
- ))}
- </div>
- </FormItem>
- )}
- />
- </div>
-
- <FormField
- control={form.control}
- name="icon"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Icon</FormLabel>
- <Select onValueChange={field.onChange} value={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {ICON_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="is_active"
- render={({ field }) => (
- <FormItem className="flex items-center gap-2 space-y-0">
- <FormControl>
- <Switch checked={field.value} onCheckedChange={field.onChange} />
- </FormControl>
- <FormLabel className="!mt-0">Skill is active</FormLabel>
- </FormItem>
- )}
- />
- </div>
- )}
-
- {activeTab === 'instructions' && (
- <div className="flex h-full flex-col gap-3">
- <div className="text-sm text-muted-foreground">
- Write markdown instructions for the agent. Include capabilities, usage
- guidelines, and examples.
- </div>
- <FormField
- control={form.control}
- name="instructions"
- render={({ field }) => (
- <FormItem className="flex-1 min-h-[400px]">
- <FormControl>
- <CodeEditor
- value={field.value}
- onChange={field.onChange}
- language="markdown"
- placeholder={`# Skill Instructions
-
-## Capabilities
-- ...
-
-## Usage
-...
-
-## Examples
-...`}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- )}
- </div>
-
- {submitError && (
- <Alert variant="destructive" className="rounded-none border-x-0 border-b-0">
- <AlertDescription>{submitError}</AlertDescription>
- </Alert>
- )}
-
- <div className="flex justify-end gap-3 border-t border-border bg-card px-4 py-3">
- <Button type="button" variant="outline" onClick={onClose}>
- Cancel
- </Button>
- <ActionButton intent="save" type="submit" disabled={isSaving}>
- {isSaving ? 'Saving...' : isExisting ? 'Update Skill' : 'Create Skill'}
- </ActionButton>
- </div>
- </form>
- </Form>
- </Modal>
- );
-};
-
-export default SkillEditorModal;
diff --git a/client/src/components/maps/index.ts b/client/src/components/maps/index.ts
deleted file mode 100644
index 8e2e3fd6..00000000
--- a/client/src/components/maps/index.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// Maps Components
-export { default as GoogleMapsPicker } from './GoogleMapsPicker';
-export { default as MapsPreviewPanel } from './MapsPreviewPanel';
-
-// Re-export types for convenience
-export interface GoogleMapsPickerProps {
- lat: number;
- lng: number;
- onLocationClick: (lat: number, lng: number) => void;
- apiKey?: string;
- zoom?: number;
- mapTypeId?: string;
- height?: string;
- width?: string;
-}
-
-export interface MapsPreviewPanelProps {
- lat: number;
- lng: number;
- zoom?: number;
- mapTypeId?: string;
- apiKey?: string;
- onLocationClick: (lat: number, lng: number) => void;
- title?: string;
- description?: string;
-}
\ No newline at end of file
diff --git a/client/src/components/parameterPanel/index.ts b/client/src/components/parameterPanel/index.ts
deleted file mode 100644
index 52943e1e..00000000
--- a/client/src/components/parameterPanel/index.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-// Modular Parameter Panel Components
-export { default as InputSection } from './InputSection';
-export { default as MiddleSection } from './MiddleSection';
-export { default as OutputSection } from './OutputSection';
-export { default as MapsSection } from './MapsSection';
-export { default as ParameterPanelLayout } from './ParameterPanelLayout';
-export { default as LocationPanelLayout } from './LocationPanelLayout';
-
-// Types defined inline for convenience
-
-// Export interface definitions
-export interface InputSectionProps {
- nodeId: string;
- visible?: boolean;
-}
-
-export interface MiddleSectionProps {
- nodeDefinition: any;
- parameters: Record<string, any>;
- onParameterChange: (paramName: string, value: any) => void;
-}
-
-export interface OutputSectionProps {
- selectedNode: any;
- executionResults: any[];
- onClearResults: () => void;
- visible?: boolean;
-}
-
-export interface ParameterPanelLayoutProps {
- selectedNode: any;
- nodeDefinition: any;
- parameters: Record<string, any>;
- hasUnsavedChanges: boolean;
- onParameterChange: (paramName: string, value: any) => void;
- onSave: () => void;
- onCancel: () => void;
- executionResults: any[];
- onClearResults: () => void;
- showInputSection?: boolean;
- showOutputSection?: boolean;
-}
\ No newline at end of file
diff --git a/client/src/components/shared/DataPanel.tsx b/client/src/components/shared/DataPanel.tsx
deleted file mode 100644
index 01656782..00000000
--- a/client/src/components/shared/DataPanel.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import React, { ReactNode } from 'react';
-
-// Compound Component Pattern
-interface DataPanelProps {
- children: ReactNode;
-}
-
-interface HeaderProps {
- title: ReactNode;
- extra?: ReactNode;
- children?: ReactNode;
-}
-
-interface ContentProps {
- children: ReactNode;
-}
-
-interface FooterProps {
- children: ReactNode;
-}
-
-interface EmptyStateProps {
- icon: ReactNode;
- title: string;
- description: string;
-}
-
-const DataPanelRoot: React.FC<DataPanelProps> = ({ children }) => (
- <div className="flex h-full w-[350px] flex-col border-l border-border bg-card">
- {children}
- </div>
-);
-
-const DataPanelHeader: React.FC<HeaderProps> = ({ title, extra, children }) => (
- <div className="border-b border-border bg-card">
- <div className="flex items-center justify-between gap-2 p-2 text-sm font-semibold">
- <div>{title}</div>
- {extra && <div>{extra}</div>}
- </div>
- {children && <div className="p-2">{children}</div>}
- </div>
-);
-
-const DataPanelContent: React.FC<ContentProps> = ({ children }) => (
- <div className="flex-1 overflow-y-auto p-2">{children}</div>
-);
-
-const DataPanelFooter: React.FC<FooterProps> = ({ children }) => (
- <div className="border-t border-border bg-card p-2 text-center">
- {children}
- </div>
-);
-
-const DataPanelEmpty: React.FC<EmptyStateProps> = ({ icon, title, description }) => (
- <div className="flex h-full w-[350px] flex-col items-center justify-center border-l border-border bg-card p-6 text-center">
- <div className="mb-3 text-muted-foreground">{icon}</div>
- <div className="text-sm text-muted-foreground">{title}</div>
- <div className="mt-1 text-xs text-muted-foreground">{description}</div>
- </div>
-);
-
-// Compound Component Export
-const DataPanel = {
- Root: DataPanelRoot,
- Header: DataPanelHeader,
- Content: DataPanelContent,
- Footer: DataPanelFooter,
- Empty: DataPanelEmpty
-};
-
-export default DataPanel;
diff --git a/client/src/components/shared/JSONTreeRenderer.tsx b/client/src/components/shared/JSONTreeRenderer.tsx
deleted file mode 100644
index 7aa773e8..00000000
--- a/client/src/components/shared/JSONTreeRenderer.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import React, { useState } from 'react';
-import { ChevronRight, GripVertical } from 'lucide-react';
-import { cn } from '@/lib/utils';
-
-interface JSONTreeProps {
- data: Record<string, any>;
- nodeName: string;
- onDragStart: (e: React.DragEvent, nodeName: string, propertyPath: string, value: any) => void;
- templateName: string;
-}
-
-interface NodeProps {
- entryKey: string;
- value: any;
- path: string;
- nodeName: string;
- templateName: string;
- onDragStart: JSONTreeProps['onDragStart'];
- depth: number;
-}
-
-const TreeNode: React.FC<NodeProps> = ({
- entryKey,
- value,
- path,
- nodeName,
- templateName,
- onDragStart,
- depth,
-}) => {
- const isObject = typeof value === 'object' && value !== null && !Array.isArray(value);
- const isDraggable = !isObject;
- const [open, setOpen] = useState(true);
-
- return (
- <div>
- <div
- draggable={isDraggable}
- onDragStart={(e) => isDraggable && onDragStart(e, nodeName, path, value)}
- style={{ paddingLeft: depth * 12 }}
- className={cn(
- 'mb-1 flex items-start justify-between gap-2 rounded-md border border-info/40 bg-info/5 p-2 transition-colors',
- isDraggable && 'cursor-grab hover:-translate-y-px hover:bg-info/10'
- )}
- >
- <div className="flex min-w-0 flex-1 items-start gap-1">
- {isObject && (
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- className="mt-0.5 text-muted-foreground hover:text-foreground"
- aria-label={open ? 'Collapse' : 'Expand'}
- >
- <ChevronRight className={cn('h-3 w-3 transition-transform', open && 'rotate-90')} />
- </button>
- )}
- <div className="min-w-0 flex-1">
- <code className="block text-[11px] text-accent">
- {`{{${templateName}.${path}}}`}
- </code>
- <div className="mt-0.5 flex items-center gap-1 text-[10px]">
- <span className="font-semibold text-success">"{entryKey}"</span>
- <span className="text-muted-foreground">:</span>
- <span
- className={cn(
- 'truncate',
- isObject
- ? 'text-muted-foreground'
- : typeof value === 'string'
- ? 'text-destructive'
- : 'text-foreground'
- )}
- >
- {isObject ? '{object}' : JSON.stringify(value)}
- </span>
- </div>
- </div>
- </div>
- {isDraggable && <GripVertical className="h-3 w-3 shrink-0 text-accent" />}
- </div>
-
- {isObject && open && (
- <div>
- {Object.entries(value).map(([childKey, childValue]) => (
- <TreeNode
- key={childKey}
- entryKey={childKey}
- value={childValue}
- path={`${path}.${childKey}`}
- nodeName={nodeName}
- templateName={templateName}
- onDragStart={onDragStart}
- depth={depth + 1}
- />
- ))}
- </div>
- )}
- </div>
- );
-};
-
-const JSONTreeRenderer: React.FC<JSONTreeProps> = ({
- data,
- nodeName,
- onDragStart,
- templateName,
-}) => (
- <div className="bg-transparent">
- {Object.entries(data).map(([key, value]) => (
- <TreeNode
- key={key}
- entryKey={key}
- value={value}
- path={key}
- nodeName={nodeName}
- templateName={templateName}
- onDragStart={onDragStart}
- depth={0}
- />
- ))}
- </div>
-);
-
-export default JSONTreeRenderer;
diff --git a/client/src/components/ui/InputNodesPanel.tsx b/client/src/components/ui/InputNodesPanel.tsx
deleted file mode 100644
index 06b60522..00000000
--- a/client/src/components/ui/InputNodesPanel.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Link2, RefreshCw, Copy, Database, Loader2 } from 'lucide-react';
-
-import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
-import { useAppStore } from '../../store/useAppStore';
-import { useWebSocket } from '../../contexts/WebSocketContext';
-import DataPanel from '../shared/DataPanel';
-import { copyToClipboard } from '../../utils/formatters';
-
-interface InputNodesPanelProps {
- nodeId: string;
-}
-
-interface InputDataItem {
- index: number;
- data: any;
- source: string;
-}
-
-const InputNodesPanel: React.FC<InputNodesPanelProps> = ({ nodeId }) => {
- const currentWorkflow = useAppStore((s) => s.currentWorkflow);
- const { getNodeOutput } = useWebSocket();
- const [inputData, setInputData] = useState<InputDataItem[]>([]);
- const [loading, setLoading] = useState(false);
-
- useEffect(() => {
- const fetchInputData = async () => {
- if (!currentWorkflow || !nodeId) {
- setInputData([]);
- return;
- }
-
- setLoading(true);
- const nodes = currentWorkflow.nodes || [];
- const edges = currentWorkflow.edges || [];
- const incomingEdges = edges.filter((edge: any) => edge.target === nodeId);
- const inputItems: InputDataItem[] = [];
-
- for (const edge of incomingEdges) {
- const sourceNode = nodes.find((node: any) => node.id === edge.source);
- const sourceName = sourceNode?.data?.label || sourceNode?.type || 'Unknown';
- const outputData = await getNodeOutput(edge.source, 'output_0');
-
- if (outputData && outputData[0] && outputData[0][0]) {
- const actualData = outputData[0][0].json || outputData[0][0];
- inputItems.push({
- index: inputItems.length,
- data: actualData,
- source: sourceName,
- });
- }
- }
-
- setInputData(inputItems);
- setLoading(false);
- };
-
- fetchInputData();
- }, [nodeId, currentWorkflow, getNodeOutput]);
-
- const hasExecutionData = inputData.length > 0;
-
- if (loading) {
- return (
- <DataPanel.Empty
- icon={<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />}
- title="Loading input data..."
- description="Fetching execution data from backend"
- />
- );
- }
-
- if (!hasExecutionData) {
- return (
- <DataPanel.Empty
- icon={<Database className="h-12 w-12 text-muted-foreground" />}
- title="No input data"
- description="Execute connected nodes to see the input data received by this node"
- />
- );
- }
-
- return (
- <DataPanel.Root>
- <DataPanel.Header
- title={
- <div className="flex items-center gap-2">
- <Link2 className="h-4 w-4" />
- <span className="text-sm font-semibold">
- Input Data ({inputData.length} item{inputData.length !== 1 ? 's' : ''})
- </span>
- </div>
- }
- extra={
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- setInputData([]);
- setLoading(true);
- }}
- title="Refresh input data from backend"
- >
- <RefreshCw className="h-4 w-4" />
- Refresh
- </Button>
- }
- />
-
- <DataPanel.Content>
- <div className="flex flex-col gap-2">
- {inputData.map((inputItem) => (
- <div
- key={inputItem.index}
- className="rounded-md border border-border border-l-4 border-l-success bg-card p-3"
- >
- <div className="mb-3 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Database className="h-4 w-4 text-success" />
- <span className="text-sm font-semibold">Item {inputItem.index + 1}</span>
- <Badge variant="success">from {inputItem.source}</Badge>
- </div>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => copyToClipboard(inputItem.data, 'Input data copied to clipboard!')}
- title="Copy input data"
- >
- <Copy className="h-4 w-4" />
- Copy
- </Button>
- </div>
-
- <div className="overflow-hidden rounded-md border border-border">
- <div className="border-b border-border bg-muted px-3 py-1.5 text-xs font-semibold">
- Received Data
- </div>
- <pre className="m-0 max-h-[300px] overflow-auto whitespace-pre-wrap break-words bg-muted/40 p-3 font-mono text-xs leading-[1.4]">
- {JSON.stringify(inputItem.data, null, 2)}
- </pre>
- </div>
- </div>
- ))}
- </div>
- </DataPanel.Content>
-
- <DataPanel.Footer>
- <span className="text-[11px] text-muted-foreground">
- Shows actual data received by this node during execution
- </span>
- </DataPanel.Footer>
- </DataPanel.Root>
- );
-};
-
-export default InputNodesPanel;
diff --git a/client/src/hooks/useAndroidOperations.ts b/client/src/hooks/useAndroidOperations.ts
deleted file mode 100644
index c69541b0..00000000
--- a/client/src/hooks/useAndroidOperations.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * useAndroidOperations Hook - WebSocket-based Android device operations
- *
- * Provides Android device management and service execution via WebSocket.
- * This replaces REST-based Android API calls for real-time operations.
- */
-
-import { useCallback, useState } from 'react';
-import { useWebSocket } from '../contexts/WebSocketContext';
-
-export interface AndroidDevice {
- id: string;
- model?: string;
- state?: string;
-}
-
-export interface AndroidActionResult {
- success: boolean;
- result?: any;
- error?: string;
-}
-
-export interface UseAndroidOperationsResult {
- // Get list of connected devices
- getDevices: () => Promise<AndroidDevice[]>;
-
- // Execute Android service action
- executeAction: (
- serviceId: string,
- action: string,
- parameters: Record<string, any>,
- deviceId?: string
- ) => Promise<AndroidActionResult>;
-
- // State
- isExecuting: boolean;
- lastError: string | null;
- isConnected: boolean;
-
- // Android status from WebSocket
- androidStatus: {
- connected: boolean;
- device_id: string | null;
- connected_devices: string[];
- connection_type: string | null;
- };
-}
-
-export const useAndroidOperations = (): UseAndroidOperationsResult => {
- const {
- getAndroidDevices: wsGetDevices,
- executeAndroidAction: wsExecuteAction,
- androidStatus,
- isConnected
- } = useWebSocket();
-
- const [isExecuting, setIsExecuting] = useState(false);
- const [lastError, setLastError] = useState<string | null>(null);
-
- /**
- * Get list of connected Android devices
- */
- const getDevices = useCallback(async (): Promise<AndroidDevice[]> => {
- try {
- const devices = await wsGetDevices();
- return devices.map((id: string) => ({ id }));
- } catch (error: any) {
- console.warn('Failed to get Android devices:', error);
- setLastError(error.message);
- return [];
- }
- }, [wsGetDevices]);
-
- /**
- * Execute Android service action
- */
- const executeAction = useCallback(async (
- serviceId: string,
- action: string,
- parameters: Record<string, any>,
- deviceId?: string
- ): Promise<AndroidActionResult> => {
- setIsExecuting(true);
- setLastError(null);
-
- try {
- const result = await wsExecuteAction(serviceId, action, parameters, deviceId);
-
- if (!result.success) {
- setLastError(result.error || 'Action failed');
- }
-
- return {
- success: result.success,
- result: result.result,
- error: result.error
- };
- } catch (error: any) {
- const errorMsg = error.message || 'Action execution failed';
- setLastError(errorMsg);
- return {
- success: false,
- error: errorMsg
- };
- } finally {
- setIsExecuting(false);
- }
- }, [wsExecuteAction]);
-
- return {
- getDevices,
- executeAction,
- isExecuting,
- lastError,
- isConnected,
- androidStatus
- };
-};
diff --git a/client/src/hooks/usePricing.ts b/client/src/hooks/usePricing.ts
deleted file mode 100644
index 43c2c8fd..00000000
--- a/client/src/hooks/usePricing.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Hook for managing pricing configuration and API usage data.
- * Provides access to pricing config (LLM and API pricing) and usage summaries.
- */
-
-import { useCallback } from 'react';
-import { useWebSocket } from '../contexts/WebSocketContext';
-
-// ============================================================================
-// Types
-// ============================================================================
-
-export interface LLMPricing {
- input: number;
- output: number;
- cache_read?: number;
- reasoning?: number;
-}
-
-export interface APIPricing {
- [operation: string]: number;
-}
-
-export interface PricingConfig {
- version: string;
- last_updated: string;
- llm: Record<string, Record<string, LLMPricing>>;
- api: Record<string, APIPricing>;
- operation_map: Record<string, Record<string, string>>;
-}
-
-export interface APIOperationSummary {
- operation: string;
- resource_count: number;
- total_cost: number;
- execution_count: number;
-}
-
-export interface APIUsageSummary {
- service: string;
- total_resources: number;
- total_cost: number;
- execution_count: number;
- operations: APIOperationSummary[];
-}
-
-// ============================================================================
-// Hook
-// ============================================================================
-
-export const usePricing = () => {
- const { sendRequest, isConnected } = useWebSocket();
-
- /**
- * Get the full pricing configuration (LLM + API pricing).
- * Returns null if not connected or request fails.
- */
- const getPricingConfig = useCallback(async (): Promise<PricingConfig | null> => {
- if (!isConnected) return null;
-
- try {
- const response = await sendRequest<{ success: boolean; config: PricingConfig }>(
- 'get_pricing_config',
- {}
- );
- return response?.config || null;
- } catch (error) {
- console.error('[usePricing] Failed to get pricing config:', error);
- return null;
- }
- }, [sendRequest, isConnected]);
-
- /**
- * Save updated pricing configuration.
- * Returns true if saved successfully.
- */
- const savePricingConfig = useCallback(async (config: PricingConfig): Promise<boolean> => {
- if (!isConnected) return false;
-
- try {
- const response = await sendRequest<{ success: boolean }>(
- 'save_pricing_config',
- { config }
- );
- return response?.success || false;
- } catch (error) {
- console.error('[usePricing] Failed to save pricing config:', error);
- return false;
- }
- }, [sendRequest, isConnected]);
-
- /**
- * Get aggregated API usage summary.
- * Optionally filter by service (e.g., 'twitter').
- */
- const getAPIUsageSummary = useCallback(async (
- service?: string
- ): Promise<APIUsageSummary[]> => {
- if (!isConnected) return [];
-
- try {
- const response = await sendRequest<{ success: boolean; services: APIUsageSummary[] }>(
- 'get_api_usage_summary',
- { service }
- );
- return response?.services || [];
- } catch (error) {
- console.error('[usePricing] Failed to get API usage summary:', error);
- return [];
- }
- }, [sendRequest, isConnected]);
-
- /**
- * Get Twitter-specific usage summary.
- * Convenience method that calls getAPIUsageSummary with 'twitter' filter.
- */
- const getTwitterUsage = useCallback(async (): Promise<APIUsageSummary | null> => {
- const services = await getAPIUsageSummary('twitter');
- return services.find(s => s.service === 'twitter') || null;
- }, [getAPIUsageSummary]);
-
- return {
- // Config methods
- getPricingConfig,
- savePricingConfig,
- // Usage methods
- getAPIUsageSummary,
- getTwitterUsage,
- // State
- isConnected,
- };
-};
-
-export default usePricing;
diff --git a/client/src/hooks/useToolSchema.ts b/client/src/hooks/useToolSchema.ts
deleted file mode 100644
index 1cd6645b..00000000
--- a/client/src/hooks/useToolSchema.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-/**
- * useToolSchema Hook - WebSocket-based tool schema management
- *
- * Provides tool schema operations for Android Toolkit and other tool nodes.
- * The database-stored schema is the source of truth for LLM tool configurations.
- */
-
-import { useCallback, useState } from 'react';
-import { useWebSocket } from '../contexts/WebSocketContext';
-
-/**
- * Schema field configuration for tool arguments
- */
-export interface SchemaFieldConfig {
- type: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array';
- description: string;
- required?: boolean;
- default?: any;
- enum?: string[];
-}
-
-/**
- * Full schema configuration stored in database
- */
-export interface ToolSchemaConfig {
- description: string;
- fields: Record<string, SchemaFieldConfig>;
-}
-
-/**
- * Tool schema as stored in database
- */
-export interface ToolSchema {
- node_id: string;
- tool_name: string;
- tool_description: string;
- schema_config: ToolSchemaConfig;
- connected_services?: Record<string, any>[];
- created_at?: string;
- updated_at?: string;
-}
-
-export interface UseToolSchemaResult {
- // Get tool schema for a node
- getToolSchema: (nodeId: string) => Promise<ToolSchema | null>;
-
- // Save tool schema for a node
- saveToolSchema: (
- nodeId: string,
- toolName: string,
- toolDescription: string,
- schemaConfig: ToolSchemaConfig,
- connectedServices?: Record<string, any>[]
- ) => Promise<boolean>;
-
- // Delete tool schema for a node
- deleteToolSchema: (nodeId: string) => Promise<boolean>;
-
- // Get all tool schemas
- getAllToolSchemas: () => Promise<ToolSchema[]>;
-
- // State
- isLoading: boolean;
- error: string | null;
- isConnected: boolean;
-}
-
-export const useToolSchema = (): UseToolSchemaResult => {
- const { sendRequest, isConnected } = useWebSocket();
-
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- /**
- * Get tool schema for a node from database
- */
- const getToolSchema = useCallback(async (nodeId: string): Promise<ToolSchema | null> => {
- if (!isConnected) {
- console.warn('[useToolSchema] WebSocket not connected');
- return null;
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await sendRequest<{ success: boolean; schema: ToolSchema | null }>('get_tool_schema', {
- node_id: nodeId
- });
-
- if (response.success) {
- return response.schema;
- }
- return null;
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : 'Failed to get tool schema';
- setError(errorMsg);
- console.error('[useToolSchema] Error getting schema:', errorMsg);
- return null;
- } finally {
- setIsLoading(false);
- }
- }, [isConnected, sendRequest]);
-
- /**
- * Save tool schema for a node to database
- */
- const saveToolSchema = useCallback(async (
- nodeId: string,
- toolName: string,
- toolDescription: string,
- schemaConfig: ToolSchemaConfig,
- connectedServices?: Record<string, any>[]
- ): Promise<boolean> => {
- if (!isConnected) {
- console.warn('[useToolSchema] WebSocket not connected');
- return false;
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await sendRequest<{ success: boolean; saved: boolean }>('save_tool_schema', {
- node_id: nodeId,
- tool_name: toolName,
- tool_description: toolDescription,
- schema_config: schemaConfig,
- connected_services: connectedServices
- });
-
- return response.success && response.saved;
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : 'Failed to save tool schema';
- setError(errorMsg);
- console.error('[useToolSchema] Error saving schema:', errorMsg);
- return false;
- } finally {
- setIsLoading(false);
- }
- }, [isConnected, sendRequest]);
-
- /**
- * Delete tool schema for a node from database
- */
- const deleteToolSchema = useCallback(async (nodeId: string): Promise<boolean> => {
- if (!isConnected) {
- console.warn('[useToolSchema] WebSocket not connected');
- return false;
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await sendRequest<{ success: boolean }>('delete_tool_schema', {
- node_id: nodeId
- });
-
- return response.success;
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : 'Failed to delete tool schema';
- setError(errorMsg);
- console.error('[useToolSchema] Error deleting schema:', errorMsg);
- return false;
- } finally {
- setIsLoading(false);
- }
- }, [isConnected, sendRequest]);
-
- /**
- * Get all tool schemas from database
- */
- const getAllToolSchemas = useCallback(async (): Promise<ToolSchema[]> => {
- if (!isConnected) {
- console.warn('[useToolSchema] WebSocket not connected');
- return [];
- }
-
- setIsLoading(true);
- setError(null);
-
- try {
- const response = await sendRequest<{ success: boolean; schemas: ToolSchema[] }>('get_all_tool_schemas', {});
-
- if (response.success) {
- return response.schemas || [];
- }
- return [];
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : 'Failed to get tool schemas';
- setError(errorMsg);
- console.error('[useToolSchema] Error getting schemas:', errorMsg);
- return [];
- } finally {
- setIsLoading(false);
- }
- }, [isConnected, sendRequest]);
-
- return {
- getToolSchema,
- saveToolSchema,
- deleteToolSchema,
- getAllToolSchemas,
- isLoading,
- error,
- isConnected
- };
-};
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index dd7bf6c0..bfb484f4 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -120,7 +120,6 @@ client/src/
│ ├── ui/
│ │ ├── ApiKeyInput.tsx # Composite: input + eye toggle + save/delete buttons
│ │ ├── SettingsPanel.tsx # Shadcn Switch + Slider + Input
-│ │ ├── PricingConfigModal.tsx # (client/src/components/PricingConfigModal.tsx)
│ │ ├── ConsolePanel.tsx # Chat + console + terminal + output
│ │ ├── Modal.tsx # Shadcn Dialog wrapper
│ │ ├── NodeOutputPanel.tsx # Deleted (superseded by output/OutputPanel)
@@ -128,8 +127,6 @@ client/src/
│ │
│ ├── icons/ # AI provider icons (SVG data URIs)
│ ├── auth/ # Login page + protected route
-│ ├── shared/
-│ │ └── JSONTreeRenderer.tsx # Recursive JSON tree (no styled-components)
│ ├── SquareNode.tsx, StartNode.tsx, TriggerNode.tsx, GenericNode.tsx, AIAgentNode.tsx, WhatsAppNode.tsx, ModelNode.tsx
│ │ # React Flow nodes with lucide icons
│ └── APIKeyValidator.tsx # Shadcn Input + Button + Tooltip composition
@@ -150,7 +147,7 @@ client/src/
│ ├── useComponentPalette.ts / useDragAndDrop.ts / useDragWorkspaceFile.ts
│ ├── useOnboarding.ts # Reads via useUserSettingsQuery; writes via mutation
│ ├── useParameterPanel.ts # Thin orchestrator over useNodeParamsQuery + save mutation
-│ ├── usePricing.ts / useToolSchema.ts / useWhatsApp.ts / useAndroidOperations.ts
+│ ├── useWhatsApp.ts # WS-based WhatsApp ops (Android ops go via useWebSocket directly)
│ └── useCopyPaste.ts / useRename.ts
│
├── store/
@@ -477,7 +474,7 @@ This is the rule that keeps the data layer schema-driven instead of imperatively
| **`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`).
+- **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`, `ParameterPanel`).
- 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).
diff --git a/docs-internal/pricing_service.md b/docs-internal/pricing_service.md
index 117803ef..75ab42aa 100644
--- a/docs-internal/pricing_service.md
+++ b/docs-internal/pricing_service.md
@@ -411,20 +411,25 @@ summary = await db.get_api_usage_summary(service='twitter')
## Frontend Display
-The CredentialsModal displays usage statistics via `renderApiUsagePanel()`:
+The credentials modal displays usage statistics through two section components, both wired via
+`credentials/useCredentialPanel.ts`:
```typescript
-// client/src/components/CredentialsModal.tsx
+// client/src/components/credentials/sections/ApiUsageSection.tsx -> per-service API cost
+// client/src/components/credentials/sections/LlmUsageSection.tsx -> per-provider token cost
-// Fetch usage data
-const { getApiUsage, apiUsage, apiUsageLoading } = usePricing();
-await getApiUsage('twitter');
-
-// Render panel
-{renderApiUsagePanel('twitter', 'Twitter')}
-{renderApiUsagePanel('google_maps', 'Google Maps')}
+const { getAPIUsageSummary, getProviderUsageSummary } = useApiKeys();
```
+**Both render precomputed costs, never the pricing config.** `get_api_usage_summary` is a
+`SUM(APIUsageMetric.cost)` GROUP BY, and the `cost` column was calculated at write time by
+`PricingService`. Nothing on the client reads or writes `pricing.json`.
+
+There is no UI for editing pricing. `PricingConfigModal` + `usePricing` existed but were never
+mounted anywhere and were deleted; the `get_pricing_config` / `save_pricing_config` WS handlers
+remain registered with no client caller. Editing `pricing.json` means editing the file. (The third
+handler in that module, `get_api_usage_summary`, IS live — `useApiKeys` calls it.)
+
### Display Format
- Collapsible panel with service icon and total cost tag
@@ -499,12 +504,10 @@ Alternatively, for a service billed per operation, skip the helper entirely and
}
```
-### 4. Add Frontend Display
+### 4. Frontend Display
-```typescript
-// In CredentialsModal.tsx, in the relevant panel:
-{renderApiUsagePanel('new_service', 'New Service')}
-```
+Nothing to add. `ApiUsageSection` renders whatever services come back from
+`get_api_usage_summary`, so a new service appears as soon as it records its first metric.
## Key Files
@@ -521,5 +524,6 @@ Alternatively, for a service billed per operation, skip the helper entirely and
| `server/services/plugin/operation.py` | `@Operation` decorator + `OperationSpec.cost` metadata |
| `server/models/database.py` | `APIUsageMetric`, `TokenUsageMetric` models |
| `server/core/database.py` | `save_api_usage_metric()`, `get_api_usage_summary()` |
-| `client/src/components/CredentialsModal.tsx` | `renderApiUsagePanel()` UI component |
-| `client/src/hooks/usePricing.ts` | Frontend hook for pricing/usage data |
+| `client/src/components/credentials/sections/ApiUsageSection.tsx` | Per-service API usage + cost display |
+| `client/src/components/credentials/sections/LlmUsageSection.tsx` | Per-provider token usage + cost display |
+| `client/src/hooks/useApiKeys.ts` | `getAPIUsageSummary` / `getProviderUsageSummary` |
diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.md
index c77404f9..1d93bf40 100644
--- a/docs-internal/ui_migration_plan.md
+++ b/docs-internal/ui_migration_plan.md
@@ -73,7 +73,8 @@ A second, deeper audit (4 parallel sub-agents — panel audit, library survey, N
- Phase 6 — `ParameterRenderer` → DIY widget registry. Backend `get_node_spec` handler is the prerequisite. Frontend layout decided (4 files in `inspector/`); rollout shape decided (5 weekly slices behind `VITE_USE_NODESPEC` with parity test against legacy renderer).
- Bulk Tailwind sweep of `GenericNode` / `BaseChatModelNode` inline `theme.dracula.*` refs. Visual-regression-prone; needs in-browser verification per file.
- ESLint rule + bundle-budget CI assertion (Phase 7 leftovers). Both touch CI config, deferred together.
-- `MasterSkillEditor` RHF migration. The editor is a split-panel UI (skill list + content editor + folder dropdown + inline create/edit) — not the >3-field-form pattern Phase 4 targeted. The form-with-validation parts already moved to `SkillEditorModal`; the registry-style list view is genuinely different work.
+- `MasterSkillEditor` RHF migration. The editor is a split-panel UI (skill list + content editor + folder dropdown + inline create/edit) — not the >3-field-form pattern Phase 4 targeted, so the registry-style list view is genuinely different work.
+ **Corrected 2026-08:** this item used to claim "the form-with-validation parts already moved to `SkillEditorModal`". That move never landed in the render tree. `SkillEditorModal` was never imported by anything, at any point — it was a parallel implementation of the same `create_user_skill` / `update_user_skill` commands that `MasterSkillEditor` still drives from its own inline form. It was carried through four migration waves as dead weight and has now been deleted. `MasterSkillEditor` still owns 100% of skill editing, form parts included.
## Wave 3 — backend as schema source of truth (April 2026)
@@ -333,6 +334,45 @@ Driven by the upstream `design_handoff_machinaos_themes/` bundle expanding from
- **Per-component decorative class hooks** beyond `app-frame` / `canvas-host` / `modal-frame` — `.sq-node`, `.cat`, `.cmdk`, `.menu-pop` add finer-grained per-theme decorations. Each is a one-line className edit; ship as themes ship.
- **Deeper Parameter Panel + Credentials sub-panel header migration** — body copy + form labels retint via the bridge but interior section headers (`MiddleSection` group labels, `MasterSkillEditor` split-panel heads, `ApiKeyPanel` / `OAuthPanel` / `EmailPanel` / `QrPairingPanel` section titles) don't yet carry the display-typography triplet. Apply the recipe (`font-display tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]`) when those files are next touched.
+## Wave 15 — frontend thinning: dead code + execution logic out of the client (August 2026)
+
+Premise: "the backend is the execution engine; the frontend is just a UI." The client was violating
+that by keeping its own copies of backend-owned facts, and the copies had gone stale enough to cause
+user-visible bugs.
+
+| Batch | What it delivers | Where |
+|---|---|---|
+| 1 — deploy gate | The "no trigger node found" check read a hardcoded 11-string array containing one type the backend registry does not define (`workflowTrigger`) and missing `stripeReceive` — so a Stripe-webhook-only workflow could not be deployed. Now reads `componentKind === 'trigger'` off the raw spec via the pre-existing `getNodeTypesWithKind()`. | `Dashboard.tsx`, `lib/nodeSpec.ts` |
+| 2 — execution budget | `BaseNode.start_to_close_timeout` is now serialized as `uiHints.executionTimeoutMs`, replacing two stale client arrays (5 of 10 triggers, 16 of 21 agents) that produced a phantom 30 s `Request timeout` on 8 node types. Rides `uiHints` because `services/node_spec.py` is a hard key whitelist. Fallback is the finite 5 min `WORKFLOW_CONTROL_REQUEST_TIMEOUT`, never "no timeout" — an unsettleable promise hangs the Run spinner with no error. Fixed `cronScheduler`, which declared 10 min while sleeping up to a month. | `services/plugin/base.py`, `WebSocketContext.tsx`, `INodeProperties.ts`, `nodes/scheduler/cron_scheduler/` |
+| 3 — dead modules (484 lines) | `popover.tsx`, `utils/nodeUtils.ts` (hardcoded the client-side node registry Wave 11 deleted), `DropCap.tsx` (its `::first-letter` rule exists in no theme), `styles/zIndex.ts`, `hooks/useExecution.ts` (dead frontend *execution* logic — the live path is `ExecutionService.executeNodeViaWebSocket`). Plus the `nodeOutput` drop branch with no producer, and the `googleChatModel` provider alias that `useAppStore` already migrates away. | client + 4 doc sites |
+| 4 — orphan sweep (1,663 lines) | `SkillEditorModal`, `JSONTreeRenderer`, `DataPanel`, `InputNodesPanel`, `PricingConfigModal`, `usePricing`, `useAndroidOperations`, `useToolSchema`, and the two unreferenced barrels (`parameterPanel/index.ts`, `maps/index.ts`). Verified by knip program-graph closure, not regex. | client + 3 doc sites |
+| 5 — guards | pytest + `inspect.getsource`, repo idiom. No client file may carry a backend node-type literal in an array/comparison context; every registered node must serialize `executionTimeoutMs`; every `TriggerNode` must report ≥ 1 h. Includes a debt ledger that can only shrink. Adversarially verified to fail on a probe — a guard never seen failing is not a guard. | `server/tests/test_frontend_no_node_type_copies.py` |
+
+**Wave 15 numbers:**
+- 2,147 lines of client code deleted across two sweeps.
+- 2 stale node-type arrays retired; 1 backend field (`executionTimeoutMs`) added to carry the truth.
+- knip closure after the sweep: 2 remaining orphans, both deliberate (`ui/tabs.tsx`, needed by
+ in-flight work; `credentials/schema/extends.ts`, retained on its documented rationale).
+- 389 client tests, typecheck, lint, and `vite build` green.
+
+**Findings worth keeping (each corrected a doc that was wrong):**
+- `SkillEditorModal` was never imported by anything. This plan previously recorded it as the place
+ MasterSkillEditor's "form-with-validation parts already moved" — that move never landed. See the
+ correction under Wave 2's deferred list.
+- `PricingConfigModal` has no entry point and no severed one to restore. `pricing.json` stays
+ load-bearing at execution time via the `PricingService` singleton; the UI was never in that path.
+- **The `tool_schemas` write path is dead while the read path is live.** `services/ai.py` reads the
+ table during tool construction to override the LLM-visible tool name/description/schema, but no
+ reachable code can write it. Deleting `useToolSchema` did not cause this and does not fix it — see
+ CLAUDE.md's Tool Schemas section.
+- `useAndroidOperations` was a wrapper over context methods that every live Android surface already
+ bypassed, documenting a signature (`setupDevice`, `deviceStatus`) the file did not export.
+
+**Deliberately not deleted:** `credentials/schema/extends.ts` — unreferenced, but its docstring names
+planned consumers and it mirrors `credential_registry._deep_merge`. Two divergences from that mirror
+were found and are worth fixing if it is ever adopted: TS adds a `statusRows` alias the Python set
+lacks, and Python treats any `key` as keyed while TS requires `typeof key === 'string'`.
+
## Context
The OpenCompany 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`).
@@ -505,7 +545,7 @@ Dependency order: 0 → {1, 2, 3} parallelizable → 4 → 5 → 7; 6 can overla
**Goal:** delete the old stack. Bundle shrinks ~200-400 KB gzipped.
- Verify zero `from 'antd'` imports remain.
-- Migrate [client/src/components/shared/JSONTreeRenderer.tsx](../client/src/components/shared/JSONTreeRenderer.tsx) — rewrite styled-components as Tailwind classes.
+- ~~Migrate `client/src/components/shared/JSONTreeRenderer.tsx` — rewrite styled-components as Tailwind classes.~~ Moot: it was migrated off styled-components, then found to have zero importers (the live JSON viewer is `@uiw/react-json-view` inside `output/OutputPanel.tsx`) and deleted 2026-08.
- Delete: `client/src/config/antdTheme.ts` (deleted in Phase 7); `ConfigProvider` wrapper in [client/src/App.tsx](../client/src/App.tsx); antd reset CSS import in `main.tsx`. Inline remaining [client/src/styles/theme.ts](../client/src/styles/theme.ts) usages against CSS vars then delete.
- Remove from [client/package.json](../client/package.json): `antd`, `@ant-design/icons`, `styled-components`, `@types/styled-components`.
- Broaden React Compiler scope to whole `src/`.
@@ -538,7 +578,7 @@ No test runner. Before Phase 5, decide:
- [client/src/components/credentials/](../client/src/components/credentials/) — exemplar for Phase 5 and 6
- [client/src/components/output/OutputPanel.tsx](../client/src/components/output/OutputPanel.tsx) — `_uiHints` wiring in Phase 6
- [client/src/components/ui/Modal.tsx](../client/src/components/ui/Modal.tsx) — replaced by shadcn `Dialog` in Phase 3
-- [client/src/components/shared/JSONTreeRenderer.tsx](../client/src/components/shared/JSONTreeRenderer.tsx) — last styled-components site
+- ~~`client/src/components/shared/JSONTreeRenderer.tsx` — last styled-components site~~ (deleted 2026-08, unreferenced)
### Rollout / rollback
Each phase behind no flag except Phase 6 (`VITE_USE_NODESPEC`). Rollback = single-PR revert; antd coexists with new stack until Phase 7.