-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocessPage.tsx
More file actions
687 lines (606 loc) · 24.9 KB
/
Copy pathprocessPage.tsx
File metadata and controls
687 lines (606 loc) · 24.9 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
import React, { useState, useEffect, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import { RootState } from "../store/store";
import { togglePanel, closePanel } from "../slices/historyPanelSlice";
import { MessageBar, MessageBarType } from "@fluentui/react";
import Header from "../components/Header/Header";
import HeaderTools from "../components/Header/HeaderTools";
import PanelRightToolbar from "../components/Panels/PanelRightToolbar";
import PanelRight from "../components/Panels/PanelRight";
import BatchHistoryPanel from "../components/batchHistoryPanel";
import { HistoryRegular, HistoryFilled, bundleIcon } from "@fluentui/react-icons";
import { CircleCheck } from "lucide-react";
import LottieImport from 'lottie-react';
const Lottie = ('default' in LottieImport ? (LottieImport as any).default : LottieImport) as typeof LottieImport;
import documentLoader from "../../public/images/loader.json";
import { apiService } from '../services/ApiService';
import ProgressModal from "../commonComponents/ProgressModal/progressModal";
export const History = bundleIcon(HistoryFilled, HistoryRegular);
// Custom scrollbar styles for better accessibility
const scrollbarStyles = `
.custom-scrollbar {
scrollbar-width: thin;
scrollbar-color: #888 #f1f1f1;
}
.custom-scrollbar::-webkit-scrollbar {
width: 8px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Ensure main content area has visible scrollbars */
.main-content {
scrollbar-width: thin;
scrollbar-color: #888 #f1f1f1;
}
.main-content::-webkit-scrollbar {
width: 8px;
}
.main-content::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.main-content::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
.main-content::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Responsive adjustments for larger screens */
@media (min-width: 1920px) {
.bg-gray-50 {
padding: 2rem !important;
}
.text-2xl {
font-size: 2.5rem !important;
}
.text-lg {
font-size: 1.5rem !important;
}
}
@media (min-width: 1400px) and (max-width: 1919px) {
.bg-gray-50 {
padding: 1.5rem !important;
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
`;
const ProcessPage: React.FC = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const { batchId } = useParams<{ batchId: string }>();
const isPanelOpen = useSelector((state: RootState) => state.historyPanel.isOpen);
// New state for real-time API data
const [currentPhase, setCurrentPhase] = useState<string>("");
const [phaseSteps, setPhaseSteps] = useState<string[]>([]);
const [apiData, setApiData] = useState<any>(null);
const [processingCompleted, setProcessingCompleted] = useState(false);
const stepsContainerRef = useRef<HTMLDivElement>(null);
// Track the last seen phase to prevent duplicate phase messages
const [lastSeenPhase, setLastSeenPhase] = useState<string>("");
// Progress modal state
const [showProgressModal, setShowProgressModal] = useState(false);
const [processingState, setProcessingState] = useState<'IDLE' | 'PROCESSING' | 'COMPLETED'>('IDLE');
// Error state management
const [migrationError, setMigrationError] = useState(false);
const [errorDetails, setErrorDetails] = useState<{ reason: string; step: string; details: string }>({
reason: '',
step: '',
details: '',
});
// Helper function to clean phase name - removes "PHASE X - " prefix
const cleanPhaseName = (phase: string): string => {
if (!phase) return "";
// Remove "PHASE X - " prefix (e.g., "PHASE 3 - SOURCE PLATFORM REVIEW" -> "SOURCE PLATFORM REVIEW")
return phase.replace(/^PHASE\s*\d+\s*-\s*/i, '').trim();
};
// Helper function to generate phase message from API data
// Returns message with agent activity but without phase number prefixes
const getPhaseMessage = (apiResponse: any): string => {
if (!apiResponse) return "";
const { phase, active_agent_count, total_agents, agents } = apiResponse;
// Clean the phase name to remove "PHASE X - " prefix
const cleanedPhase = cleanPhaseName(phase);
// Handle unknown/start phases with friendly initialization message
const initializationPhases = ['unknown', 'start', '', undefined, null];
if (initializationPhases.includes(phase?.toLowerCase()) || initializationPhases.includes(cleanedPhase?.toLowerCase())) {
return 'Initialization phase in progress';
}
const phaseMessages: Record<string, string> = {
'Analysis': 'Analyzing workloads and dependencies, existing container images and configurations',
'Design': 'Designing target environment mappings to align with Azure AKS',
'YAML': 'Converting container specifications and orchestration configs to Azure format',
'Documentation': 'Generating migration report and deployment files'
};
// Extract active agent information from agents array
const activeAgents = agents?.filter((agent: string) =>
agent.includes('speaking') || agent.includes('thinking')
) || [];
const speakingAgent = activeAgents.find((agent: string) => agent.includes('speaking'));
const thinkingAgent = activeAgents.find((agent: string) => agent.includes('thinking'));
let agentActivity = "";
if (speakingAgent) {
const agentName = speakingAgent.split(':')[0].replace(/[✓✗]/g, '').replace(/\[.*?\]/g, '').trim();
agentActivity = ` - ${agentName} is speaking`;
} else if (thinkingAgent) {
const agentName = thinkingAgent.split(':')[0].replace(/[✓✗]/g, '').replace(/\[.*?\]/g, '').trim();
agentActivity = ` - ${agentName} is thinking`;
}
// Use predefined message if available, otherwise use cleaned phase name
const baseMessage = phaseMessages[phase] || phaseMessages[cleanedPhase] || `${cleanedPhase} phase in progress`;
const agentInfo = active_agent_count && total_agents ? ` (${active_agent_count}/${total_agents} agents active)` : '';
// Return message without phase number prefix
return `${baseMessage}${agentActivity}${agentInfo}`;
};
// Polling function to check batch status
const pollBatchStatus = async () => {
if (!batchId) return;
try {
const response = await apiService.get(`/process/status/${batchId}/render/`);
if (!response) {
console.error('No response received from status endpoint');
return;
}
console.log('Polling batch status:', response);
// Store API data for real-time display
setApiData(response);
// Update processing state and show modal when processing starts
if (response.status === 'processing' && processingState !== 'PROCESSING') {
setProcessingState('PROCESSING');
setShowProgressModal(true);
}
// Update current phase - only add a new message when the phase actually changes
// This prevents duplicate messages from agent activity changes within the same phase
if (response.phase && response.phase !== lastSeenPhase) {
console.log('Phase transition detected:', lastSeenPhase, '->', response.phase);
const newPhaseMessage = getPhaseMessage(response);
setCurrentPhase(response.phase);
setLastSeenPhase(response.phase);
// Add the phase message only on phase transition
setPhaseSteps(prev => {
// Double-check to avoid any duplicate messages
if (!prev.includes(newPhaseMessage)) {
console.log('Adding new phase message:', newPhaseMessage);
return [...prev, newPhaseMessage];
}
console.log('Skipping duplicate phase message:', newPhaseMessage);
return prev;
});
} else if (response.phase) {
// Phase unchanged, just update current phase state for display
setCurrentPhase(response.phase);
console.log('Same phase, no new message added:', response.phase);
}
// Check for completion and navigate to batch-view
if (response.status === 'completed') {
console.log('Migration completed! Navigating to batch view page...');
setProcessingCompleted(true);
setProcessingState('COMPLETED');
// Add completion message
setPhaseSteps(prev => [...prev, "✅ Migration completed successfully! Redirecting to results..."]);
// Navigate to the batch view page after a short delay
setTimeout(() => {
navigate(`/batch-view/${batchId}`);
}, 2000); // 2 second delay to show completion
}
// Check for error/failure status
if (response.status === 'failed' || response.status === 'error') {
console.log('Migration failed! Status:', response.status);
setMigrationError(true);
setErrorDetails({
reason: response.failure_reason || '',
step: response.failure_step || '',
details: response.failure_details || '',
});
setProcessingState('IDLE');
setProcessingCompleted(true); // Stop polling
// Add error message with failure reason to steps
const failureMsg = response.failure_reason
? `❌ Migration failed at ${response.failure_step || 'unknown'} step: ${response.failure_reason}`
: "❌ Migration failed - stopping process...";
setPhaseSteps(prev => [...prev, failureMsg]);
}
} catch (error) {
console.error('Error polling batch status:', error);
}
};
// COMMENTED OUT - Old static steps logic
/*
const steps = [
"Analyzing workloads and dependencies, existing container images and configurations...",
"Designing target environment mappings to align with Azure AKS...",
"Converting container specifications and orchestration configs to the new environment...",
"Generating migration report and deployment files...",
"Analyzing workloads and dependencies, existing container images and configurations...",
"Designing target environment mappings to align with Azure AKS...",
"Converting container specifications and orchestration configs to the new environment...",
"Generating migration report and deployment files...",
"Analyzing workloads and dependencies, existing container images and configurations...",
"Designing target environment mappings to align with Azure AKS...",
"Converting container specifications and orchestration configs to the new environment...",
"Generating migration report and deployment files..."
];
*/
// COMMENTED OUT - Old progressive step display logic
/*
// Progressive step display that keeps appending cycles
useEffect(() => {
let stepTimer: ReturnType<typeof setTimeout>;
const addNextStep = () => {
setVisibleStepsCount(prev => {
const newCount = prev + 1;
// After every 4 steps, increment the cycle count
if (newCount % 4 === 0) {
setTotalCycles(prevCycles => prevCycles + 1);
}
return newCount;
});
// Schedule next step in 5 seconds
stepTimer = setTimeout(addNextStep, 5000);
};
// Start the first step after 5 seconds
stepTimer = setTimeout(addNextStep, 5000);
// Cleanup timer on component unmount
return () => {
clearTimeout(stepTimer);
};
}, []);
*/
// Handle modal cancellation
const handleCancelProcessing = async () => {
console.log('=== handleCancelProcessing called ===');
console.log('batchId:', batchId);
// Call API to cancel the process
if (batchId) {
try {
console.log('Calling apiService.cancelProcess with batchId:', batchId);
const result = await apiService.cancelProcess(batchId, 'User cancelled from UI');
console.log('Cancel request result:', result);
// Poll for cancel status every 3 seconds until kill_state is "executed"
const pollCancelStatus = async () => {
const maxAttempts = 60; // Max 3 minutes of polling (60 * 3 seconds)
let attempts = 0;
const poll = async (): Promise<void> => {
attempts++;
console.log(`Polling cancel status, attempt ${attempts}...`);
try {
const status = await apiService.getCancelStatus(batchId);
console.log('Cancel status response:', status);
if (status.kill_state === 'executed') {
console.log('Process cancellation completed successfully');
return;
}
if (status.kill_state === 'failed') {
console.error('Process cancellation failed');
return;
}
// Continue polling if not completed and under max attempts
if (attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 3000)); // Wait 3 seconds
return poll();
} else {
console.warn('Max polling attempts reached for cancel status');
}
} catch (error) {
console.error('Error polling cancel status:', error);
// Don't throw, just stop polling on error
}
};
await poll();
};
// Start polling in the background (don't await to avoid blocking navigation)
pollCancelStatus();
// Navigate to home page immediately after kill is requested
setShowProgressModal(false);
setProcessingState('IDLE');
navigate('/');
} catch (error) {
console.error('Failed to cancel process:', error);
// Still navigate to home page even if API call fails
setShowProgressModal(false);
setProcessingState('IDLE');
navigate('/');
}
} else {
console.warn('No batchId available, skipping cancel API call');
setShowProgressModal(false);
setProcessingState('IDLE');
navigate('/');
}
};
// Effect to show modal automatically when processing is detected
useEffect(() => {
if (apiData && apiData.status === 'processing' && !showProgressModal) {
setShowProgressModal(true);
setProcessingState('PROCESSING');
}
}, [apiData, showProgressModal]);
// Polling effect - poll every 5 seconds for batch status
useEffect(() => {
if (!batchId || processingCompleted) {
return;
}
console.log('Starting batch status polling every 5 seconds...');
// Poll immediately on mount
pollBatchStatus();
// Set up interval for every 5 seconds
const pollInterval = setInterval(() => {
console.log('Polling batch status...');
pollBatchStatus();
}, 10000); // Poll every 10 seconds
return () => {
console.log('Cleaning up batch status polling');
clearInterval(pollInterval);
};
}, [batchId, processingCompleted]);
// Auto-scroll effect when new phase steps are added
useEffect(() => {
if (stepsContainerRef.current && phaseSteps.length > 0) {
const container = stepsContainerRef.current;
// Scroll to bottom with smooth behavior
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth'
});
}
}, [phaseSteps]);
const handleTogglePanel = () => {
console.log("Toggling panel from Process Page");
dispatch(togglePanel());
};
const handleLeave = () => {
// Show progress modal when header is clicked
setShowProgressModal(true);
};
const handleNavigateHome = () => {
// Navigate back to landing page
navigate('/');
};
return (
<>
<style dangerouslySetInnerHTML={{ __html: scrollbarStyles }} />
<div className="landing-page flex flex-col relative h-screen">
{/* Header - Same as Landing Page */}
<Header subtitle="Container Migration" onTitleClick={handleLeave}>
<HeaderTools>
</HeaderTools>
</Header>
{/* Main Content */}
<main className={`main-content ${isPanelOpen ? "shifted" : ""} flex-1 flex overflow-auto bg-mode-neutral-background-1-rest relative`}>
<div className="min-h-full flex flex-col items-center bg-gray-50 p-4 sm:p-6 lg:p-8 w-full" style={{ marginTop: 'clamp(20px, 4vh, 60px)', paddingTop: '1rem' }}>
{/* Header - Centered */}
<div className="text-center mb-2" style={{ textAlign: 'center' }}>
<h1 className="text-2xl sm:text-3xl lg:text-4xl font-semibold mb-1">Container Migration</h1>
<p className="text-gray-600 max-w-xl lg:max-w-2xl mx-auto text-sm sm:text-base">
Migrate your third party container workloads to{" "}
<a
href="https://azure.microsoft.com/en-us/products/kubernetes-service/"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline"
>
Azure AKS
</a>{" "}
</p>
</div>
{/* Error MessageBar - Between title and Agent Activity */}
{migrationError && (
<div style={{
width: '100%',
maxWidth: '60vw',
margin: '0px auto',
marginBottom: '20px' // Reduced gap from 40px to 20px
}}>
<MessageBar
messageBarType={MessageBarType.error}
isMultiline={true}
//onDismiss={() => setMigrationError(false)}
dismissButtonAriaLabel="Close"
styles={{
root: {
display: "flex",
alignItems: "center",
backgroundColor: "#fef2f2",
borderColor: "#fca5a5",
color: "#991b1b"
},
text: {
fontSize: "14px", // Increased from default (usually 14px)
}
}}
>
The migration stopped before completion and no results were generated.
<br />
{errorDetails.step && (
<><strong>Failed step:</strong> {errorDetails.step}<br /></>
)}
{errorDetails.reason && (
<><strong>Reason:</strong> {errorDetails.reason.length > 300 ? errorDetails.reason.substring(0, 300) + '...' : errorDetails.reason}<br /></>
)}
<span style={{ fontSize: '12px', color: '#666' }}>Process ID: {batchId}</span>
</MessageBar>
</div>
)}
{/* Card */}
<div className="bg-white border-2 border-gray-300 rounded-2xl shadow-lg p-6 sm:p-8" style={{
textAlign: 'center',
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
border: '1px solid #d1d5db',
width: '100%',
maxWidth: '60vw',
margin: '10px auto', // Reduced from '0px auto' to bring it closer to header
borderRadius: '12px',
paddingBottom: '16px',
paddingTop: '16px',
}}>
{/* Lottie Animation - Centered above Agent Activity */}
{!migrationError && (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '100%',
marginBottom: '24px'
}}>
<Lottie
animationData={documentLoader}
loop={true}
style={{
width: '120px',
height: '120px',
margin: '0 auto'
}}
/>
</div>
)}
{/* Title */}
<h2 className="text-lg font-semibold text-center mb-6" style={{ textAlign: 'center' }}>Agent Activity</h2>
{/* Real-time phase steps from API */}
<div
ref={stepsContainerRef}
style={{
display: 'flex',
flexDirection: 'column',
gap: '8px',
width: '100%',
maxWidth: '90%',
margin: '0 auto',
maxHeight: '240px', // Reduced from 320px to show exactly 4 steps
minHeight: '200px',
overflowY: 'auto',
paddingRight: '8px',
scrollbarWidth: 'thin',
scrollbarColor: '#888 #f1f1f1'
}}
className="custom-scrollbar"
>
{phaseSteps.length === 0 ? (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
padding: '12px 16px',
backgroundColor: '#f9fafb',
borderRadius: '8px',
border: '1px solid #d1d5db',
boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
}}
>
<div style={{ display: 'flex', alignItems: 'center', width: '24px' }}>
<CircleCheck
strokeWidth="2.5px"
color="#203474"
size="16px"
/>
</div>
<div
style={{
flex: 1,
fontSize: "14px",
color: "#666666",
textAlign: "left",
fontStyle: "italic"
}}
>
Waiting for migration process to start...
</div>
</div>
) : (
phaseSteps.map((step, index) => (
<div
key={index}
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
padding: '12px 16px',
backgroundColor: step.includes('✅') ? '#f0f9f0' : '#f9fafb',
borderRadius: '8px',
border: step.includes('✅') ? '1px solid #10b981' : '1px solid #d1d5db',
boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
animation: 'fadeIn 0.5s ease-in-out',
}}
>
<div style={{ display: 'flex', alignItems: 'center', width: '24px' }}>
<CircleCheck
strokeWidth="2.5px"
color={step.includes('✅') ? "#10b981" : "#203474"}
size="16px"
/>
</div>
<div
style={{
flex: 1,
fontSize: "14px",
color: "#000000",
textAlign: "left",
}}
>
{step}
</div>
</div>
))
)}
</div>
</div>
</div>
</main>
{/* Side Panel - Same as Landing Page */}
{isPanelOpen && (
<div
style={{
position: "fixed",
top: "60px",
right: 0,
height: "calc(100vh - 60px)",
width: "clamp(260px, 20vw, 320px)", // Responsive width
zIndex: 1050,
background: "white",
overflowY: "auto",
}}
>
<PanelRight panelWidth={300} panelResize={true} panelType={"first"} >
<PanelRightToolbar panelTitle="Batch history" panelIcon={<History />} handleDismiss={handleTogglePanel} />
<BatchHistoryPanel isOpen={isPanelOpen} onClose={() => dispatch(closePanel())} />
</PanelRight>
</div>
)}
{/* Progress Modal */}
<ProgressModal
open={showProgressModal}
setOpen={setShowProgressModal}
title="Processing Container Migration"
currentPhase={currentPhase}
phaseSteps={phaseSteps}
apiData={apiData}
onCancel={handleCancelProcessing}
showCancelButton={true}
processingCompleted={processingCompleted}
migrationError={migrationError}
onNavigateHome={handleNavigateHome}
/>
</div>
</>
);
};
export default ProcessPage;