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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useTraceUploader } from '@/hooks/useTraceUploader';
import { useAgentStore } from '@/stores/agentStore';
import { AgentStep, AgentTrace, AgentTraceMetadata, FinalStep } from '@/types/agent';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import AddIcon from '@mui/icons-material/Add';
import AssignmentIcon from '@mui/icons-material/Assignment';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import FormatListNumberedIcon from '@mui/icons-material/FormatListNumbered';
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty';
import InputIcon from '@mui/icons-material/Input';
import OutputIcon from '@mui/icons-material/Output';
import SmartToyIcon from '@mui/icons-material/SmartToy';
import StopCircleIcon from '@mui/icons-material/StopCircle';
import ThumbDownIcon from '@mui/icons-material/ThumbDown';
import ThumbUpIcon from '@mui/icons-material/ThumbUp';
import { Alert, Box, Button, Divider, IconButton, Paper, Tooltip, Typography } from '@mui/material';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { DownloadGifButton } from './DownloadGifButton';
import { DownloadJsonButton } from './DownloadJsonButton';

interface CompletionViewProps {
  finalStep: FinalStep;
  trace?: AgentTrace;
  steps?: AgentStep[];
  metadata?: AgentTraceMetadata;
  finalAnswer?: string | null;
  isGenerating: boolean;
  gifError: string | null;
  onGenerateGif: () => void;
  onDownloadJson: () => void;
  onBackToHome: () => void;
}

/**

 * Component displaying the completion status (success or failure) of a task

 */
