File size: 23,722 Bytes
3f78860
 
1e24842
3f78860
 
1e24842
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
3f78860
 
8085285
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
1e24842
3f78860
1e24842
 
3f78860
 
 
1e24842
3f78860
 
8085285
1e24842
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f78860
 
1e24842
3f78860
 
1e24842
3f78860
 
 
1e24842
3f78860
f1c3c6d
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c3c6d
 
 
 
 
3f78860
1e24842
 
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
 
3f78860
 
 
 
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c3c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
1e24842
3f78860
 
 
1e24842
3f78860
 
1e24842
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
1e24842
 
3f78860
 
1e24842
 
3f78860
 
 
1e24842
3f78860
 
1e24842
 
 
 
 
 
8085285
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
3f78860
 
 
 
1e24842
 
 
 
 
 
 
3f78860
 
 
1e24842
 
 
f1c3c6d
1e24842
 
3f78860
 
 
 
1e24842
 
 
 
 
 
 
8085285
 
 
 
 
 
1e24842
3f78860
 
1e24842
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
3f78860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ChevronRight, Bot, Database, Terminal, Layers, Download } from 'lucide-react';
import { useAppContext } from '../components/AppContext';
import ChatAssistant from '../components/ChatAssistant';
import ScenarioComposer from '../components/workflow/ScenarioComposer';
import PlanHeader from '../components/workflow/PlanHeader';
import StepCard from '../components/workflow/StepCard';
import ContextPanel from '../components/workflow/ContextPanel';
import OtpModal from '../components/workflow/OtpModal';
import SelectionModal from '../components/workflow/SelectionModal';
import { PlanService, SessionService, SpecService } from '../services/api';

