File size: 13,532 Bytes
7fcdb70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useGifGenerator } from '@/hooks/useGifGenerator';
import { useJsonExporter } from '@/hooks/useJsonExporter';
import { selectError, selectFinalStep, selectSteps, selectTrace, useAgentStore } from '@/stores/agentStore';
import { AgentStep, AgentTraceMetadata } from '@/types/agent';
import ImageIcon from '@mui/icons-material/Image';
import MonitorIcon from '@mui/icons-material/Monitor';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import { Box, Button, CircularProgress, keyframes, Typography } from '@mui/material';
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { CompletionView } from './completionview/CompletionView';

// Animation for live indicator
const livePulse = keyframes`

  0%, 100% {

    opacity: 1;

    transform: scale(1);

  }

  50% {

    opacity: 0.7;

    transform: scale(1.2);

  }

`;

interface SandboxViewerProps {
  vncUrl: string;
  isAgentProcessing?: boolean;
  metadata?: AgentTraceMetadata;
  traceStartTime?: Date;
  selectedStep?: AgentStep | null; // The step to display in time-travel mode
  isRunning?: boolean; // Is the agent currently running
}

export const SandboxViewer: React.FC<SandboxViewerProps> = ({

  vncUrl,

  isAgentProcessing = false,

  metadata,

  traceStartTime,

  selectedStep,

  isRunning = false

}) => {
  const navigate = useNavigate();
  const error = useAgentStore(selectError);
  const finalStep = useAgentStore(selectFinalStep);
  const steps = useAgentStore(selectSteps);
  const trace = useAgentStore(selectTrace);
  const resetAgent = useAgentStore((state) => state.resetAgent);
  const setSelectedStepIndex = useAgentStore((state) => state.setSelectedStepIndex);

  // Get the latest screenshot from steps (for non-VNC mode)
  const latestScreenshot = steps && steps.length > 0 ? steps[steps.length - 1].image : null;

  // Hook to generate GIF
  const { isGenerating, error: gifError, generateAndDownloadGif } = useGifGenerator({
    steps: steps || [],
    traceId: finalStep?.metadata.traceId || '',
  });

  // Hook to export JSON
  const { downloadTraceAsJson } = useJsonExporter({
    trace,
    steps: steps || [],
    metadata: finalStep?.metadata || metadata,
    finalStep,
  });

  // Extract final_answer from the last step, or fallback to last thought
  const getFinalAnswer = (): string | null => {
    console.log('πŸ” getFinalAnswer - steps:', steps);
    if (!steps || steps.length === 0) {
      console.log('❌ No steps available');
      return null;
    }

    // Try to find final_answer in any step (iterate backwards)
    for (let i = steps.length - 1; i >= 0; i--) {
      const step = steps[i];

      if (step.actions && Array.isArray(step.actions)) {
        const finalAnswerAction = step.actions.find(
          (action) => action.function_name === 'final_answer'
        );

        if (finalAnswerAction) {
          // Handle both named parameter and positional argument
          const result = finalAnswerAction?.parameters?.answer || finalAnswerAction?.parameters?.arg_0 || null;
          console.log('βœ… Final answer found in step', i + 1, ':', result);
          return result;
        }
      }
    }

    console.log('πŸ” No final_answer found, looking for last thought...');

    // Fallback: find the last step with a thought (iterate backwards)
    for (let i = steps.length - 1; i >= 0; i--) {
      const step = steps[i];
      if (step.thought) {
        console.log('πŸ“ Using thought from step', i + 1, 'as fallback:', step.thought);
        return step.thought;
      }
    }

    console.log('❌ No final answer or thought found in any step');
    return null;
  };

  const finalAnswer = getFinalAnswer();
  console.log('🎯 Final answer to display:', finalAnswer);

  // Determine if we should show success/fail status
  const showStatus = !isRunning && !selectedStep && finalStep;

  // Handler to go back to home
  const handleBackToHome = () => {
    // Reset frontend state
    useAgentStore.getState().resetAgent();

    // Reload the page to reconnect websocket
    window.location.href = '/';
  };

  // Handler to go back to live mode
  const handleGoLive = () => {
    setSelectedStepIndex(null);
  };

  return (
    <Box

      sx={{

        flex: '1 1 auto',

        display: 'flex',

        flexDirection: 'column',

        position: 'relative',

        border: '1px solid',

        borderColor: showStatus

          ? ((finalStep?.type === 'failure' || finalStep?.type === 'sandbox_timeout') ? 'error.main' : 'success.main')

          : ((vncUrl || isAgentProcessing) && !selectedStep && !showStatus ? 'primary.main' : 'divider'),

        borderRadius: '12px',

        backgroundColor: 'background.paper',

        transition: 'border 0.3s ease',

        overflow: 'hidden',

      }}

    >

      {/* Live Badge or Go Live Button */}

      {vncUrl && !showStatus && (

        <>

          {!selectedStep ? (

            // Live Badge when in live mode

            <Box

              sx={{

                position: 'absolute',

                top: 12,

                right: 12,

                zIndex: 10,

                display: 'flex',

                alignItems: 'center',

                gap: 1,

                px: 2,

                py: 1,

                backgroundColor: (theme) =>

                  theme.palette.mode === 'dark'

                    ? 'rgba(0, 0, 0, 0.7)'

                    : 'rgba(255, 255, 255, 0.9)',

                backdropFilter: 'blur(8px)',

                borderRadius: 0.75,

                border: '1px solid',

                borderColor: 'primary.main',

                boxShadow: (theme) =>

                  theme.palette.mode === 'dark'

                    ? '0 2px 8px rgba(0, 0, 0, 0.4)'

                    : '0 2px 8px rgba(0, 0, 0, 0.1)',

              }}

            >

              <Box

                sx={{

                  width: 10,

                  height: 10,

                  borderRadius: '50%',

                  backgroundColor: 'error.main',

                  animation: `${livePulse} 2s ease-in-out infinite`,

                }}

              />

              <Typography

                variant="caption"

                sx={{

                  fontSize: '0.8rem',

                  fontWeight: 700,

                  color: 'text.primary',

                  textTransform: 'uppercase',

                  letterSpacing: '0.5px',

                }}

              >

                Live

              </Typography>

            </Box>

          ) : (

            // Go Live Button when viewing a specific step

            <Button

              onClick={handleGoLive}

              startIcon={<PlayCircleIcon sx={{ fontSize: 20 }} />}

              sx={{

                position: 'absolute',

                top: 12,

                right: 12,

                zIndex: 10,

                px: 2,

                py: 1,

                backgroundColor: (theme) =>

                  theme.palette.mode === 'dark'

                    ? 'rgba(0, 0, 0, 0.7)'

                    : 'rgba(255, 255, 255, 0.9)',

                backdropFilter: 'blur(8px)',

                borderRadius: 0.75,

                border: '1px solid',

                borderColor: 'primary.main',

                boxShadow: (theme) =>

                  theme.palette.mode === 'dark'

                    ? '0 2px 8px rgba(0, 0, 0, 0.4)'

                    : '0 2px 8px rgba(0, 0, 0, 0.1)',

                fontSize: '0.8rem',

                fontWeight: 700,

                textTransform: 'uppercase',

                letterSpacing: '0.5px',

                color: 'primary.main',

                '&:hover': {

                  backgroundColor: (theme) =>

                    theme.palette.mode === 'dark'

                      ? 'rgba(0, 0, 0, 0.85)'

                      : 'rgba(255, 255, 255, 1)',

                  borderColor: 'primary.dark',

                },

              }}

            >

              Go Live

            </Button>

          )}

        </>
      )}

      <Box
        sx={{
          flex: 1,
          minHeight: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {showStatus && finalStep ? (
          // Show success/fail status when agent has completed
          <CompletionView

            finalStep={finalStep}

            trace={trace}

            steps={steps}

            metadata={metadata}

            finalAnswer={finalAnswer}

            isGenerating={isGenerating}

            gifError={gifError}

            onGenerateGif={generateAndDownloadGif}

            onDownloadJson={downloadTraceAsJson}

            onBackToHome={handleBackToHome}

          />
        ) : selectedStep ? (
          // Time-travel mode: Show screenshot of selected step
          <Box

            sx={{

              width: '100%',

              height: '100%',

              display: 'flex',

              alignItems: 'center',

              justifyContent: 'center',

              overflow: 'auto',

              backgroundColor: 'black',

              position: 'relative',

            }}

          >

            {selectedStep.image ? (

              <img

                src={selectedStep.image}

                alt="Step screenshot"

                style={{

                  maxWidth: '100%',

                  maxHeight: '100%',

                  objectFit: 'contain',

                }}

              />

            ) : (

              <Box

                sx={{

                  textAlign: 'center',

                  p: 4,

                  color: 'text.secondary',

                  width: '100%',

                  height: '100%',

                  display: 'flex',

                  flexDirection: 'column',

                  alignItems: 'center',

                  justifyContent: 'center',

                }}

              >

                <ImageIcon sx={{ fontSize: 48, mb: 2, opacity: 0.5 }} />

                <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5, fontSize: '0.875rem', color: 'text.primary' }}>

                  No screenshot available

                </Typography>

                <Typography variant="caption" sx={{ fontSize: '0.75rem', color: 'text.secondary' }}>

                  This step doesn't have a screenshot

                </Typography>

              </Box>

            )}

          </Box>
        ) : vncUrl ? (
          // Live mode: Show VNC stream
          <iframe

            src={vncUrl}

            style={{ width: '100%', height: '100%', border: 'none' }}

            title="OS Stream"

            lang="en"

          />
        ) : latestScreenshot ? (
          // Live mode without VNC: Show latest screenshot
          <Box

            sx={{

              width: '100%',

              height: '100%',

              display: 'flex',

              alignItems: 'center',

              justifyContent: 'center',

              overflow: 'auto',

              backgroundColor: 'black',

              position: 'relative',

            }}

          >

            <img

              src={latestScreenshot}

              alt="Latest screenshot"

              style={{

                maxWidth: '100%',

                maxHeight: '100%',

                objectFit: 'contain',

              }}

            />

          </Box>
        ) : isAgentProcessing ? (
          // Loading state
          <Box

            sx={{

              textAlign: 'center',

              p: 4,

              color: 'text.secondary',

              width: '100%',

              height: '100%',

              display: 'flex',

              flexDirection: 'column',

              alignItems: 'center',

              justifyContent: 'center',

            }}

          >

            <CircularProgress

              size={48}

              sx={{

                mb: 2,

                color: 'primary.main'

              }}

            />

            <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5, fontSize: '0.875rem', color: 'text.primary' }}>

              Starting FARA Agent...

            </Typography>

            <Typography variant="caption" sx={{ fontSize: '0.75rem', color: 'text.secondary' }}>

              Initializing browser environment

            </Typography>

          </Box>
        ) : (
          // No stream available
          <Box

            sx={{

              textAlign: 'center',

              p: 4,

              color: 'text.secondary',

              width: '100%',

              height: '100%',

              display: 'flex',

              flexDirection: 'column',

              alignItems: 'center',

              justifyContent: 'center',

            }}

          >

            <MonitorIcon sx={{ fontSize: 48, mb: 2, opacity: 0.5 }} />

            <Typography variant="body2" sx={{ fontWeight: 600, mb: 0.5, fontSize: '0.875rem' }}>

              No stream available

            </Typography>

            <Typography variant="caption" sx={{ fontSize: '0.75rem', color: 'text.secondary' }}>

              Stream will appear when agent starts

            </Typography>

          </Box>
        )}
      </Box>
    </Box>
  );
};