export const CompletionView: React.FC<CompletionViewProps> = ({

  finalStep,

  trace,

  steps,

  metadata,

  finalAnswer,

  isGenerating,

  gifError,

  onGenerateGif,

  onDownloadJson,

  onBackToHome,

}) => {
  const updateTraceEvaluationInStore = useAgentStore((state) => state.updateTraceEvaluation);
  const [evaluation, setEvaluation] = useState<'success' | 'failed' | 'not_evaluated'>(
    finalStep.metadata.user_evaluation || 'not_evaluated'
  );
  const [isVoting, setIsVoting] = useState(false);
  
  // Use refs to always have fresh values for the upload callback
  const traceRef = useRef(trace);
  const stepsRef = useRef(steps || []);
  const metadataRef = useRef(metadata || finalStep.metadata);
  const finalStepRef = useRef(finalStep);
  
  // Keep refs updated
  useEffect(() => {
    traceRef.current = trace;
    stepsRef.current = steps || [];
    metadataRef.current = metadata || finalStep.metadata;
    finalStepRef.current = finalStep;
  }, [trace, steps, metadata, finalStep]);
  
  // Hook for uploading traces to Modal - uses callback to get fresh data
  const { uploadTrace, isUploading, uploadError, uploadSuccess } = useTraceUploader({
    getTraceData: useCallback(() => ({
      trace: traceRef.current,
      steps: stepsRef.current,
      metadata: metadataRef.current,
      finalStep: finalStepRef.current,
    }), []),
  });

  // Note: Auto-upload on task completion is now handled by useAgentWebSocket
  // This component only handles re-uploads when user provides evaluation

  const handleTraceEvaluation = async (vote: 'success' | 'failed') => {
    if (isVoting || !trace?.id) return;

    const newEvaluation = evaluation === vote ? 'not_evaluated' : vote;
    setIsVoting(true);

    try {
      setEvaluation(newEvaluation);
      // Update the store so the evaluation is reflected in the trace data
      updateTraceEvaluationInStore(newEvaluation);
      
      // Force re-upload the full trace with evaluation included
      // The Modal storage will overwrite the existing trace with the same ID
      // Use a slight delay to ensure store is updated
      setTimeout(() => {
        uploadTrace(true); // forceUpload=true to always upload with new evaluation
      }, 100);
    } catch (error) {
      console.error('Failed to update trace evaluation:', error);
    } finally {
      setIsVoting(false);
    }
  };

  const getStatusConfig = () => {
    switch (finalStep.type) {
      case 'success':
        return {
          icon: <CheckIcon sx={{ fontSize: 28 }} />,
          title: 'Task Completed Successfully!',
          color: 'success.main',
        };
      case 'stopped':
        return {
          icon: <StopCircleIcon sx={{ fontSize: 28 }} />,
          title: 'Task Stopped',
          color: 'warning.main',
        };
      case 'max_steps_reached':
        return {
          icon: <HourglassEmptyIcon sx={{ fontSize: 28 }} />,
          title: 'Maximum Steps Reached',
          color: 'warning.main',
        };
      case 'sandbox_timeout':
        return {
          icon: <AccessTimeIcon sx={{ fontSize: 28 }} />,
          title: 'Max Sandbox Time Reached',
          color: 'error.main',
        };
      case 'failure':
      default:
        return {
          icon: <CloseIcon sx={{ fontSize: 28 }} />,
          title: 'Task Failed (Agent Internal Error)',
          color: 'error.main',
        };
    }
  };

  const statusConfig = getStatusConfig();

  // Format model name for display
  const formatModelName = (modelId: string) => {
    const parts = modelId.split('/');
    return parts.length > 1 ? parts[1] : modelId;
  };

  return (
    <Box

      sx={{

        width: '100%',

        maxWidth: 600,

        mx: 'auto',

        p: 2,

        display: 'flex',

        flexDirection: 'column',

        gap: 1.5,

      }}

    >

      {/* Status Header - Compact */}

      <Box sx={{ textAlign: 'center', mb: 0.5 }}>

        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 1.5, mb: 0.75 }}>

          <Box

            sx={{

              width: 40,

              height: 40,

              borderRadius: '50%',

              backgroundColor: statusConfig.color,

              display: 'flex',

              alignItems: 'center',

              justifyContent: 'center',

              boxShadow: (theme) => {

                const rgba = finalStep.type === 'success'

                  ? '102, 187, 106'

                  : (finalStep.type === 'failure' || finalStep.type === 'sandbox_timeout')

                    ? '244, 67, 54'

                    : '255, 152, 0';

                return `0 2px 8px ${theme.palette.mode === 'dark' ? `rgba(${rgba}, 0.3)` : `rgba(${rgba}, 0.2)`}`;

              },

            }}

          >

            {React.cloneElement(statusConfig.icon, { sx: { fontSize: 24, color: 'white' } })}

          </Box>

          <Typography

            variant="h6"

            sx={{

              fontWeight: 700,

              color: statusConfig.color,

              fontSize: '1.1rem',

              letterSpacing: '-0.5px',

            }}

          >

            {statusConfig.title}

          </Typography>

        </Box>

      </Box>



      {/* Single Report Box - Task + Agent + Response + Metrics */}

      <Paper

        elevation={0}

        sx={{

          p: 2.5,

          backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.03)',

          borderRadius: 1.5,

          border: '1px solid',

          borderColor: 'divider',

        }}

      >

        {/* Task */}

        {trace?.instruction && (

          <Box sx={{ mb: 2 }}>

            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5 }}>

              <AssignmentIcon sx={{ fontSize: 18, color: 'text.secondary', mt: 0.25, flexShrink: 0 }} />

              <Box sx={{ flex: 1, minWidth: 0 }}>

                <Typography

                  variant="caption"

                  sx={{

                    fontWeight: 700,

                    color: 'text.secondary',

                    fontSize: '0.7rem',

                    textTransform: 'uppercase',

                    letterSpacing: '0.5px',

                    display: 'block',

                    mb: 0.5,

                  }}

                >

                  Task

                </Typography>

                <Typography

                  variant="body2"

                  sx={{

                    color: 'text.primary',

                    fontWeight: 700,

                    lineHeight: 1.5,

                    fontSize: '0.85rem',

                  }}

                >

                  {trace.instruction}

                </Typography>

              </Box>

            </Box>

          </Box>

        )}



        {/* Agent Response */}

        {finalAnswer && (

          <Box sx={{ mb: 2 }}>

            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5 }}>

              <ChatBubbleOutlineIcon

                sx={{

                  fontSize: 18,

                  color: 'text.secondary',

                  mt: 0.25,

                  flexShrink: 0

                }}

              />

              <Box sx={{ flex: 1, minWidth: 0 }}>

                <Typography

                  variant="caption"

                  sx={{

                    fontWeight: 700,

                    color: 'text.secondary',

                    fontSize: '0.7rem',

                    textTransform: 'uppercase',

                    letterSpacing: '0.5px',

                    display: 'block',

                    mb: 0.75,

                  }}

                >

                  Agent Response

                </Typography>

                <Typography

                  variant="body2"

                  sx={{

                    color: 'text.primary',

                    lineHeight: 1.5,

                    fontSize: '0.85rem',

                    whiteSpace: 'pre-wrap',

                    wordBreak: 'break-word',

                  }}

                >

                  {finalAnswer}

                </Typography>

              </Box>

            </Box>

          </Box>

        )}



        {/* Trace Evaluation */}

        <Box sx={{ mb: 2 }}>

          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>

            <Typography

              variant="caption"

              sx={{

                fontWeight: 700,

                color: 'text.secondary',

                fontSize: '0.7rem',

                textTransform: 'uppercase',

                letterSpacing: '0.5px',

              }}

            >

              Was this task completed successfully?

            </Typography>



            {/* Evaluation buttons */}

            <Box sx={{ display: 'flex', gap: 1 }}>

              <Tooltip title={evaluation === 'success' ? 'Remove success rating' : 'Mark as successful'}>

                <IconButton

                  size="small"

                  onClick={() => handleTraceEvaluation('success')}

                  disabled={isVoting}

                  sx={{

                    padding: '4px',

                    color: evaluation === 'success' ? 'success.main' : 'action.disabled',

                    '&:hover': {

                      color: 'success.main',

                      backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'rgba(102, 187, 106, 0.1)' : 'rgba(102, 187, 106, 0.08)',

                    },

                  }}

                >

                  <ThumbUpIcon sx={{ fontSize: 18 }} />

                </IconButton>

              </Tooltip>

              <Tooltip title={evaluation === 'failed' ? 'Remove failure rating' : 'Mark as failed'}>

                <IconButton

                  size="small"

                  onClick={() => handleTraceEvaluation('failed')}

                  disabled={isVoting}

                  sx={{

                    padding: '4px',

                    color: evaluation === 'failed' ? 'error.main' : 'action.disabled',

                    '&:hover': {

                      color: 'error.main',

                      backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'rgba(244, 67, 54, 0.1)' : 'rgba(244, 67, 54, 0.08)',

                    },

                  }}

                >

                  <ThumbDownIcon sx={{ fontSize: 18 }} />

                </IconButton>

              </Tooltip>

            </Box>

          </Box>

        </Box>



        {/* Divider before metrics */}

        <Divider sx={{ my: 2 }} />



        {/* Metrics */}

        <Box

          sx={{

            display: 'flex',

            alignItems: 'center',

            gap: 1.5,

            flexWrap: 'wrap',

            justifyContent: 'center',

          }}

        >

          {/* Agent */}

          {trace?.modelId && (

            <>

              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>

                <SmartToyIcon sx={{ fontSize: '0.85rem', color: 'primary.main' }} />

                <Typography

                  variant="caption"

                  sx={{

                    color: 'text.primary',

                    fontFamily: 'monospace',

                    fontSize: '0.75rem',

                    fontWeight: 700,

                  }}

                >

                  {formatModelName(trace.modelId)}

                </Typography>

              </Box>



              {/* Divider */}

              <Box sx={{ width: '1px', height: 16, backgroundColor: 'divider' }} />

            </>

          )}



          {/* Steps Count */}

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>

            <FormatListNumberedIcon sx={{ fontSize: '0.85rem', color: 'primary.main' }} />

            <Typography

              variant="caption"

              sx={{

                fontSize: '0.75rem',

                fontWeight: 700,

                color: 'text.primary',

                mr: 0.5,

              }}

            >

              {finalStep.metadata.numberOfSteps}

            </Typography>

            <Typography

              variant="caption"

              sx={{

                fontSize: '0.7rem',

                fontWeight: 400,

                color: 'text.secondary',

              }}

            >

              {finalStep.metadata.numberOfSteps === 1 ? 'Step' : 'Steps'}

            </Typography>

          </Box>



          {/* Divider */}

          <Box sx={{ width: '1px', height: 16, backgroundColor: 'divider' }} />



          {/* Duration */}

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>

            <AccessTimeIcon sx={{ fontSize: '0.85rem', color: 'primary.main' }} />

            <Typography

              variant="caption"

              sx={{

                fontSize: '0.75rem',

                fontWeight: 700,

                color: 'text.primary',

              }}

            >

              {finalStep.metadata.duration.toFixed(1)}s

            </Typography>

          </Box>



          {/* Divider */}

          <Box sx={{ width: '1px', height: 16, backgroundColor: 'divider' }} />



          {/* Input Tokens */}

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>

            <InputIcon sx={{ fontSize: '0.85rem', color: 'primary.main' }} />

            <Typography

              variant="caption"

              sx={{

                fontSize: '0.75rem',

                fontWeight: 700,

                color: 'text.primary',

              }}

            >

              {finalStep.metadata.inputTokensUsed.toLocaleString()}

            </Typography>

          </Box>



          {/* Divider */}

          <Box sx={{ width: '1px', height: 16, backgroundColor: 'divider' }} />



          {/* Output Tokens */}

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>

            <OutputIcon sx={{ fontSize: '0.85rem', color: 'primary.main' }} />

            <Typography

              variant="caption"

              sx={{

                fontSize: '0.75rem',

                fontWeight: 700,

                color: 'text.primary',

              }}

            >

              {finalStep.metadata.outputTokensUsed.toLocaleString()}

            </Typography>

          </Box>

        </Box>

      </Paper>

      {/* GIF Error Alert */}
      {gifError && (
        <Alert severity="error" sx={{ fontSize: '0.72rem', py: 0.5 }}>

          {gifError}

        </Alert>
      )}

      {/* Action Buttons */}
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          gap: 1.5,
          alignItems: 'center',
        }}
      >
        {/* Download buttons */}
        <Box
          sx={{
            display: 'flex',
            gap: 1,
            justifyContent: 'center',
            flexWrap: 'wrap',
          }}
        >
          <DownloadGifButton

            isGenerating={isGenerating}

            onClick={onGenerateGif}

            disabled={!steps || steps.length === 0}

          />
          <DownloadJsonButton onClick={onDownloadJson} disabled={!trace} />
        </Box>

        {/* New Task button - larger and below */}
        <Button
          variant="contained"
          startIcon={<AddIcon sx={{ fontSize: 20 }} />}
          onClick={onBackToHome}
          color="primary"
          sx={{
            textTransform: 'none',
            fontWeight: 700,
            fontSize: '0.9rem',
            px: 3,
            py: 1,
            boxShadow: 2,
            minWidth: 200,
            '&:hover': {
              boxShadow: 4,
            },
          }}
        >
          New Task
        </Button>
      </Box>
    </Box>
  );
};