File size: 5,917 Bytes
5da4770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMemo, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { useAgent } from '@/hooks/react-query/agents/use-agents';
import { useAgentVersion, useVersionStore } from '@/lib/versioning';

interface NormalizedMCP {
  name: string;
  type: string;
  customType: string;
  config: Record<string, any>;
  enabledTools: string[];
}

interface NormalizedVersionData {
  version_id: string;
  agent_id: string;
  version_number: number;
  version_name: string;
  system_prompt: string;
  configured_mcps: any[];
  custom_mcps: NormalizedMCP[];
  agentpress_tools: Record<string, any>;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  created_by?: string;
  change_description?: string;
}

interface UseAgentVersionDataProps {
  agentId: string;
}

interface UseAgentVersionDataReturn {
  agent: any;
  versionData: NormalizedVersionData | null;
  isViewingOldVersion: boolean;
  isLoading: boolean;
  error: Error | null;
}


function normalizeCustomMcps(mcps: any): NormalizedMCP[] {
  if (!mcps || !Array.isArray(mcps)) {
    return [];
  }
  
  return mcps.map(mcp => {
    if (!mcp || typeof mcp !== 'object') {
      return {
        name: 'Unknown MCP',
        type: 'sse',
        customType: 'sse',
        config: {},
        enabledTools: []
      };
    }
    
    return {
      name: mcp.name || 'Unnamed MCP',
      type: mcp.type || mcp.customType || 'sse',
      customType: mcp.customType || mcp.type || 'sse',
      config: mcp.config || {},
      enabledTools: mcp.enabledTools || mcp.enabled_tools || []
    };
  });
}

function normalizeVersionData(version: any): NormalizedVersionData | null {
  if (!version) return null;
  
  const isApiFormat = 'version_id' in version;
  
  if (isApiFormat) {
    return {
      version_id: version.version_id,
      agent_id: version.agent_id,
      version_number: version.version_number,
      version_name: version.version_name,
      system_prompt: version.system_prompt || '',
      configured_mcps: Array.isArray(version.configured_mcps) ? version.configured_mcps : [],
      custom_mcps: normalizeCustomMcps(version.custom_mcps),
      agentpress_tools: version.agentpress_tools && typeof version.agentpress_tools === 'object' 
        ? version.agentpress_tools 
        : {},
      is_active: version.is_active ?? true,
      created_at: version.created_at,
      updated_at: version.updated_at || version.created_at,
      created_by: version.created_by,
      change_description: version.change_description
    };
  } else {
    return {
      version_id: version.versionId?.value || version.versionId,
      agent_id: version.agentId?.value || version.agentId,
      version_number: version.versionNumber?.value || version.versionNumber,
      version_name: version.versionName,
      system_prompt: version.systemPrompt || '',
      configured_mcps: Array.isArray(version.configuredMcps) ? version.configuredMcps : [],
      custom_mcps: normalizeCustomMcps(version.customMcps),
      agentpress_tools: version.agentpress_tools || version.toolConfiguration?.tools || {},
      is_active: version.isActive ?? true,
      created_at: version.createdAt instanceof Date ? version.createdAt.toISOString() : version.createdAt,
      updated_at: (version.updatedAt instanceof Date ? version.updatedAt.toISOString() : version.updatedAt) || version.created_at,
      created_by: version.createdBy?.value || version.createdBy,
      change_description: version.changeDescription
    };
  }
}

export function useAgentVersionData({ agentId }: UseAgentVersionDataProps): UseAgentVersionDataReturn {
  const searchParams = useSearchParams();
  const versionParam = searchParams.get('version');
  
  const { data: agent, isLoading: agentLoading, error: agentError } = useAgent(agentId);
  const shouldLoadVersion = versionParam || agent?.current_version_id;
  const versionToLoad = versionParam || agent?.current_version_id || '';
  
  const { data: rawVersionData, isLoading: versionLoading, error: versionError } = useAgentVersion(
    agentId,
    shouldLoadVersion ? versionToLoad : null
  );
  
  const { setCurrentVersion, clearVersionState } = useVersionStore();
  
  const versionData = useMemo(() => {
    console.log('[useAgentVersionData] Raw version data:', rawVersionData);
    const normalized = normalizeVersionData(rawVersionData);
    console.log('[useAgentVersionData] Normalized version data:', normalized);
    return normalized;
  }, [rawVersionData]);
  
  const isViewingOldVersion = useMemo(() => {
    return Boolean(versionParam && versionParam !== agent?.current_version_id);
  }, [versionParam, agent?.current_version_id]);

  useEffect(() => {
    if (versionData) {
      setCurrentVersion({
        versionId: { value: versionData.version_id },
        agentId: { value: versionData.agent_id },
        versionNumber: { value: versionData.version_number },
        versionName: versionData.version_name,
        systemPrompt: versionData.system_prompt,
        configuredMcps: versionData.configured_mcps,
        customMcps: versionData.custom_mcps,
        toolConfiguration: { tools: versionData.agentpress_tools },
        agentpress_tools: versionData.agentpress_tools,
        isActive: versionData.is_active,
        createdAt: new Date(versionData.created_at),
        updatedAt: new Date(versionData.updated_at),
        createdBy: { value: versionData.created_by || '' },
        changeDescription: versionData.change_description,
      });
    } else if (!versionParam) {
      clearVersionState();
    }

    return () => {
      clearVersionState();
    };
  }, [versionData, versionParam, setCurrentVersion, clearVersionState]);
  
  const isLoading = agentLoading || (shouldLoadVersion ? versionLoading : false);
  const error = agentError || versionError;
  
  return {
    agent,
    versionData,
    isViewingOldVersion,
    isLoading,
    error
  };
}