export default function WorkflowPage() {
  const navigate = useNavigate();
  const {
    activeSpecId, activeSpecName, activeBaseUrl, setActiveBaseUrl,
    storedCredentials, setStoredCredentials, saveProfile, parsedSpec,
    sessionContextVars, refreshSessionContext, sessionId,
    executionPlan, setExecutionPlan,
    scenario, setScenario,
    startNewSession,
    addToast,
  } = useAppContext();

  const [isPlanning, setIsPlanning] = useState(false);
  const [planningStatus, setPlanningStatus] = useState('');
  const [executingStep, setExecutingStep] = useState(null);
  const [isRunningAll, setIsRunningAll] = useState(false);
  const [stepResults, setStepResults] = useState(() => {
    try { const v = sessionStorage.getItem('wf_stepResults'); return v ? JSON.parse(v) : {}; } catch { return {}; }
  });
  React.useEffect(() => {
    try { sessionStorage.setItem('wf_stepResults', JSON.stringify(stepResults)); } catch {}
  }, [stepResults]);

  const [otpPrompt, setOtpPrompt] = useState(null);
  const [otpInput, setOtpInput] = useState('');
  const [selectionPrompt, setSelectionPrompt] = useState(null);
  const [planTokenUsage, setPlanTokenUsage] = useState(null);
  const [totalScenarioTokens, setTotalScenarioTokens] = useState({ prompt: 0, completion: 0, total: 0 });
  const [rightPanelOpen, setRightPanelOpen] = useState(true);
  const [rightPanelMode, setRightPanelMode] = useState('context');

  /* ── Plan generation ───────────────────────────────────────── */
  const handleGeneratePlan = async () => {
    if (!activeSpecId) { addToast('warning', 'Please select a spec first.'); return; }
    if (!activeBaseUrl) { addToast('warning', 'Please set a Base URL.'); return; }
    if (!scenario.trim()) { addToast('warning', 'Please describe a test scenario.'); return; }

    setIsPlanning(true);
    setPlanningStatus('Starting…');
    setPlanTokenUsage(null);
    setStepResults({});
    try { sessionStorage.removeItem('wf_stepResults'); } catch {}
    setExecutionPlan([]);
    setTotalScenarioTokens({ prompt: 0, completion: 0, total: 0 });

    try {
      const newSid = await startNewSession();
      if (!newSid) throw new Error('Could not initialize fresh session');

      const payload = {
        spec_content: typeof parsedSpec === 'string' ? parsedSpec : JSON.stringify(parsedSpec),
        base_url: activeBaseUrl,
        scenario,
        user_credentials: storedCredentials,
        spec_id: activeSpecId,
        session_id: newSid,
      };

      await PlanService.streamPlan(payload, {
        onStatus: (msg) => setPlanningStatus(msg),
        onStep: (step) => {
          setExecutionPlan(prev => [...(prev || []), step]);
        },
        onComplete: (data) => {
          if (data.suggested_credentials && Object.keys(data.suggested_credentials).length > 0) {
            setStoredCredentials(prev => ({ ...prev, ...data.suggested_credentials }));
          }
          if (data.token_usage) {
            setPlanTokenUsage(data.token_usage);
            setTotalScenarioTokens({
              prompt: data.token_usage.prompt_tokens,
              completion: data.token_usage.completion_tokens,
              total: data.token_usage.total_tokens,
            });
          }
        },
        onError: (msg) => { throw new Error(msg); },
      });
    } catch (err) {
      addToast('error', err.message || 'Plan generation failed.');
      setExecutionPlan(null);
    } finally {
      setIsPlanning(false);
      setPlanningStatus('');
    }
  };

  /* ── Step execution ────────────────────────────────────────── */
  const executeStep = async (stepDef) => {
    const requiredKeys = stepDef.required_context_keys || [];
    const missingKeys = requiredKeys.filter(key => !sessionContextVars[key]);
    if (missingKeys.length > 0) {
      setSelectionPrompt({ type: 'manual_input', step: stepDef, missingKeys });
      return;
    }

    setExecutingStep(stepDef.step);
    try {
      if (!sessionId) { addToast('error', 'Session not initialized. Please refresh.'); return; }
      if (!activeBaseUrl) { addToast('warning', 'Base URL is missing.'); return; }

      await refreshSessionContext();
      const payload = {
        session_id: sessionId,
        step_definition: stepDef,
        context_variables: sessionContextVars || {},
        user_credentials: storedCredentials || {},
        base_url: activeBaseUrl,
        spec_id: activeSpecId,
      };
      const execData = await PlanService.executeStep(payload);

      setStepResults(prev => ({
        ...prev,
        [stepDef.step]: {
          request: execData.executed_request,
          response: execData.response,
          analysis: { status: 'pending', response_summary: 'Analyzing response with AI…' },
          token_usage: execData.token_usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
        },
      }));

      const analyzePayload = {
        session_id: sessionId,
        step: stepDef.step,
        response_data: execData.response,
        step_definition: stepDef,
      };
      const analyzeData = await PlanService.analyzeResponse(analyzePayload);

      const stepTokens = {
        prompt_tokens: (execData.token_usage?.prompt_tokens || 0) + (analyzeData.token_usage?.prompt_tokens || 0),
        completion_tokens: (execData.token_usage?.completion_tokens || 0) + (analyzeData.token_usage?.completion_tokens || 0),
        total_tokens: (execData.token_usage?.total_tokens || 0) + (analyzeData.token_usage?.total_tokens || 0),
      };

      setStepResults(prev => ({
        ...prev,
        [stepDef.step]: { ...prev[stepDef.step], analysis: analyzeData, token_usage: stepTokens },
      }));

      setTotalScenarioTokens(prev => ({
        prompt: prev.prompt + stepTokens.prompt_tokens,
        completion: prev.completion + stepTokens.completion_tokens,
        total: prev.total + stepTokens.total_tokens,
      }));

      await refreshSessionContext();

      if (analyzeData.is_otp_required) {
        setOtpPrompt({ stepDef, otpFieldName: analyzeData.otp_field_name || 'otp' });
      }
      if (analyzeData.is_selection_required && analyzeData.selection_options?.length > 0) {
        setSelectionPrompt({
          stepDef,
          fieldName: analyzeData.selection_field_name || 'selected_item',
          options: analyzeData.selection_options,
          responseBody: execData.response.body,
        });
      }
    } catch (err) {
      if (err.response?.data?.error === 'missing_context_keys') {
        const missing = err.response.data.missing_keys || [];
        setSelectionPrompt({ type: 'manual_input', step: stepDef, missingKeys: missing });
        return;
      }
      console.error(`Execution failed for step ${stepDef.step}`, err);
      addToast('error', `Step ${stepDef.step} failed: ${err.message}`);
      setStepResults(prev => ({
        ...prev,
        [stepDef.step]: {
          ...prev[stepDef.step],
          analysis: { status: 'failed', response_summary: err.message },
        },
      }));
    } finally {
      setExecutingStep(null);
    }
  };

  const runAllSteps = async () => {
    if (!executionPlan?.length) return;
    setIsRunningAll(true);
    for (const step of executionPlan) {
      if (otpPrompt || selectionPrompt) break;
      await executeStep(step);
      const failed = await new Promise(resolve => {
        setStepResults(prev => {
          resolve(prev[step.step]?.analysis?.status === 'failed');
          return prev;
        });
      });
      if (failed) {
        addToast('warning', `Stopped at step ${step.step} β€” step failed.`);
        break;
      }
    }
    setIsRunningAll(false);
  };

  const exportAsPostman = () => {
    if (!executionPlan?.length) return;
    const collection = {
      info: {
        name: activeSpecName || 'API Test Plan',
        schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
      },
      item: executionPlan.map(step => {
        const parts = (step.endpoint || '').split(' ');
        const method = parts.length >= 2 ? parts[0].toUpperCase() : 'GET';
        const rawPath = parts.length >= 2 ? parts.slice(1).join(' ') : parts[0];
        const url = rawPath.startsWith('http') ? rawPath : `${activeBaseUrl || '{{baseUrl}}'}${rawPath}`;
        const res = stepResults[step.step];
        const requestBody = res?.request?.body;

        return {
          name: `Step ${step.step}: ${step.purpose || step.endpoint}`,
          request: {
            method,
            header: Object.entries(res?.request?.headers || {}).map(([key, value]) => ({ key, value })),
            url: { raw: url },
            body: requestBody
              ? { mode: 'raw', raw: typeof requestBody === 'string' ? requestBody : JSON.stringify(requestBody, null, 2), options: { raw: { language: 'json' } } }
              : undefined,
            description: step.purpose || '',
          },
          response: res?.response?.body
            ? [{
                name: `${res.response.status_code} response`,
                status: String(res.response.status_code),
                code: res.response.status_code,
                body: typeof res.response.body === 'string' ? res.response.body : JSON.stringify(res.response.body),
              }]
            : [],
        };
      }),
      variable: [{ key: 'baseUrl', value: activeBaseUrl || '' }],
    };

    const blob = new Blob([JSON.stringify(collection, null, 2)], { type: 'application/json' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${(activeSpecName || 'plan').replace(/\s+/g, '_')}_postman_collection.json`;
    link.click();
    URL.revokeObjectURL(link.href);
    addToast('success', 'Postman collection exported.');
  };

  const handleOtpSubmit = async () => {
    if (!otpInput.trim()) return;
    const { otpFieldName } = otpPrompt;
    try {
      await saveProfile({ extra: { [otpFieldName]: otpInput } });
      setOtpPrompt(null);
      setOtpInput('');
      await refreshSessionContext();
      addToast('success', `OTP "${otpInput}" saved as "${otpFieldName}".`);
    } catch {
      addToast('error', 'Failed to save OTP.');
    }
  };

  const handleManualInputConfirm = async (values) => {
    if (!selectionPrompt) return;
    try {
      for (const [key, value] of Object.entries(values)) {
        await SessionService.updateContext(sessionId, key, value);
      }
      const stepToRetry = selectionPrompt.step;
      setSelectionPrompt(null);
      await refreshSessionContext();
      await executeStep(stepToRetry);
    } catch {
      addToast('error', 'Failed to save context values.');
    }
  };

  const handleSelectionSubmit = async (option) => {
    if (!selectionPrompt) return;
    try {
      await SessionService.updateContext(sessionId, selectionPrompt.fieldName, option.value);
      setSelectionPrompt(null);
      await refreshSessionContext();
    } catch {
      addToast('error', 'Failed to save selection.');
    }
  };

  /* ── Layout ─────────────────────────────────────────────────── */
  return (
    <div style={{ display: 'flex', flex: 1, minHeight: 0, overflow: 'hidden', position: 'relative' }}>

      {/* ── Content column ─────────────────────────────────────── */}
      <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, overflow: 'hidden' }}>

        {/* Token strip + Base URL bar */}
        {activeSpecId && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, padding: '0 24px',
            height: 40, flexShrink: 0, borderBottom: '1px solid var(--line-1)',
            background: 'var(--bg-1)',
          }}>
            {planTokenUsage && (
              <span className="tokstrip">
                <span className="dot"/>plan <b>{planTokenUsage.total_tokens?.toLocaleString()}</b>
              </span>
            )}
            {totalScenarioTokens.total > 0 && (
              <span className="tokstrip">
                <span className="dot" style={{ background: 'var(--ok)' }}/>
                total <b>{totalScenarioTokens.total.toLocaleString()}</b>
              </span>
            )}
            <div style={{ flex: 1 }}/>
            <div className="url-input">
              <span className="label">base</span>
              <input
                value={activeBaseUrl || ''}
                onChange={e => setActiveBaseUrl(e.target.value)}
                onBlur={async () => {
                  if (activeBaseUrl) {
                    try { await SpecService.updateBaseUrl(activeSpecId, activeBaseUrl); }
                    catch (e) { console.error('URL save failed', e); }
                  }
                }}
                placeholder="https://api.example.com"
                spellCheck={false}
              />
            </div>
          </div>
        )}

        {/* Scrollable plan area */}
        <div style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ maxWidth: 900, margin: '0 auto', padding: '32px 32px 24px' }}>

            {/* Streaming status while planning */}
            {isPlanning && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 0', marginBottom: 8, borderBottom: '1px solid var(--line-1)' }}>
                <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid var(--line-2)', borderTopColor: 'var(--accent)', animation: 'spin 0.8s linear infinite', flexShrink: 0 }}/>
                <span style={{ fontSize: 12, color: 'var(--fg-2)' }}>{planningStatus || 'Generating plan…'}</span>
              </div>
            )}

            {(!executionPlan || (executionPlan.length === 0 && !isPlanning)) && !isPlanning ? (
              /* ── Empty state ── */
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '55vh', textAlign: 'center' }}>
                <div style={{ padding: '20px', borderRadius: 12, background: 'var(--bg-2)', border: '1px solid var(--line-2)', marginBottom: 28 }}>
                  <Terminal size={36} style={{ color: 'var(--accent)' }} strokeWidth={1.5}/>
                </div>
                <div className="h-eyebrow" style={{ marginBottom: 8 }}>Workflow Studio</div>
                <h1 style={{ fontSize: 22, fontWeight: 600, color: 'var(--fg-0)', letterSpacing: '-0.01em', margin: '0 0 10px' }}>
                  AI-Powered API Testing
                </h1>
                <p style={{ fontSize: 12.5, color: 'var(--fg-2)', maxWidth: 420, lineHeight: 1.65, margin: 0 }}>
                  {activeSpecId
                    ? 'Describe a test scenario below and the AI will generate a complete execution plan for your API.'
                    : 'Start by loading a spec from the sidebar.'}
                </p>
                {!activeSpecId && (
                  <button onClick={() => navigate('/specs')} className="btn" style={{ marginTop: 24, gap: 8 }}>
                    <Layers size={13}/> Browse Specs
                  </button>
                )}
              </div>
            ) : executionPlan && executionPlan.length > 0 && (
              /* ── Execution plan ── */
              <div>
                <PlanHeader
                  executionPlan={executionPlan}
                  stepResults={stepResults}
                  isRunningAll={isRunningAll}
                  executingStep={executingStep}
                  onRunAll={runAllSteps}
                  onReset={() => { setExecutionPlan(null); setStepResults({}); try { sessionStorage.removeItem('wf_stepResults'); } catch {} }}
                  onExport={exportAsPostman}
                />

                {executionPlan.map(step => (
                  <StepCard
                    key={step.step}
                    step={step}
                    isRunning={executingStep === step.step}
                    isRunningAll={isRunningAll}
                    res={stepResults[step.step]}
                    onExecute={executeStep}
                  />
                ))}
              </div>
            )}

            {otpPrompt && (
              <OtpModal
                otpPrompt={otpPrompt}
                otpInput={otpInput}
                setOtpInput={setOtpInput}
                onSubmit={handleOtpSubmit}
                onCancel={() => setOtpPrompt(null)}
              />
            )}

            {selectionPrompt && (
              <SelectionModal
                selectionPrompt={selectionPrompt}
                onSelect={handleSelectionSubmit}
                onConfirm={handleManualInputConfirm}
                onCancel={() => setSelectionPrompt(null)}
              />
            )}
          </div>
        </div>

        <ScenarioComposer
          scenario={scenario}
          setScenario={setScenario}
          activeSpecId={activeSpecId}
          activeSpecName={activeSpecName}
          isPlanning={isPlanning}
          onGenerate={handleGeneratePlan}
          hasPlan={!!executionPlan?.length}
          onNewPlan={() => {
            setExecutionPlan(null);
            setStepResults({});
            try { sessionStorage.removeItem('wf_stepResults'); } catch {}
          }}
        />
      </div>

      {/* ── Right context panel ─────────────────────────────────── */}
      <aside style={{
        display: 'flex',
        flexShrink: 0,
        background: 'var(--bg-1)',
        borderLeft: '1px solid var(--line-1)',
        transition: 'width 280ms ease',
        width: rightPanelOpen ? (rightPanelMode === 'chat' ? 360 : 300) : 0,
        overflow: 'hidden',
      }}>
        <div style={{ width: rightPanelMode === 'chat' ? 360 : 300, height: '100%', display: 'flex', flexDirection: 'column', flexShrink: 0 }}>

          {/* Panel tab header */}
          <div style={{ height: 48, display: 'flex', alignItems: 'center', borderBottom: '1px solid var(--line-1)', padding: '0 8px', gap: 4, flexShrink: 0 }}>
            <div style={{ display: 'flex', flex: 1, background: 'var(--bg-2)', borderRadius: 4, padding: 2 }}>
              <button
                onClick={() => setRightPanelMode('context')}
                style={{
                  flex: 1, padding: '4px 8px', borderRadius: 3, border: 0,
                  fontSize: 10.5, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
                  background: rightPanelMode === 'context' ? 'var(--bg-0)' : 'transparent',
                  color: rightPanelMode === 'context' ? 'var(--fg-0)' : 'var(--fg-3)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                  transition: 'all 120ms', cursor: 'pointer',
                }}
              >
                <Database size={10}/> Context
              </button>
              <button
                onClick={() => setRightPanelMode('chat')}
                style={{
                  flex: 1, padding: '4px 8px', borderRadius: 3, border: 0,
                  fontSize: 10.5, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
                  background: rightPanelMode === 'chat' ? 'var(--bg-0)' : 'transparent',
                  color: rightPanelMode === 'chat' ? 'var(--accent)' : 'var(--fg-3)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                  transition: 'all 120ms', cursor: 'pointer',
                }}
              >
                <Bot size={10}/> AI
              </button>
            </div>
            <button onClick={() => setRightPanelOpen(false)} className="ico-btn" title="Collapse panel">
              <ChevronRight size={14}/>
            </button>
          </div>

          {/* Context panel */}
          {rightPanelMode === 'context' && (
            <ContextPanel
              sessionContextVars={sessionContextVars}
              storedCredentials={storedCredentials}
              onRefresh={refreshSessionContext}
            />
          )}

          {/* AI chat panel */}
          <div style={{ flex: 1, minHeight: 0, overflow: 'hidden', display: rightPanelMode === 'chat' ? 'flex' : 'none', flexDirection: 'column' }}>
            <ChatAssistant
              compact={true}
              allStepResultsProp={stepResults}
              lastStepResultProp={
                Object.keys(stepResults).length > 0
                  ? stepResults[Math.max(...Object.keys(stepResults).map(Number))]
                  : null
              }
              executeStepFromChat={async (stepDef, changes) => {
                const modifiedStep = changes && Object.keys(changes).length > 0
                  ? {
                      ...stepDef,
                      body: changes.body !== undefined ? { ...(stepDef.body || {}), ...changes.body } : stepDef.body,
                      query_params: changes.query_params !== undefined ? { ...(stepDef.query_params || {}), ...changes.query_params } : stepDef.query_params,
                      headers: changes.headers !== undefined ? { ...(stepDef.headers || {}), ...changes.headers } : stepDef.headers,
                      path_params: changes.path_params !== undefined ? { ...(stepDef.path_params || {}), ...changes.path_params } : stepDef.path_params,
                      ...Object.fromEntries(Object.entries(changes).filter(([k]) => !['body', 'query_params', 'headers', 'path_params'].includes(k)))
                    }
                  : stepDef;
                await executeStep(modifiedStep);
                return {
                  step_definition: modifiedStep,
                  response: stepResults[modifiedStep.step]?.response,
                  analysis: stepResults[modifiedStep.step]?.analysis,
                };
              }}
            />
          </div>
        </div>
      </aside>

      {/* Expand button when panel is collapsed */}
      {!rightPanelOpen && (
        <button
          onClick={() => setRightPanelOpen(true)}
          style={{
            position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)',
            zIndex: 20, padding: '6px 4px',
            background: 'var(--bg-1)', color: 'var(--fg-2)',
            border: '1px solid var(--line-2)', borderRight: 0,
            borderRadius: '4px 0 0 4px',
            transition: 'color 120ms', cursor: 'pointer',
          }}
          title="Open context panel"
        >
          <ChevronRight size={14} style={{ transform: 'rotate(180deg)' }}/>
        </button>
      )}
    </div>
  );
}