Skip to content

Self-improving AI Employees for everyone

18.8 KB
Raw Blame
import React, { memo, useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { nodePropsEqual } from './nodeMemoEquality';
import { Handle, Position, NodeProps } from 'reactflow';
import { NodeData, NodeStyle } from '../types/NodeTypes';
import { useAppStore } from '../store/useAppStore';
import { useAppTheme } from '../hooks/useAppTheme';
import EditableNodeLabel from './ui/EditableNodeLabel';
import { useWebSocket, useWhatsAppStatus, useNodeStatus } from '../contexts/WebSocketContext';
import { isNodeInBackendGroup, resolveNodeDescription, useNodeSpec } from '../lib/nodeSpec';
import { NodeIcon } from '../assets/icons';
import { AI_MODEL_PROVIDER_MAP } from '../lib/aiModelProviders';
import { credentialProviderId } from '../lib/credentialProviderId';
import { useProviderStored } from '../hooks/useCatalogueQuery';
import type { NodeSpecHandle } from '../adapters/nodeSpecToDescription';

// Nodes with 'tool' in their group can connect to AI Agent/Zeenie tool handles
const hasToolGroup = (definition: any): boolean => {
  const groups = definition?.group || [];
  return groups.includes('tool');
};

// Wave 10.E: AI model dispatch + provider-id-by-type still need a
// frontend lookup because the per-provider visual mapping
// (icon component, credential key) lives in the icon registry below.
// The map of node types itself comes from the backend NodeSpec registry.
const AI_MODEL_NODE_TYPES = AI_MODEL_PROVIDER_MAP;

const REACT_POSITION: Record<NodeSpecHandle['position'], Position> = {
  top: Position.Top,
  bottom: Position.Bottom,
  left: Position.Left,
  right: Position.Right,
};

const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
  const theme = useAppTheme();
  // Slice selectors so an unrelated store mutation (sidebar toggle,
  // workflow rename, parameter save on another node) does NOT re-render
  // every canvas node. Setters are stable refs — single-field selector
  // is the cheapest read.
  const setSelectedNode = useAppStore((s) => s.setSelectedNode);
  const setRenamingNodeId = useAppStore((s) => s.setRenamingNodeId);
  const updateNodeData = useAppStore((s) => s.updateNodeData);
  const isDisabled = data?.disabled === true;

  // Get Android status + API key status from the broad WebSocket
  // context, but subscribe to node status via the per-id slice selector
  // so an unrelated node's status update does NOT re-render this node.
  // Reference: zustand slice subscription pattern, see
  // https://github.com/pmndrs/zustand#selecting-multiple-state-slices
  const { androidStatus, getApiKeyStatus } = useWebSocket();
  const nodeStatus = useNodeStatus(id);
  const executionStatus = nodeStatus?.status || 'idle';

  // Minimum glow duration state - keeps glow visible for at least 500ms
  const [isGlowing, setIsGlowing] = useState(false);
  const glowTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // Track when execution starts to ensure minimum glow duration
  useEffect(() => {
    if (executionStatus === 'executing' || executionStatus === 'waiting') {
      // Start glowing immediately
      setIsGlowing(true);
      // Clear any existing timeout that would stop the glow
      if (glowTimeoutRef.current) {
        clearTimeout(glowTimeoutRef.current);
        glowTimeoutRef.current = null;
      }
    } else if (isGlowing) {
      // Execution ended but we're still glowing - set timeout to stop after minimum duration
      if (!glowTimeoutRef.current) {
        glowTimeoutRef.current = setTimeout(() => {
          setIsGlowing(false);
          glowTimeoutRef.current = null;
        }, 500);
      }
    }

    return () => {
      if (glowTimeoutRef.current) {
        clearTimeout(glowTimeoutRef.current);
        glowTimeoutRef.current = null;
      }
    };
  }, [executionStatus, isGlowing]);

  // Wave 10.E: backend NodeSpec group membership, with a definition.group
  // fallback for the brief window before the cache warms. No more local
  // type arrays; isNodeInBackendGroup returns undefined when the cache
  // is cold, in which case we read the bundled definition's group list.
  const groupOf = (t: string | undefined): string[] => (t ? (resolveNodeDescription(t)?.group ?? []) : []);
  const inGroup = (t: string | undefined, g: string): boolean =>
    isNodeInBackendGroup(t, g) ?? groupOf(t).includes(g);
  const isGoogleMapsNode = inGroup(type, 'location');
  const googleMapsKeyStatus = isGoogleMapsNode ? getApiKeyStatus('google_maps') : undefined;

  // Check if this is an AI model node and get reactive API key status
  const isAIModelNode = type ? type in AI_MODEL_NODE_TYPES : false;
  const aiProviderId = type && AI_MODEL_NODE_TYPES[type] ? AI_MODEL_NODE_TYPES[type] : null;
  const aiKeyStatus = aiProviderId ? getApiKeyStatus(aiProviderId) : undefined;

  // Wave 6 Phase 3e: backend NodeSpec -> legacy fallback. Flag off or
  // cache cold -> returns local nodeDefinitions entry unchanged.
  const definition = resolveNodeDescription(type || '');
  const spec = useNodeSpec(type);

  // Wave 10.E: backend group membership with bundled-definition fallback
  const isAndroidNode = inGroup(type, 'android');

  // Check if this node can be used as a tool: any Android service node
  // can connect to Android Toolkit, plus any node carrying the 'tool' group.
  const isToolCapable = isAndroidNode || hasToolGroup(definition);
  const renderedHandles = useMemo<NodeSpecHandle[]>(() => {
    if (spec?.handles?.length) return spec.handles;

    // Cold-cache / legacy fallback. Once a NodeSpec arrives its declared
    // topology replaces this list wholesale, including Context handles.
    const fallback: NodeSpecHandle[] = [];
    if (!spec?.hideInputHandle) {
      fallback.push({
        name: 'input-main',
        kind: 'input',
        position: 'left',
        offset: '50%',
        label: 'Service Input',
        role: 'main',
      });
    }
    if (!spec?.hideOutputHandle) {
      fallback.push({
        name: 'output-main',
        kind: 'output',
        position: 'right',
        offset: '50%',
        label: 'Service Output',
        role: 'main',
      });
    }
    if (isToolCapable) {
      fallback.push({
        name: 'output-tool',
        kind: 'output',
        position: 'top',
        offset: '50%',
        label: 'Tool Output',
        role: 'tools',
      });
    }
    return fallback;
  }, [
    spec?.handles,
    spec?.hideInputHandle,
    spec?.hideOutputHandle,
    isToolCapable,
  ]);

  // Android connection status from WebSocket (real-time updates)
  // Service nodes need a paired device to execute, not just relay connection
  const isAndroidConnected = isAndroidNode && androidStatus.paired;

  const isWhatsAppNode = inGroup(type, 'whatsapp');

  // WhatsApp connection status from WebSocket (real-time updates)
  const whatsappStatus = useWhatsAppStatus();

  // Execution state - waiting is treated identically to executing
  // Also respect minimum glow duration for fast-executing tools
  const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting' || isGlowing;


  const defaultLabel = definition?.displayName || type || '';
  // useAppStore.updateNodeData performs `{ ...node.data, ...newData }`
  // so we only need to pass the changed field. Dropping `data` from deps
  // keeps the callback ref stable across parent re-renders, which lets
  // the React.memo wrapper actually short-circuit.
  const handleLabelChange = useCallback(
    (newLabel: string) => updateNodeData(id, { label: newLabel }),
    [id, updateNodeData]
  );
  const handleLabelActivate = useCallback(
    () => setRenamingNodeId(id),
    [id, setRenamingNodeId]
  );

  // Catalogue provider of the node's first declared credential: the
  // plugin credential id itself, or a mapped legacy name. Its `stored`
  // flag is `hasApiKey` below; AI model nodes add the validation state
  // from `aiProviderId`, Google Maps from `googleMapsKeyStatus`.
  const providerId = useMemo<string>(
    () => credentialProviderId(definition?.credentials?.[0]?.name, type),
    [definition?.credentials, type],
  );

  // "Is a credential configured for this provider?" reads from the
  // server-driven catalogue (single source of truth — the `stored`
  // flag is computed from `auth_service.has_valid_key()` on every
  // catalogue read). The retired `apiKeyStatuses[id].hasKey` mirror
  // duplicated this answer with no synchronisation contract.
  const hasApiKey = useProviderStored(providerId);
  const isConfigured = hasApiKey && !!data && Object.keys(data).length > 0;

  const handleParametersClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });
  };

  // Bucket execution + connection state into one of five status tokens
  // consumed by `.sq-node-pip[data-status="..."]` in base.css. Per-theme
  // CSS overrides these without fighting inline `backgroundColor`.
  // Buckets: 'idle' | 'executing' | 'waiting' | 'success' | 'error'.
  // Matches the TriggerNode/StartNode contract (Wave 26.B).
  const pipStatus: 'idle' | 'executing' | 'waiting' | 'success' | 'error' = (() => {
    if (executionStatus === 'executing' || executionStatus === 'waiting' || isGlowing) {
      return 'executing';
    }
    if (executionStatus === 'success') return 'success';
    if (executionStatus === 'error') return 'error';

    // Idle bucket — derive from connection / configuration signals.
    if (isAndroidNode) {
      return isAndroidConnected ? 'success' : 'error';
    }
    if (isWhatsAppNode) {
      if (whatsappStatus.connected) return 'success';
      if (whatsappStatus.pairing) return 'waiting';
      return 'error';
    }
    if (isGoogleMapsNode && googleMapsKeyStatus) {
      return googleMapsKeyStatus.valid ? 'success' : 'error';
    }
    if (isAIModelNode) {
      if (aiKeyStatus?.valid && hasApiKey) return 'success';
      if (hasApiKey) return 'waiting';
      return 'error';
    }
    if (isConfigured) return 'success';
    if (hasApiKey) return 'waiting';
    return 'idle';
  })();

  const getStatusTitle = () => {
    switch (executionStatus) {
      case 'executing':
        return 'Executing...';
      case 'waiting':
        return nodeStatus?.message || 'Waiting for event...';
      case 'success':
        return 'Execution successful';
      case 'error':
        return `Error: ${nodeStatus?.data?.error || 'Unknown error'}`;
      default:
        if (isAndroidNode) {
          return isAndroidConnected ? 'Android device connected' : 'Android device not connected';
        }
        // WhatsApp nodes - use WebSocket connection status
        if (isWhatsAppNode) {
          if (whatsappStatus.connected) return 'WhatsApp connected';
          if (whatsappStatus.pairing) return 'Pairing in progress...';
          if (whatsappStatus.running) return 'WhatsApp service running';
          return 'WhatsApp not connected';
        }
        // Google Maps nodes - use WebSocket API key validation status
        if (isGoogleMapsNode && googleMapsKeyStatus) {
          return googleMapsKeyStatus.valid
            ? 'Google Maps API key validated'
            : `API key invalid: ${googleMapsKeyStatus.message || 'Validation failed'}`;
        }
        // AI Model nodes - "is stored" from catalogue (hasApiKey),
        // "is validated" from apiKeyStatuses. Independent concerns
        // post-Wave-12; the two sources don't drift across tabs.
        if (isAIModelNode) {
          if (aiKeyStatus?.valid && hasApiKey) {
            return `${aiProviderId?.charAt(0).toUpperCase()}${aiProviderId?.slice(1)} API key validated`;
          }
          if (hasApiKey) {
            return 'API key found, validation pending';
          }
          return 'API key required - configure in Credentials';
        }
        return isConfigured
          ? 'Service configured and ready'
          : hasApiKey
            ? 'API key found, service needs configuration'
            : 'API key required';
    }
  };


  // Schema-driven icon dispatch. `useNodeSpec` subscribes to the
  // NodeSpec cache so the icon populates when prefetch lands without
  // waiting for a parent re-render. <NodeIcon> resolves the ref and
  // tints lucide icons with the node's brand color via currentColor.
  const iconRef = (spec?.icon as string | undefined) ?? (definition?.icon as string | undefined);

  // Get the node color from definition or use default
  const nodeColor = definition?.defaults?.color || 'var(--node-model)';

  return (
    // `sq-node` + `selected` co-classes are the design-handoff structural
    // hooks for per-theme square-node styling (Atomic's `.sq-node-box`
    // and its selected state).
    <div
      className={`sq-node ${selected ? 'selected' : ''}`}
      data-executing={isExecuting ? '' : undefined}
      style={{
        '--node-color': nodeColor,
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        fontFamily: 'var(--font-body)',
        fontSize: '11px',
        cursor: 'pointer',
      } as NodeStyle}
    >
      {isExecuting && typeof nodeStatus?.data?.iteration === 'number' && <span role="status" className="text-xs text-fg-muted">
        Step {nodeStatus.data.iteration} / {Number(nodeStatus.data.max_iterations || 0)}
        {typeof nodeStatus.data.phase === 'string' ? ` · ${nodeStatus.data.phase}` : ''}
      </span>}
      {/* Main Square Node */}
      <div
        className="sq-node-box"
        style={{
          '--node-color': nodeColor,
          position: 'relative',
          width: theme.nodeSize.square,
          height: theme.nodeSize.square,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: theme.colors.text,
          fontSize: theme.nodeSize.squareIcon,
          fontWeight: '600',
          transition: 'transform 0.2s ease, border-color 0.2s ease, opacity 0.2s ease',
          opacity: isDisabled ? 0.5 : 1,
        } as NodeStyle}
      >
        {/* Disabled Overlay */}
        {isDisabled && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'color-mix(in srgb, var(--fg-faint) 40%, transparent)',
            borderRadius: 'inherit',
            zIndex: 35,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            pointerEvents: 'none',
          }}>
            <span style={{ fontSize: '20px', opacity: 0.8, color: theme.colors.textSecondary }}>||</span>
          </div>
        )}


        {/* Service Icon */}
        <NodeIcon icon={iconRef} size={theme.nodeSize.squareIcon} />

        {/* Parameters Button — visual styles (background, border, hover)
            owned by `.sq-node-gear` in base.css + per-theme overrides.
            Inline keeps positioning + sizing only. */}
        <button
          onClick={handleParametersClick}
          style={{
            position: 'absolute',
            top: '-8px',
            right: '-8px',
            width: theme.nodeSize.paramButton,
            height: theme.nodeSize.paramButton,
            fontSize: theme.fontSize.xs,
            zIndex: 30,
          }}
          title="Edit Service Parameters"
          className="sq-node-gear"
        >
          ⚙️
        </button>

        {/* Configuration/Execution Status Indicator.
            Background color is owned by `.sq-node-pip[data-status="..."]`
            in base.css (and per-theme overrides). We pass only the
            execution/connection bucket here — no inline color. */}
        <div
          className="sq-node-pip"
          data-status={pipStatus}
          style={{
            position: 'absolute',
            top: '-4px',
            left: '-4px',
            width: theme.nodeSize.statusIndicator,
            height: theme.nodeSize.statusIndicator,
            zIndex: 30,
          }}
          title={getStatusTitle()}
        />

        {/* NodeSpec owns the complete topology. This renderer deliberately
            knows no handle ids: Context, Memory-as-tool and future plugin
            handles use the same positioning contract as main I/O. */}
        {renderedHandles.map((handle) => {
          const placement: React.CSSProperties =
            handle.position === 'left'
              ? { left: '-6px', top: handle.offset || '50%', transform: 'translateY(-50%)' }
              : handle.position === 'right'
                ? { right: '-6px', top: handle.offset || '50%', transform: 'translateY(-50%)' }
                : handle.position === 'top'
                  ? { top: '-6px', left: handle.offset || '50%', transform: 'translateX(-50%)' }
                  : { bottom: '-6px', left: handle.offset || '50%', transform: 'translateX(-50%)' };
          return (
            <Handle
              key={handle.name}
              id={handle.name}
              type={handle.kind === 'input' ? 'target' : 'source'}
              position={REACT_POSITION[handle.position]}
              isConnectable={isConnectable}
              className={`sq-node-handle ${handle.kind === 'input' ? 'in' : 'out'}`}
              style={{
                '--node-color':
                  handle.kind === 'output' && handle.role === 'main' && !isConfigured
                    ? theme.colors.textSecondary
                    : nodeColor,
                position: 'absolute',
                ...placement,
                width: theme.nodeSize.handle,
                height: theme.nodeSize.handle,
                zIndex: 20,
              } as NodeStyle}
              title={handle.label || handle.name}
            />
          );
        })}

        {/* Output Data Indicator - shows when node has execution output */}
        {executionStatus === 'success' && nodeStatus?.data && (
          <div
            style={{
              position: 'absolute',
              bottom: '-4px',
              right: '-4px',
              width: theme.nodeSize.outputBadge,
              height: theme.nodeSize.outputBadge,
              borderRadius: theme.borderRadius.sm,
              backgroundColor: 'var(--success)',
              border: '1px solid var(--bg-canvas)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: theme.fontSize.xs,
              color: 'white',
              fontWeight: 'bold',
              zIndex: 30,
              boxShadow: theme.isDarkMode
                ? '0 1px 3px rgba(0,0,0,0.2)'
                : '0 1px 3px rgba(0,0,0,0.15)',
            }}
            title="Output data available - click node to view"
          >
            <span style={{ lineHeight: 1 }}>D</span>
          </div>
        )}
      </div>

      {/* Service Name Below Square */}
      <EditableNodeLabel
        nodeId={id}
        label={data?.label}
        defaultLabel={defaultLabel}
        onLabelChange={handleLabelChange}
        onActivate={handleLabelActivate}
      />

    </div>
  );
};

export default memo(SquareNode, nodePropsEqual);