All files / src/lib useTeamEvents.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * useTeamEvents - WebSocket Real-time Event Sync Hook
 *
 * Subscribes to team collaboration events via WebSocket
 * and updates the team store in real-time.
 *
 * @module lib/useTeamEvents
 */
 
import { useEffect, useRef, useCallback } from 'react';
import { useTeamStore } from '../store/teamStore';
import { useGatewayStore } from '../store/gatewayStore';
import type { TeamEventMessage, TeamEventType, CollaborationEvent } from '../lib/team-client';
import { silentErrorHandler } from './error-utils';
 
interface UseTeamEventsOptions {
  /** Subscribe to specific team only, or null for all teams */
  teamId?: string | null;
  /** Event types to subscribe to (default: all) */
  eventTypes?: TeamEventType[];
  /** Maximum events to keep in history (default: 100) */
  maxEvents?: number;
}
 
/**
 * Hook for subscribing to real-time team collaboration events
 */
export function useTeamEvents(options: UseTeamEventsOptions = {}) {
  const { teamId = null, eventTypes } = options;
  const unsubscribeRef = useRef<(() => void) | null>(null);
 
  const {
    addEvent,
    updateTaskStatus,
    updateLoopState,
    loadTeams,
  } = useTeamStore();
 
  const { connectionState } = useGatewayStore();
 
  const handleTeamEvent = useCallback(
    (message: TeamEventMessage) => {
      // Filter by event types if specified
      if (eventTypes && !eventTypes.includes(message.eventType)) {
        return;
      }
 
      // Create collaboration event for store
      const event = {
        type: mapEventType(message.eventType),
        teamId: message.teamId,
        sourceAgentId: (message.payload.sourceAgentId as string) || 'system',
        payload: message.payload,
        timestamp: message.timestamp,
      };
 
      // Add to event history
      addEvent(event);
 
      // Handle specific event types
      switch (message.eventType) {
        case 'task.status_changed':
          if (message.payload.taskId && message.payload.status) {
            updateTaskStatus(
              message.teamId,
              message.payload.taskId as string,
              message.payload.status as any
            );
          }
          break;
 
        case 'loop.state_changed':
          if (message.payload.loopId && message.payload.state) {
            updateLoopState(
              message.teamId,
              message.payload.loopId as string,
              message.payload.state as any
            );
          }
          break;
 
        case 'team.updated':
        case 'member.added':
        case 'member.removed':
          // Reload teams to get updated data
          loadTeams().catch(silentErrorHandler('useTeamEvents'));
          break;
      }
    },
    [eventTypes, addEvent, updateTaskStatus, updateLoopState, loadTeams]
  );
 
  useEffect(() => {
    // Only subscribe when connected
    if (connectionState !== 'connected') {
      return;
    }
 
    // Get WebSocket from gateway client
    const client = getGatewayClientSafe();
    if (!client || !client.ws) {
      return;
    }
 
    const ws = client.ws;
 
    // Subscribe to team events
    const handleMessage = (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'team_event') {
          handleTeamEvent(data as TeamEventMessage);
        }
      } catch {
        // Ignore non-JSON messages
      }
    };
 
    ws.addEventListener('message', handleMessage);
 
    // Send subscription message
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(
        JSON.stringify({
          type: 'subscribe',
          topic: teamId ? `team:${teamId}` : 'teams',
        })
      );
    }
 
    unsubscribeRef.current = () => {
      ws.removeEventListener('message', handleMessage);
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(
          JSON.stringify({
            type: 'unsubscribe',
            topic: teamId ? `team:${teamId}` : 'teams',
          })
        );
      }
    };
 
    return () => {
      if (unsubscribeRef.current) {
        unsubscribeRef.current();
        unsubscribeRef.current = null;
      }
    };
  }, [connectionState, teamId, handleTeamEvent]);
 
  return {
    isConnected: connectionState === 'connected',
  };
}
 
/**
 * Hook for subscribing to a specific team's events
 */
export function useTeamEventStream(teamId: string) {
  return useTeamEvents({ teamId });
}
 
/**
 * Hook for subscribing to all team events
 */
export function useAllTeamEvents(options: Omit<UseTeamEventsOptions, 'teamId'> = {}) {
  return useTeamEvents({ ...options, teamId: null });
}
 
// === Helper Functions ===
 
function mapEventType(eventType: TeamEventType): CollaborationEvent['type'] {
  const mapping: Record<TeamEventType, CollaborationEvent['type']> = {
    'team.created': 'member_status_change',
    'team.updated': 'member_status_change',
    'team.deleted': 'member_status_change',
    'member.added': 'member_status_change',
    'member.removed': 'member_status_change',
    'member.status_changed': 'member_status_change',
    'task.created': 'task_assigned',
    'task.assigned': 'task_assigned',
    'task.status_changed': 'task_started',
    'task.completed': 'task_completed',
    'loop.started': 'loop_state_change',
    'loop.state_changed': 'loop_state_change',
    'loop.completed': 'loop_state_change',
    'review.submitted': 'review_submitted',
  };
  return mapping[eventType] || 'task_started';
}
 
function getGatewayClientSafe() {
  try {
    // Dynamic import to avoid circular dependency
    const { getClient } = require('../store/connectionStore');
    return getClient();
  } catch {
    return null;
  }
}
 
export default useTeamEvents;