All files / src App.tsx

0% Statements 0/377
0% Branches 0/1
0% Functions 0/1
0% Lines 0/377

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import './index.css';
import { Sidebar, MainViewType } from './components/Sidebar';
import { ChatArea } from './components/ChatArea';
import { RightPanel } from './components/RightPanel';
import { SettingsLayout } from './components/Settings/SettingsLayout';
import { AutomationPanel } from './components/Automation';
import { TeamCollaborationView } from './components/TeamCollaborationView';
import { TeamOrchestrator } from './components/TeamOrchestrator';
import { SwarmDashboard } from './components/SwarmDashboard';
import { SkillMarket } from './components/SkillMarket';
import { AgentOnboardingWizard } from './components/AgentOnboardingWizard';
import { HandApprovalModal } from './components/HandApprovalModal';
import { TopBar } from './components/TopBar';
import { DetailDrawer } from './components/DetailDrawer';
import { useConnectionStore } from './store/connectionStore';
import { useHandStore, type HandRun } from './store/handStore';
import { useTeamStore } from './store/teamStore';
import { useChatStore } from './store/chatStore';
import { initializeStores } from './store';
import { getStoredGatewayToken } from './lib/gateway-client';
import { pageVariants, defaultTransition, fadeInVariants } from './lib/animations';
import { Users, Loader2, Settings } from 'lucide-react';
import { EmptyState } from './components/ui';
import { isTauriRuntime, getLocalGatewayStatus, startLocalGateway } from './lib/tauri-gateway';
import { useOnboarding } from './lib/use-onboarding';
import { intelligenceClient } from './lib/intelligence-client';
import { useProposalNotifications, ProposalNotificationHandler } from './lib/useProposalNotifications';
import { useToast } from './components/ui/Toast';
import type { Clone } from './store/agentStore';
 
type View = 'main' | 'settings';
 
// Bootstrap component that ensures OpenFang is running before rendering main UI
function BootstrapScreen({ status }: { status: string }) {
  return (
    <div className="h-screen flex items-center justify-center bg-gray-50">
      <div className="flex flex-col items-center gap-4">
        <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
        <p className="text-gray-600 text-sm">{status}</p>
      </div>
    </div>
  );
}
 
