earl 0.5.2

AI-safe CLI for AI agents
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
"use client";

import { AlertTriangle, Play, Square } from "lucide-react";
import {
  useCallback,
  useEffect,
  useMemo,
  useReducer,
  useRef,
  useState,
} from "react";
import { CliImport } from "@/components/cli-import";
import { CodeExamples } from "@/components/code-examples";
import { HistoryDrawer } from "@/components/history-drawer";
import { ParamForm } from "@/components/param-form";
import {
  extractBindErrorParam,
  isWriteConfirmationRequired,
  ResponseView,
} from "@/components/response-view";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";

import { useHistory } from "@/hooks/use-history";
import { ApiClientError, executeCommand, validateParams } from "@/lib/api";
import type {
  ApiError,
  ExecuteResponse,
  ExecutionState,
  HistoryEntry,
  Tool,
} from "@/lib/types";
import { cn } from "@/lib/utils";

const MAC_RE = /mac/i;

// ---------------------------------------------------------------------------
// Props
// ---------------------------------------------------------------------------

interface PlaygroundProps {
  initialParams: Record<string, string>;
  loading: boolean;
  onParamsChange: (params: Record<string, unknown>) => void;
  tool: Tool | null;
}

// ---------------------------------------------------------------------------
// Execution reducer
// ---------------------------------------------------------------------------

type ExecAction =
  | {
      type: "start";
      abortController: AbortController;
      previousResponse?: ExecuteResponse;
    }
  | { type: "success"; response: ExecuteResponse; timing: number }
  | { type: "error"; error: ApiError; timing?: number }
  | { type: "reset" };

function execReducer(
  _state: ExecutionState,
  action: ExecAction
): ExecutionState {
  switch (action.type) {
    case "start":
      return {
        status: "loading",
        abortController: action.abortController,
        previousResponse: action.previousResponse,
      };
    case "success":
      return {
        status: "success",
        response: action.response,
        timing: action.timing,
      };
    case "error":
      return {
        status: "error",
        error: action.error,
        timing: action.timing,
      };
    case "reset":
      return { status: "idle" };
    default:
      return { status: "idle" };
  }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** Build default values from param specs + initialParams overlay. */
function buildDefaults(
  tool: Tool,
  initialParams: Record<string, string>
): Record<string, unknown> {
  const values: Record<string, unknown> = {};
  for (const p of tool.params) {
    if (p.default !== undefined) {
      values[p.name] = p.default;
    }
  }
  // Overlay URL hash params
  for (const [key, value] of Object.entries(initialParams)) {
    values[key] = value;
  }
  return values;
}

/** Handle specific error codes (bind_error, write_confirmation_required). */
function handleErrorSideEffects(
  apiError: ApiError,
  setErrors: React.Dispatch<React.SetStateAction<Record<string, string>>>,
  setWriteDialogOpen: React.Dispatch<React.SetStateAction<boolean>>
) {
  if (apiError.error.code === "bind_error") {
    const param = extractBindErrorParam(apiError.error.message);
    if (param) {
      setErrors((prev) => ({
        ...prev,
        [param]: apiError.error.message,
      }));
    }
  }
  if (isWriteConfirmationRequired(apiError)) {
    setWriteDialogOpen(true);
  }
}

/** Convert an unknown catch value into an ApiError shape. */
function toApiError(err: unknown): ApiError {
  if (err instanceof ApiClientError) {
    return { error: { code: err.code, message: err.message } };
  }
  if (err instanceof DOMException && err.name === "AbortError") {
    return { error: { code: "aborted", message: "Request cancelled" } };
  }
  if (err instanceof Error) {
    return { error: { code: "unknown", message: err.message } };
  }
  return { error: { code: "unknown", message: String(err) } };
}

// ---------------------------------------------------------------------------
// Loading skeleton
// ---------------------------------------------------------------------------

function PlaygroundSkeleton() {
  return (
    <div className="flex h-full flex-col">
      {/* Request strip skeleton */}
      <div className="shrink-0 border-border border-b">
        <div className="flex items-center gap-2 px-4 py-2">
          <Skeleton className="h-4 w-32" />
          <Skeleton className="h-4 w-12 rounded-full" />
          <Skeleton className="h-4 w-10 rounded-full" />
        </div>
        <div className="grid grid-cols-3 gap-3 px-4 pb-2">
          <div className="space-y-1">
            <Skeleton className="h-3 w-12" />
            <Skeleton className="h-7 w-full" />
          </div>
          <div className="space-y-1">
            <Skeleton className="h-3 w-16" />
            <Skeleton className="h-7 w-full" />
          </div>
          <div className="space-y-1">
            <Skeleton className="h-3 w-10" />
            <Skeleton className="h-7 w-full" />
          </div>
        </div>
        <div className="border-border/50 border-t px-4 py-1.5">
          <Skeleton className="h-7 w-20" />
        </div>
      </div>
      {/* Response pane skeleton */}
      <div className="flex flex-1 items-center justify-center">
        <Skeleton className="h-4 w-32" />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Write-confirmation dialog
// ---------------------------------------------------------------------------

function WriteConfirmDialog({
  open,
  onOpenChange,
  tool,
  args,
  onConfirm,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tool: Tool;
  args: Record<string, unknown>;
  onConfirm: () => void;
}) {
  const argSummary = useMemo(() => {
    const entries = Object.entries(args).filter(
      ([, v]) => v !== undefined && v !== null && v !== ""
    );
    if (entries.length === 0) {
      return "No arguments";
    }
    return entries
      .map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
      .join("\n");
  }, [args]);

  return (
    <Dialog onOpenChange={onOpenChange} open={open}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Confirm Write Operation</DialogTitle>
          <DialogDescription>
            <span className="font-mono font-semibold">{tool.key}</span> is a{" "}
            <span className="font-semibold text-amber-400">write</span> command.
            This may modify data.
          </DialogDescription>
        </DialogHeader>

        <div className="rounded-md border border-border bg-muted/30 p-3">
          <pre className="max-h-32 overflow-auto whitespace-pre-wrap break-all font-mono text-[0.65rem] text-muted-foreground">
            {argSummary}
          </pre>
        </div>

        <DialogFooter>
          <Button onClick={() => onOpenChange(false)} variant="outline">
            Cancel
          </Button>
          <Button
            onClick={() => {
              onOpenChange(false);
              onConfirm();
            }}
            variant="destructive"
          >
            <AlertTriangle className="size-3" />
            Confirm &amp; Execute
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------

export function Playground({
  tool,
  loading,
  initialParams,
  onParamsChange,
}: PlaygroundProps) {
  // ----- Form state -----
  const [formValues, setFormValues] = useState<Record<string, unknown>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});

  // ----- Execution state -----
  const [execution, dispatch] = useReducer(execReducer, { status: "idle" });

  // ----- History -----
  const { entries: historyEntries, addEntry, clearHistory } = useHistory();

  // ----- Write confirmation dialog -----
  const [writeDialogOpen, setWriteDialogOpen] = useState(false);

  // ----- Server-side validation -----
  const validateControllerRef = useRef<AbortController | null>(null);
  const validateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // ----- Form persistence per-command -----
  const formCacheRef = useRef<Map<string, Record<string, unknown>>>(new Map());
  const prevToolKeyRef = useRef<string | null>(null);

  // ----- Ref mirror of formValues for use in effects without deps -----
  const formValuesRef = useRef(formValues);
  formValuesRef.current = formValues;

  // ----- Stale tracking: did form change after last execution? -----
  const [isStale, setIsStale] = useState(false);
  const lastExecutedValuesRef = useRef<Record<string, unknown> | null>(null);

  // ----- Container ref for keyboard shortcut -----
  const containerRef = useRef<HTMLDivElement>(null);

  // ----- Last URL from successful execution (for cURL examples) -----
  const lastUrl =
    execution.status === "success" ? execution.response.url : undefined;

  // ----- Stable ref for initialParams (only used on first mount per command) -----
  const initialParamsRef = useRef(initialParams);
  initialParamsRef.current = initialParams;

  // -----------------------------------------------------------------------
  // Initialise / switch commands: save old form, restore or build new defaults
  // -----------------------------------------------------------------------
  useEffect(() => {
    const prevKey = prevToolKeyRef.current;
    const newKey = tool?.key ?? null;

    // Save current form values for the previous command
    if (prevKey && prevKey !== newKey) {
      formCacheRef.current.set(prevKey, formValuesRef.current);
    }

    if (tool) {
      // Restore cached values or build from defaults
      const cached = formCacheRef.current.get(tool.key);
      const nextValues =
        cached ?? buildDefaults(tool, initialParamsRef.current);
      setFormValues(nextValues);
      setErrors({});
      dispatch({ type: "reset" });
      setIsStale(false);
      lastExecutedValuesRef.current = null;
    }

    prevToolKeyRef.current = newKey;
    // Only run when the tool identity changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tool?.key, tool]);

  // -----------------------------------------------------------------------
  // Propagate param changes to URL hash
  // -----------------------------------------------------------------------
  const handleFormChange = useCallback(
    (values: Record<string, unknown>) => {
      setFormValues(values);
      onParamsChange(values);
      // Mark response as stale if values differ from last execution
      if (lastExecutedValuesRef.current !== null) {
        setIsStale(true);
      }
    },
    [onParamsChange]
  );

  // -----------------------------------------------------------------------
  // Server-side validation (debounced 300ms)
  // -----------------------------------------------------------------------
  useEffect(() => {
    if (!tool) {
      return;
    }
    if (Object.keys(formValues).length === 0) {
      return;
    }

    // Cancel pending validation
    if (validateTimerRef.current) {
      clearTimeout(validateTimerRef.current);
    }
    if (validateControllerRef.current) {
      validateControllerRef.current.abort();
    }

    validateTimerRef.current = setTimeout(() => {
      const controller = new AbortController();
      validateControllerRef.current = controller;

      validateParams({ command: tool.key, args: formValues }, controller.signal)
        .then((result) => {
          if (controller.signal.aborted) {
            return;
          }
          if (!result.valid && result.missing_required) {
            const serverErrors: Record<string, string> = {};
            for (const param of result.missing_required) {
              serverErrors[param] = "Required by server";
            }
            setErrors((prev) => ({ ...prev, ...serverErrors }));
          }
        })
        .catch(() => {
          // Ignore validation errors (abort, network, etc.)
        });
    }, 300);

    return () => {
      if (validateTimerRef.current) {
        clearTimeout(validateTimerRef.current);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tool?.key, formValues, tool]);

  // -----------------------------------------------------------------------
  // Execute command
  // -----------------------------------------------------------------------
  const doExecute = useCallback(
    async (confirmWrite = false) => {
      if (!tool) {
        return;
      }

      // If write mode and not confirmed yet, show dialog
      if (tool.mode === "write" && !confirmWrite) {
        setWriteDialogOpen(true);
        return;
      }

      // Cancel any in-flight request
      if (execution.status === "loading") {
        execution.abortController.abort();
      }

      const controller = new AbortController();
      const previousResponse =
        execution.status === "success" ? execution.response : undefined;

      dispatch({
        type: "start",
        abortController: controller,
        previousResponse,
      });

      const startTime = Date.now();

      try {
        const response = await executeCommand(
          {
            command: tool.key,
            args: formValues,
            confirm_write: confirmWrite || undefined,
          },
          controller.signal
        );

        const timing = Date.now() - startTime;
        dispatch({ type: "success", response, timing });
        lastExecutedValuesRef.current = { ...formValues };
        setIsStale(false);
        addEntry(tool.key, formValues, response);
      } catch (err: unknown) {
        if (controller.signal.aborted) {
          dispatch({
            type: "error",
            error: { error: { code: "aborted", message: "Request cancelled" } },
            timing: Date.now() - startTime,
          });
          return;
        }

        const timing = Date.now() - startTime;
        const apiError = toApiError(err);

        dispatch({ type: "error", error: apiError, timing });
        addEntry(tool.key, formValues, undefined, apiError);
        handleErrorSideEffects(apiError, setErrors, setWriteDialogOpen);
      }
    },
    [tool, formValues, execution, addEntry]
  );

  const handleExecute = useCallback(() => {
    doExecute(false);
  }, [doExecute]);

  const handleConfirmWrite = useCallback(() => {
    doExecute(true);
  }, [doExecute]);

  const handleCancel = useCallback(() => {
    if (execution.status === "loading") {
      execution.abortController.abort();
    }
  }, [execution]);

  // -----------------------------------------------------------------------
  // Cmd+Enter / Ctrl+Enter keyboard shortcut
  // -----------------------------------------------------------------------
  useEffect(() => {
    const container = containerRef.current;
    if (!container) {
      return;
    }

    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        doExecute(false);
      }
    }

    container.addEventListener("keydown", onKeyDown);
    return () => container.removeEventListener("keydown", onKeyDown);
  }, [doExecute]);

  // -----------------------------------------------------------------------
  // CLI import handler
  // -----------------------------------------------------------------------
  const handleCliImport = useCallback(
    (command: string, args: Record<string, string>) => {
      // Navigate to the imported command by updating the URL hash.
      // The app.tsx hashchange listener will pick this up.
      const search = new URLSearchParams(args);
      const qs = search.toString();
      const hash = qs ? `#${command}?${qs}` : `#${command}`;
      window.location.hash = hash;

      // If the command matches the current tool, fill form directly
      if (tool && tool.key === command) {
        const nextValues = { ...formValues, ...args };
        setFormValues(nextValues);
        onParamsChange(nextValues);
      }
    },
    [tool, formValues, onParamsChange]
  );

  // -----------------------------------------------------------------------
  // History replay handler
  // -----------------------------------------------------------------------
  const handleHistoryReplay = useCallback(
    (entry: HistoryEntry) => {
      // Navigate to the command
      window.location.hash = `#${entry.command}`;

      // If same command, fill form with history entry's args
      if (tool && tool.key === entry.command) {
        setFormValues(entry.args);
        onParamsChange(entry.args);
      }

      // If the entry has a cached response, show it
      if (entry.response) {
        dispatch({
          type: "success",
          response: entry.response,
          timing: 0,
        });
      } else if (entry.error) {
        dispatch({ type: "error", error: entry.error });
      }
    },
    [tool, onParamsChange]
  );

  // -----------------------------------------------------------------------
  // Render
  // -----------------------------------------------------------------------
  if (loading) {
    return <PlaygroundSkeleton />;
  }

  if (!tool) {
    return (
      <div className="flex h-full items-center justify-center p-6 text-muted-foreground text-sm">
        No command selected
      </div>
    );
  }

  const isExecuting = execution.status === "loading";

  return (
    <div className="flex h-full flex-col" ref={containerRef} tabIndex={-1}>
      {/* ---- Request strip (fixed at top) ---- */}
      <div className="shrink-0 border-border border-b">
        {/* Header row */}
        <div className="flex items-center gap-2 px-4 py-2">
          <code className="font-semibold text-xs">{tool.key}</code>
          <span className="rounded-full bg-muted px-1.5 py-0.5 font-medium text-[0.55rem] text-muted-foreground uppercase tracking-wider">
            {tool.protocol}
          </span>
          <span
            className={cn(
              "rounded-full px-1.5 py-0.5 font-medium text-[0.55rem]",
              tool.mode === "read"
                ? "bg-emerald-500/15 text-emerald-400"
                : "bg-amber-500/15 text-amber-400"
            )}
          >
            {tool.mode}
          </span>
          <div className="ml-auto">
            <CliImport onImport={handleCliImport} />
          </div>
        </div>

        {/* Param grid */}
        <div className="px-4 pb-2">
          <ParamForm
            autoFocus
            errors={errors}
            onChange={handleFormChange}
            onErrorsChange={setErrors}
            params={tool.params}
            values={formValues}
          />
        </div>

        {/* Action row */}
        <div className="flex items-center gap-2 border-border/50 border-t px-4 py-1.5">
          {isExecuting ? (
            <Button
              className="h-7 animate-pulse"
              onClick={handleCancel}
              size="sm"
              variant="outline"
            >
              <Square className="size-3" />
              Cancel
            </Button>
          ) : (
            <Button
              className="h-7 transition-transform duration-100 hover:brightness-110 active:scale-[0.98]"
              onClick={handleExecute}
              size="sm"
            >
              <Play className="size-3" />
              Execute
            </Button>
          )}
          <span className="ml-auto text-[0.55rem] text-muted-foreground">
            {MAC_RE.test(navigator.userAgent) ? "\u2318" : "Ctrl"}+Enter
          </span>
        </div>
      </div>

      {/* ---- Collapsible code examples ---- */}
      <div className="shrink-0 border-border/50 border-b px-4 py-1">
        <CodeExamples args={formValues} lastUrl={lastUrl} tool={tool} />
      </div>

      {/* ---- Response pane (fills remaining space) ---- */}
      <div aria-live="polite" className="min-h-0 flex-1">
        <ResponseView
          execution={execution}
          isHttp={tool.protocol === "http"}
          stale={isStale}
        />
      </div>

      {/* ---- History drawer (pinned to bottom) ---- */}
      <HistoryDrawer
        entries={historyEntries}
        onClear={clearHistory}
        onReplay={handleHistoryReplay}
      />

      {/* Write confirmation dialog */}
      <WriteConfirmDialog
        args={formValues}
        onConfirm={handleConfirmWrite}
        onOpenChange={setWriteDialogOpen}
        open={writeDialogOpen}
        tool={tool}
      />
    </div>
  );
}