function App() {
  const [view, setView] = useState<View>('main');
  const [mainContentView, setMainContentView] = useState<MainViewType>('chat');
  const [selectedTeamId, setSelectedTeamId] = useState<string | undefined>(undefined);
  const [bootstrapping, setBootstrapping] = useState(true);
  const [bootstrapStatus, setBootstrapStatus] = useState('Initializing...');
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showDetailDrawer, setShowDetailDrawer] = useState(false);
 
  // Hand Approval state
  const [pendingApprovalRun, setPendingApprovalRun] = useState<HandRun | null>(null);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [teamViewMode, setTeamViewMode] = useState<'collaboration' | 'orchestrator'>('collaboration');
 
  const connect = useConnectionStore((s) => s.connect);
  const hands = useHandStore((s) => s.hands);
  const approveHand = useHandStore((s) => s.approveHand);
  const loadHands = useHandStore((s) => s.loadHands);
  const { activeTeam, setActiveTeam, teams } = useTeamStore();
  const { setCurrentAgent, newConversation } = useChatStore();
  const { isNeeded: onboardingNeeded, isLoading: onboardingLoading, markCompleted } = useOnboarding();
 
  // Proposal notifications
  const { toast } = useToast();
  useProposalNotifications(); // Sets up polling for pending proposals
 
  // Show toast when new proposals are available
  useEffect(() => {
    const handleProposalAvailable = (event: Event) => {
      const customEvent = event as CustomEvent<{ count: number }>;
      const { count } = customEvent.detail;
      toast(`${count} 个新的人格变更提案待审批`, 'info');
    };
 
    window.addEventListener('zclaw:proposal-available', handleProposalAvailable);
    return () => {
      window.removeEventListener('zclaw:proposal-available', handleProposalAvailable);
    };
  }, [toast]);
 
  useEffect(() => {
    document.title = 'ZCLAW';
  }, []);
 
  // Watch for Hands that need approval
  useEffect(() => {
    const handsNeedingApproval = hands.filter(h => h.status === 'needs_approval');
    if (handsNeedingApproval.length > 0 && !showApprovalModal) {
      // Find the first hand with needs_approval and create a pending run
      const hand = handsNeedingApproval[0];
      if (hand.currentRunId) {
        setPendingApprovalRun({
          runId: hand.currentRunId,
          status: 'needs_approval',
          startedAt: new Date().toISOString(),
        });
        setShowApprovalModal(true);
      }
    }
  }, [hands, showApprovalModal]);
 
  // Handle approval/rejection of Hand runs
  const handleApproveHand = useCallback(async (runId: string) => {
    // Find the hand that owns this run
    const hand = hands.find(h => h.currentRunId === runId);
    if (!hand) return;
 
    await approveHand(hand.id, runId, true);
    await loadHands();
    setShowApprovalModal(false);
    setPendingApprovalRun(null);
  }, [hands, approveHand, loadHands]);
 
  const handleRejectHand = useCallback(async (runId: string, reason: string) => {
    // Find the hand that owns this run
    const hand = hands.find(h => h.currentRunId === runId);
    if (!hand) return;
 
    await approveHand(hand.id, runId, false, reason);
    await loadHands();
    setShowApprovalModal(false);
    setPendingApprovalRun(null);
  }, [hands, approveHand, loadHands]);
 
  const handleCloseApprovalModal = useCallback(() => {
    setShowApprovalModal(false);
    // Don't clear pendingApprovalRun - keep it for reference
  }, []);
 
  // Bootstrap: Start OpenFang Gateway before rendering main UI
  useEffect(() => {
    let mounted = true;
 
    const bootstrap = async () => {
      try {
        // Step 1: Check and start local gateway in Tauri environment
        if (isTauriRuntime()) {
          setBootstrapStatus('Checking gateway status...');
 
          try {
            const status = await getLocalGatewayStatus();
            const isRunning = status.portStatus === 'busy' || status.listenerPids.length > 0;
 
            if (!isRunning && status.cliAvailable) {
              setBootstrapStatus('Starting OpenFang Gateway...');
              console.log('[App] Local gateway not running, auto-starting...');
 
            await startLocalGateway();
 
            // Wait for gateway to be ready
            await new Promise(resolve => setTimeout(resolve, 2000));
            console.log('[App] Local gateway started');
          } else if (isRunning) {
            console.log('[App] Local gateway already running');
          }
        } catch (err) {
          console.warn('[App] Failed to check/start local gateway:', err);
        }
      }
 
      if (!mounted) return;
 
      // Step 2: Connect to gateway
      setBootstrapStatus('Connecting to gateway...');
      const gatewayToken = getStoredGatewayToken();
      await connect(undefined, gatewayToken);
 
      if (!mounted) return;
 
      // Step 3: Check if onboarding is needed
      if (onboardingNeeded && !onboardingLoading) {
        setShowOnboarding(true);
      }
 
      // Step 4: Initialize stores with gateway client
      initializeStores();
 
      // Step 4.5: Auto-start heartbeat engine for self-evolution
      try {
        const defaultAgentId = 'zclaw-main';
        await intelligenceClient.heartbeat.init(defaultAgentId, {
          enabled: true,
          interval_minutes: 30,
          quiet_hours_start: '22:00',
          quiet_hours_end: '08:00',
          notify_channel: 'ui',
          proactivity_level: 'standard',
          max_alerts_per_tick: 5,
        });
 
        // Sync memory stats to heartbeat engine
        try {
          const stats = await intelligenceClient.memory.stats();
          const taskCount = stats.byType?.['task'] || 0;
          await intelligenceClient.heartbeat.updateMemoryStats(
            defaultAgentId,
            taskCount,
            stats.totalEntries,
            stats.storageSizeBytes
          );
          console.log('[App] Memory stats synced to heartbeat engine');
        } catch (statsErr) {
          console.warn('[App] Failed to sync memory stats:', statsErr);
        }
 
        await intelligenceClient.heartbeat.start(defaultAgentId);
        console.log('[App] Heartbeat engine started for self-evolution');
 
        // Set up periodic memory stats sync (every 5 minutes)
        const MEMORY_STATS_SYNC_INTERVAL = 5 * 60 * 1000;
        const statsSyncInterval = setInterval(async () => {
          try {
            const stats = await intelligenceClient.memory.stats();
            const taskCount = stats.byType?.['task'] || 0;
            await intelligenceClient.heartbeat.updateMemoryStats(
              defaultAgentId,
              taskCount,
              stats.totalEntries,
              stats.storageSizeBytes
            );
            console.log('[App] Memory stats synced (periodic)');
          } catch (err) {
            console.warn('[App] Periodic memory stats sync failed:', err);
          }
        }, MEMORY_STATS_SYNC_INTERVAL);
 
        // Store interval for cleanup
        // @ts-expect-error - Global cleanup reference
        window.__ZCLAW_STATS_SYNC_INTERVAL__ = statsSyncInterval;
      } catch (err) {
        console.warn('[App] Failed to start heartbeat engine:', err);
        // Non-critical, continue without heartbeat
      }
 
      // Step 5: Bootstrap complete
      setBootstrapping(false);
    } catch (err) {
      console.error('[App] Bootstrap failed:', err);
      // Still allow app to load, connection status will show error
      setBootstrapping(false);
    }
  };
 
    bootstrap();
 
    return () => {
      mounted = false;
      // Clean up periodic stats sync interval
      // @ts-expect-error - Global cleanup reference
      if (window.__ZCLAW_STATS_SYNC_INTERVAL__) {
        // @ts-expect-error - Global cleanup reference
        clearInterval(window.__ZCLAW_STATS_SYNC_INTERVAL__);
      }
    };
  }, [connect, onboardingNeeded, onboardingLoading]);
 
  // Handle onboarding completion
  const handleOnboardingSuccess = (clone: Clone) => {
    markCompleted({
      userName: clone.userName || 'User',
      userRole: clone.userRole,
    });
    setCurrentAgent({
      id: clone.id,
      name: clone.name,
      icon: clone.emoji || '🦞',
      color: 'bg-gradient-to-br from-orange-500 to-red-500',
      lastMessage: clone.role || 'New Agent',
      time: '',
    });
    setShowOnboarding(false);
  };
 
  // 处理主视图切换
  const handleMainViewChange = (view: MainViewType) => {
    setMainContentView(view);
  };
 
  // 处理新对话
  const handleNewChat = () => {
    newConversation();
    setMainContentView('chat');
  };
 
  const handleSelectTeam = (teamId: string) => {
    const team = teams.find(t => t.id === teamId);
    if (team) {
      setActiveTeam(team);
      setSelectedTeamId(teamId);
    }
  };
 
  if (view === 'settings') {
    return <SettingsLayout onBack={() => setView('main')} />;
  }
 
  // Show bootstrap screen while starting gateway
  if (bootstrapping) {
    return <BootstrapScreen status={bootstrapStatus} />;
  }
 
  // Show onboarding wizard for first-time users
  if (showOnboarding) {
    return (
      <AgentOnboardingWizard
        isOpen={true}
        onClose={async () => {
          // Skip onboarding but still create a default agent with default personality
          try {
            const { getGatewayClient } = await import('./lib/gateway-client');
            const client = getGatewayClient();
            if (client) {
              // Create default agent with versatile assistant personality
              const defaultAgent = await client.createClone({
                name: '全能助手',
                role: '全能型 AI 助手',
                nickname: '小龙',
                emoji: '🦞',
                personality: 'friendly',
                scenarios: ['coding', 'writing', 'research', 'product', 'data'],
                userName: 'User',
                userRole: 'user',
                communicationStyle: '亲切、耐心、善解人意,用易懂的语言解释复杂概念',
              });
 
              if (defaultAgent?.clone) {
                setCurrentAgent({
                  id: defaultAgent.clone.id,
                  name: defaultAgent.clone.name,
                  icon: defaultAgent.clone.emoji || '🦞',
                  color: 'bg-gradient-to-br from-orange-500 to-red-500',
                  lastMessage: defaultAgent.clone.role || '全能型 AI 助手',
                  time: '',
                });
              }
            }
          } catch (err) {
            console.warn('[App] Failed to create default agent on skip:', err);
          }
 
          // Mark onboarding as completed
          markCompleted({
            userName: 'User',
            userRole: 'user',
          });
          setShowOnboarding(false);
        }}
        onSuccess={handleOnboardingSuccess}
      />
    );
  }
 
  return (
    <div className="h-screen flex overflow-hidden text-gray-800 text-sm bg-white dark:bg-gray-950">
      {/* 左侧边栏 */}
      <Sidebar
        onOpenSettings={() => setView('settings')}
        onMainViewChange={handleMainViewChange}
        selectedTeamId={selectedTeamId}
        onSelectTeam={handleSelectTeam}
        onNewChat={handleNewChat}
      />
 
      {/* 主内容区 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* 顶部工具栏 */}
        <TopBar
          title="ZCLAW"
          onOpenDetail={() => setShowDetailDrawer(true)}
        />
 
        {/* 内容区域 */}
        <AnimatePresence mode="wait">
          <motion.main
            key={mainContentView}
            variants={pageVariants}
            initial="initial"
            animate="animate"
            exit="exit"
            transition={defaultTransition}
            className="flex-1 overflow-hidden relative flex flex-col"
          >
            {mainContentView === 'automation' ? (
              <motion.div
                variants={fadeInVariants}
                initial="initial"
                animate="animate"
                className="h-full overflow-y-auto"
              >
                <AutomationPanel />
              </motion.div>
            ) : mainContentView === 'team' ? (
              activeTeam ? (
                <div className="h-full flex flex-col">
                  {/* Team View Tabs */}
                  <div className="flex border-b border-gray-200 dark:border-gray-700 px-4">
                    <button
                      onClick={() => setTeamViewMode('collaboration')}
                      className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                        teamViewMode === 'collaboration'
                          ? 'text-orange-600 dark:text-orange-400 border-orange-500'
                          : 'text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300'
                      }`}
                    >
                      <Users className="w-4 h-4" />
                      协作视图
                    </button>
                    <button
                      onClick={() => setTeamViewMode('orchestrator')}
                      className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                        teamViewMode === 'orchestrator'
                          ? 'text-orange-600 dark:text-orange-400 border-orange-500'
                          : 'text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300'
                      }`}
                    >
                      <Settings className="w-4 h-4" />
                      编排管理
                    </button>
                  </div>
                  {/* Tab Content */}
                  <div className="flex-1 overflow-hidden">
                    {teamViewMode === 'orchestrator' ? (
                      <TeamOrchestrator isOpen={true} onClose={() => setTeamViewMode('collaboration')} />
                    ) : (
                      <TeamCollaborationView teamId={activeTeam.id} />
                    )}
                  </div>
                </div>
              ) : (
                <EmptyState
                  icon={<Users className="w-8 h-8" />}
                  title="选择或创建团队"
                  description="从左侧列表中选择一个团队,或点击 + 创建新的多 Agent 协作团队。"
                />
              )
            ) : mainContentView === 'swarm' ? (
              <motion.div
                variants={fadeInVariants}
                initial="initial"
                animate="animate"
                className="h-full overflow-hidden"
              >
                <SwarmDashboard />
              </motion.div>
            ) : mainContentView === 'skills' ? (
              <motion.div
                variants={fadeInVariants}
                initial="initial"
                animate="animate"
                className="h-full overflow-hidden"
              >
                <SkillMarket />
              </motion.div>
            ) : (
              <ChatArea />
            )}
          </motion.main>
        </AnimatePresence>
      </div>
 
      {/* 详情抽屉 - 按需显示 */}
      <DetailDrawer
        open={showDetailDrawer}
        onClose={() => setShowDetailDrawer(false)}
        title="详情"
      >
        <RightPanel />
      </DetailDrawer>
 
      {/* Hand Approval Modal (global) */}
      <HandApprovalModal
        handRun={pendingApprovalRun}
        isOpen={showApprovalModal}
        onApprove={handleApproveHand}
        onReject={handleRejectHand}
        onClose={handleCloseApprovalModal}
      />
 
      {/* Proposal Notifications Handler */}
      <ProposalNotificationHandler />
    </div>
  );
}
 
export default App;