@majapisoftwares/ui 6.7.0 → 6.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,37 @@
1
1
  "use client";
2
2
 
3
- import { useState, type ReactNode } from "react";
4
- import { BrainIcon, WrenchIcon } from "lucide-react";
3
+ import {
4
+ cloneElement,
5
+ isValidElement,
6
+ useState,
7
+ type ReactElement,
8
+ type ReactNode,
9
+ } from "react";
10
+ import {
11
+ ArrowUpRightIcon,
12
+ BrainIcon,
13
+ CheckIcon,
14
+ CircleCheckIcon,
15
+ CircleDashedIcon,
16
+ CircleDotIcon,
17
+ CircleIcon,
18
+ CircleXIcon,
19
+ FileCodeIcon,
20
+ FlaskConicalIcon,
21
+ GlobeIcon,
22
+ LayersIcon,
23
+ ListChecksIcon,
24
+ ListTodoIcon,
25
+ RouteIcon,
26
+ TerminalIcon,
27
+ WrenchIcon,
28
+ XIcon,
29
+ } from "lucide-react";
5
30
  import { cn } from "../lib/utils";
6
31
  import { useUiMessages } from "../lib/i18n";
32
+ import { Badge } from "../components/ui/badge";
7
33
  import { Button } from "../components/ui/button";
34
+ import { CodeBlock, CodeBlockContent } from "../components/ui/code-block";
8
35
  import {
9
36
  Item,
10
37
  ItemActions,
@@ -102,6 +129,17 @@ export interface ToolProps {
102
129
  children?: ReactNode;
103
130
  }
104
131
 
132
+ /** Command or tool output as AI Elements shows it: a small code block that wraps and scrolls. */
133
+ function Output({ children }: { children: ReactNode }) {
134
+ return (
135
+ <CodeBlock size="sm">
136
+ <CodeBlockContent wrap className="max-h-64">
137
+ {children}
138
+ </CodeBlockContent>
139
+ </CodeBlock>
140
+ );
141
+ }
142
+
105
143
  /** One tool call (shadcn AI Elements Tool) with its output on demand. */
106
144
  export function Tool({
107
145
  title,
@@ -128,13 +166,7 @@ export function Tool({
128
166
  <TraceCollapsible>
129
167
  <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
130
168
  <TraceCollapsibleContent>
131
- {typeof children === "string" ? (
132
- <pre className="max-h-64 overflow-auto rounded-xl bg-muted px-3 py-2 font-mono text-xs whitespace-pre-wrap text-foreground">
133
- {children}
134
- </pre>
135
- ) : (
136
- children
137
- )}
169
+ {typeof children === "string" ? <Output>{children}</Output> : children}
138
170
  </TraceCollapsibleContent>
139
171
  </TraceCollapsible>
140
172
  );
@@ -198,3 +230,701 @@ export function Confirmation({
198
230
  </Item>
199
231
  );
200
232
  }
233
+
234
+ /** A step's state: done (none), running, failed or not started. */
235
+ export type StepStatus = "done" | "running" | "error" | "pending";
236
+
237
+ const lineStatus = (status: StepStatus | undefined) =>
238
+ status === "running" || status === "error" || status === "pending"
239
+ ? status
240
+ : undefined;
241
+
242
+ /** The icon a step gets for its state. */
243
+ function StatusIcon({ status }: { status: StepStatus }) {
244
+ if (status === "running") return <Orb size={16} variant="B1" />;
245
+ if (status === "error") return <CircleXIcon />;
246
+ if (status === "pending") return <CircleIcon />;
247
+ return <CircleCheckIcon />;
248
+ }
249
+
250
+ /** Open while running and closed when done, unless the person toggled it (as Reasoning). */
251
+ function useRunningOpen(running: boolean) {
252
+ const [open, setOpen] = useState<boolean>();
253
+ return { open: open ?? running, onOpenChange: setOpen };
254
+ }
255
+
256
+ export interface StepProps {
257
+ title: ReactNode;
258
+ status?: StepStatus;
259
+ /** Defaults to the state's icon; `null` for none. */
260
+ icon?: ReactNode;
261
+ /** Short metadata after the title, e.g. a duration. */
262
+ description?: ReactNode;
263
+ /** Makes the line a link, e.g. `<a href="…" />` or a router link. */
264
+ render?: ReactElement;
265
+ /** Search results: one badge each (hostnames), shown when the step opens. */
266
+ badges?: string[];
267
+ /** Shown when the step opens: strings as output, anything else as is. */
268
+ children?: ReactNode;
269
+ defaultOpen?: boolean;
270
+ }
271
+
272
+ /**
273
+ * One thing an agent did, inside Chain of Thought, Task or Subagent (a trace
274
+ * line). With content (children or badges) it opens to show it.
275
+ */
276
+ export function Step({
277
+ title,
278
+ status = "done",
279
+ icon,
280
+ description,
281
+ render,
282
+ badges,
283
+ children,
284
+ defaultOpen,
285
+ }: StepProps) {
286
+ const line = (
287
+ <TraceLine status={lineStatus(status)}>
288
+ {icon === null ? null : (
289
+ <TraceIcon>{icon ?? <StatusIcon status={status} />}</TraceIcon>
290
+ )}
291
+ <TraceTitle>{title}</TraceTitle>
292
+ {description ? <TraceDescription>{description}</TraceDescription> : null}
293
+ </TraceLine>
294
+ );
295
+ if (children || badges?.length)
296
+ return (
297
+ <TraceCollapsible defaultOpen={defaultOpen}>
298
+ <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
299
+ <TraceCollapsibleContent
300
+ className={cn(badges?.length && "flex flex-wrap gap-1.5")}
301
+ >
302
+ {badges?.map((badge) => (
303
+ <Badge key={badge} variant="secondary">
304
+ {badge}
305
+ </Badge>
306
+ ))}
307
+ {typeof children === "string" ? (
308
+ <Output>{children}</Output>
309
+ ) : (
310
+ children
311
+ )}
312
+ </TraceCollapsibleContent>
313
+ </TraceCollapsible>
314
+ );
315
+ if (render && isValidElement(render)) return cloneElement(render, {}, line);
316
+ return line;
317
+ }
318
+
319
+ export interface ChainOfThoughtProps {
320
+ /** One `Step` per thing the agent did. */
321
+ children: ReactNode;
322
+ /** How many steps, for the default title. */
323
+ steps: number;
324
+ running?: boolean;
325
+ /** A step failed. */
326
+ failed?: boolean;
327
+ /** Overrides "Researching" / "Researched in N steps". */
328
+ title?: ReactNode;
329
+ }
330
+
331
+ /**
332
+ * The steps behind an answer (shadcn AI Elements Chain of Thought): a summary
333
+ * line that opens to them, open while they run.
334
+ */
335
+ export function ChainOfThought({
336
+ children,
337
+ steps,
338
+ running = false,
339
+ failed = false,
340
+ title,
341
+ }: ChainOfThoughtProps) {
342
+ const messages = useUiMessages();
343
+ const state = useRunningOpen(running);
344
+ return (
345
+ <TraceCollapsible {...state}>
346
+ <TraceCollapsibleTrigger>
347
+ <TraceLine status={running ? "running" : failed ? "error" : undefined}>
348
+ <TraceIcon>
349
+ <StatusIcon status={running ? "running" : "done"} />
350
+ </TraceIcon>
351
+ <TraceTitle>
352
+ {title ??
353
+ (running ? messages.researching : messages.researched(steps))}
354
+ </TraceTitle>
355
+ </TraceLine>
356
+ </TraceCollapsibleTrigger>
357
+ <TraceCollapsibleContent keepMounted>
358
+ <Trace>{children}</Trace>
359
+ </TraceCollapsibleContent>
360
+ </TraceCollapsible>
361
+ );
362
+ }
363
+
364
+ export interface PlanStep {
365
+ title: ReactNode;
366
+ status: "done" | "running" | "pending";
367
+ }
368
+
369
+ export interface PlanProps {
370
+ /** E.g. "Plan: migrate to Base UI". */
371
+ title: ReactNode;
372
+ steps: PlanStep[];
373
+ /** Shown above the steps. */
374
+ description?: ReactNode;
375
+ defaultOpen?: boolean;
376
+ }
377
+
378
+ /**
379
+ * Steps the agent decided on before starting, with its progress (shadcn AI
380
+ * Elements Plan). For steps that come from the work itself, use Task.
381
+ */
382
+ export function Plan({
383
+ title,
384
+ steps,
385
+ description,
386
+ defaultOpen = true,
387
+ }: PlanProps) {
388
+ const messages = useUiMessages();
389
+ const done = steps.filter((step) => step.status === "done").length;
390
+ const running = steps.some((step) => step.status === "running");
391
+ return (
392
+ <TraceCollapsible defaultOpen={defaultOpen}>
393
+ <TraceCollapsibleTrigger>
394
+ <TraceLine status={running ? "running" : undefined}>
395
+ <TraceIcon>
396
+ <RouteIcon />
397
+ </TraceIcon>
398
+ <TraceTitle>{title}</TraceTitle>
399
+ <TraceDescription>
400
+ {messages.planProgress(done, steps.length)}
401
+ </TraceDescription>
402
+ </TraceLine>
403
+ </TraceCollapsibleTrigger>
404
+ <TraceCollapsibleContent
405
+ className={cn(description && "flex flex-col gap-3")}
406
+ >
407
+ {description ? <p>{description}</p> : null}
408
+ <Trace>
409
+ {steps.map((step, index) => (
410
+ <TraceLine key={index} status={lineStatus(step.status)}>
411
+ <TraceIcon>
412
+ {step.status === "done" ? (
413
+ <CircleCheckIcon />
414
+ ) : step.status === "running" ? (
415
+ <CircleDotIcon />
416
+ ) : (
417
+ <CircleIcon />
418
+ )}
419
+ </TraceIcon>
420
+ <TraceTitle>{step.title}</TraceTitle>
421
+ </TraceLine>
422
+ ))}
423
+ </Trace>
424
+ </TraceCollapsibleContent>
425
+ </TraceCollapsible>
426
+ );
427
+ }
428
+
429
+ export interface QueueTodo {
430
+ id?: string;
431
+ title: ReactNode;
432
+ /** Opens from the todo. */
433
+ description?: ReactNode;
434
+ status: "pending" | "in_progress" | "completed";
435
+ }
436
+
437
+ export interface QueueProps {
438
+ todos: QueueTodo[];
439
+ /** While the agent works, the todo in progress shimmers. */
440
+ running?: boolean;
441
+ }
442
+
443
+ function TodoRow({ todo, running }: { todo: QueueTodo; running: boolean }) {
444
+ const line = (
445
+ <TraceLine
446
+ status={todo.status === "in_progress" && running ? "running" : undefined}
447
+ >
448
+ <TraceIcon>
449
+ {todo.status === "completed" ? (
450
+ <CircleCheckIcon />
451
+ ) : todo.status === "in_progress" ? (
452
+ <CircleDotIcon />
453
+ ) : (
454
+ <CircleIcon />
455
+ )}
456
+ </TraceIcon>
457
+ <TraceTitle>{todo.title}</TraceTitle>
458
+ </TraceLine>
459
+ );
460
+ if (!todo.description) return line;
461
+ return (
462
+ <TraceCollapsible>
463
+ <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
464
+ <TraceCollapsibleContent>{todo.description}</TraceCollapsibleContent>
465
+ </TraceCollapsible>
466
+ );
467
+ }
468
+
469
+ /**
470
+ * The agent's todo list (shadcn AI Elements Queue): what's left (open) and
471
+ * what's done (closed). Todos move to the second when done.
472
+ */
473
+ export function Queue({ todos, running = false }: QueueProps) {
474
+ const messages = useUiMessages();
475
+ const pending = todos.filter((todo) => todo.status !== "completed");
476
+ const completed = todos.filter((todo) => todo.status === "completed");
477
+ const section = (
478
+ items: QueueTodo[],
479
+ icon: ReactNode,
480
+ label: string,
481
+ defaultOpen: boolean,
482
+ ) =>
483
+ items.length ? (
484
+ <TraceCollapsible defaultOpen={defaultOpen}>
485
+ <TraceCollapsibleTrigger>
486
+ <TraceLine>
487
+ <TraceIcon>{icon}</TraceIcon>
488
+ <TraceTitle>{label}</TraceTitle>
489
+ </TraceLine>
490
+ </TraceCollapsibleTrigger>
491
+ <TraceCollapsibleContent keepMounted>
492
+ <Trace>
493
+ {items.map((todo, index) => (
494
+ <TodoRow key={todo.id ?? index} todo={todo} running={running} />
495
+ ))}
496
+ </Trace>
497
+ </TraceCollapsibleContent>
498
+ </TraceCollapsible>
499
+ ) : null;
500
+ return (
501
+ <>
502
+ {section(pending, <ListTodoIcon />, messages.toDo(pending.length), true)}
503
+ {section(
504
+ completed,
505
+ <ListChecksIcon />,
506
+ messages.completedCount(completed.length),
507
+ false,
508
+ )}
509
+ </>
510
+ );
511
+ }
512
+
513
+ export interface TaskProps {
514
+ /** Present tense while it runs ("Updating the page metadata"), past once done. */
515
+ title: ReactNode;
516
+ status?: "done" | "running" | "error";
517
+ /** One `Step` per thing done so far. */
518
+ children: ReactNode;
519
+ }
520
+
521
+ /**
522
+ * One unit of the agent's work, its steps appearing as they happen (shadcn
523
+ * AI Elements Task). Open while it runs; several tasks share one ChatTrace.
524
+ */
525
+ export function Task({ title, status = "done", children }: TaskProps) {
526
+ const state = useRunningOpen(status === "running");
527
+ return (
528
+ <TraceCollapsible {...state}>
529
+ <TraceCollapsibleTrigger>
530
+ <TraceLine status={lineStatus(status)}>
531
+ <TraceTitle>{title}</TraceTitle>
532
+ </TraceLine>
533
+ </TraceCollapsibleTrigger>
534
+ <TraceCollapsibleContent keepMounted>
535
+ <Trace>{children}</Trace>
536
+ </TraceCollapsibleContent>
537
+ </TraceCollapsible>
538
+ );
539
+ }
540
+
541
+ export interface Source {
542
+ url: string;
543
+ /** Falls back to the URL's hostname. */
544
+ title?: string;
545
+ }
546
+
547
+ /** A URL's hostname without "www.", or the text as is when it isn't a URL. */
548
+ export function hostnameOf(url: string) {
549
+ try {
550
+ return new URL(url).hostname.replace(/^www\./, "");
551
+ } catch {
552
+ return url;
553
+ }
554
+ }
555
+
556
+ /** The links an answer used (shadcn AI Elements Sources), closed by default. */
557
+ export function Sources({ sources }: { sources: Source[] }) {
558
+ const messages = useUiMessages();
559
+ if (!sources.length) return null;
560
+ return (
561
+ <TraceCollapsible>
562
+ <TraceCollapsibleTrigger>
563
+ <TraceLine>
564
+ <TraceIcon>
565
+ <GlobeIcon />
566
+ </TraceIcon>
567
+ <TraceTitle>{messages.usedSources(sources.length)}</TraceTitle>
568
+ </TraceLine>
569
+ </TraceCollapsibleTrigger>
570
+ <TraceCollapsibleContent>
571
+ <Trace>
572
+ {sources.map((source) => (
573
+ <a
574
+ key={source.url}
575
+ href={source.url}
576
+ target="_blank"
577
+ rel="noreferrer"
578
+ >
579
+ <TraceLine>
580
+ <TraceIcon>
581
+ <GlobeIcon />
582
+ </TraceIcon>
583
+ <TraceTitle>
584
+ {source.title ?? hostnameOf(source.url)}
585
+ <span className="sr-only"> {messages.opensInNewTab}</span>
586
+ </TraceTitle>
587
+ <TraceIcon>
588
+ <ArrowUpRightIcon />
589
+ </TraceIcon>
590
+ </TraceLine>
591
+ </a>
592
+ ))}
593
+ </Trace>
594
+ </TraceCollapsibleContent>
595
+ </TraceCollapsible>
596
+ );
597
+ }
598
+
599
+ export interface SubagentProps {
600
+ /** "Running the research agent" while it runs, "Ran the research agent" after. */
601
+ title: ReactNode;
602
+ status?: "done" | "running" | "error";
603
+ /** How long it ran, e.g. "48s". */
604
+ duration?: ReactNode;
605
+ /** What it was asked to do. */
606
+ task?: ReactNode;
607
+ /** Its model, as a badge. */
608
+ model?: string;
609
+ /** Its tools, as badges. */
610
+ tools?: string[];
611
+ /** One `Step` (or `Tool`, `Terminal`…) per tool call so far. */
612
+ children?: ReactNode;
613
+ /** What it found, once done. */
614
+ result?: ReactNode;
615
+ }
616
+
617
+ /**
618
+ * A delegated agent run (shadcn AI Elements Subagent): its line opens to the
619
+ * task it was given, its model and tools, its tool calls and its result.
620
+ * Open while it runs.
621
+ */
622
+ export function Subagent({
623
+ title,
624
+ status = "done",
625
+ duration,
626
+ task,
627
+ model,
628
+ tools,
629
+ children,
630
+ result,
631
+ }: SubagentProps) {
632
+ const state = useRunningOpen(status === "running");
633
+ return (
634
+ <TraceCollapsible {...state}>
635
+ <TraceCollapsibleTrigger>
636
+ <TraceLine status={lineStatus(status)}>
637
+ <TraceIcon>
638
+ <StatusIcon status={status} />
639
+ </TraceIcon>
640
+ <TraceTitle>{title}</TraceTitle>
641
+ {duration ? <TraceDescription>{duration}</TraceDescription> : null}
642
+ </TraceLine>
643
+ </TraceCollapsibleTrigger>
644
+ <TraceCollapsibleContent keepMounted className="flex flex-col gap-3">
645
+ {model || tools?.length ? (
646
+ <div className="flex flex-wrap gap-1.5">
647
+ {model ? <Badge variant="secondary">{model}</Badge> : null}
648
+ {tools?.map((tool) => (
649
+ <Badge key={tool} variant="outline" className="font-mono">
650
+ {tool}
651
+ </Badge>
652
+ ))}
653
+ </div>
654
+ ) : null}
655
+ {task ? <div>{task}</div> : null}
656
+ {children ? <Trace>{children}</Trace> : null}
657
+ {result ? <div className="text-foreground">{result}</div> : null}
658
+ </TraceCollapsibleContent>
659
+ </TraceCollapsible>
660
+ );
661
+ }
662
+
663
+ export interface TerminalProps {
664
+ command: string;
665
+ status?: "done" | "running" | "error";
666
+ /** A command that exits with any code but 0 failed. */
667
+ exitCode?: number;
668
+ /** What it printed so far. */
669
+ output?: string;
670
+ }
671
+
672
+ /**
673
+ * A shell command and its output (shadcn AI Elements Terminal). It opens once
674
+ * output arrives while it runs; a non-zero exit is an error.
675
+ */
676
+ export function Terminal({
677
+ command,
678
+ status = "done",
679
+ exitCode,
680
+ output,
681
+ }: TerminalProps) {
682
+ const messages = useUiMessages();
683
+ const failed =
684
+ status === "error" || (exitCode !== undefined && exitCode !== 0);
685
+ const running = status === "running" && !failed;
686
+ const state = useRunningOpen(running);
687
+ const line = (
688
+ <TraceLine status={running ? "running" : failed ? "error" : undefined}>
689
+ <TraceIcon>
690
+ <TerminalIcon />
691
+ </TraceIcon>
692
+ <TraceTitle>
693
+ {running
694
+ ? messages.runningCommand(command)
695
+ : failed && exitCode !== undefined
696
+ ? messages.exitedWith(command, exitCode)
697
+ : messages.ranCommand(command)}
698
+ </TraceTitle>
699
+ </TraceLine>
700
+ );
701
+ if (!output) return line;
702
+ return (
703
+ <TraceCollapsible {...state}>
704
+ <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
705
+ <TraceCollapsibleContent>
706
+ <Output>{output}</Output>
707
+ </TraceCollapsibleContent>
708
+ </TraceCollapsible>
709
+ );
710
+ }
711
+
712
+ export interface TestCase {
713
+ name: string;
714
+ status: "passed" | "failed" | "skipped";
715
+ /** A failure's message and stack. */
716
+ error?: string;
717
+ }
718
+
719
+ export interface TestSuite {
720
+ /** Usually the test file. */
721
+ name: string;
722
+ tests: TestCase[];
723
+ }
724
+
725
+ const countTests = (tests: TestCase[]) => ({
726
+ total: tests.length,
727
+ failed: tests.filter((test) => test.status === "failed").length,
728
+ skipped: tests.filter((test) => test.status === "skipped").length,
729
+ });
730
+
731
+ function TestRow({ test }: { test: TestCase }) {
732
+ const messages = useUiMessages();
733
+ if (test.status === "failed")
734
+ return (
735
+ <TraceCollapsible>
736
+ <TraceCollapsibleTrigger>
737
+ <TraceLine status="error">
738
+ <TraceIcon>
739
+ <XIcon />
740
+ </TraceIcon>
741
+ <TraceTitle>{test.name}</TraceTitle>
742
+ </TraceLine>
743
+ </TraceCollapsibleTrigger>
744
+ {test.error ? (
745
+ <TraceCollapsibleContent>
746
+ <Output>{test.error}</Output>
747
+ </TraceCollapsibleContent>
748
+ ) : null}
749
+ </TraceCollapsible>
750
+ );
751
+ return (
752
+ <TraceLine>
753
+ <TraceIcon>
754
+ {test.status === "skipped" ? <CircleDashedIcon /> : <CheckIcon />}
755
+ </TraceIcon>
756
+ <TraceTitle>
757
+ {test.status === "skipped"
758
+ ? messages.skippedTest(test.name)
759
+ : test.name}
760
+ </TraceTitle>
761
+ </TraceLine>
762
+ );
763
+ }
764
+
765
+ /**
766
+ * A test run (shadcn AI Elements Test Results): the counts, then each suite
767
+ * (file) and its tests. Suites with a failure open; a failure opens to its
768
+ * error.
769
+ */
770
+ export function TestResults({ suites }: { suites: TestSuite[] }) {
771
+ const messages = useUiMessages();
772
+ const counts = (tests: TestCase[]) => {
773
+ const { total, failed, skipped } = countTests(tests);
774
+ return messages.testCounts(total, failed, skipped);
775
+ };
776
+ const all = suites.flatMap((suite) => suite.tests);
777
+ const failed = countTests(all).failed;
778
+ return (
779
+ <TraceCollapsible defaultOpen>
780
+ <TraceCollapsibleTrigger>
781
+ <TraceLine status={failed > 0 ? "error" : undefined}>
782
+ <TraceIcon>
783
+ <FlaskConicalIcon />
784
+ </TraceIcon>
785
+ <TraceTitle>{messages.ranTests(counts(all))}</TraceTitle>
786
+ </TraceLine>
787
+ </TraceCollapsibleTrigger>
788
+ <TraceCollapsibleContent keepMounted>
789
+ <Trace>
790
+ {suites.map((suite) => {
791
+ const suiteFailed = countTests(suite.tests).failed;
792
+ return (
793
+ <TraceCollapsible key={suite.name} defaultOpen={suiteFailed > 0}>
794
+ <TraceCollapsibleTrigger>
795
+ <TraceLine status={suiteFailed > 0 ? "error" : undefined}>
796
+ <TraceIcon>
797
+ <FileCodeIcon />
798
+ </TraceIcon>
799
+ <TraceTitle>
800
+ {suite.name}, {counts(suite.tests)}
801
+ </TraceTitle>
802
+ </TraceLine>
803
+ </TraceCollapsibleTrigger>
804
+ <TraceCollapsibleContent keepMounted>
805
+ <Trace>
806
+ {suite.tests.map((test) => (
807
+ <TestRow key={test.name} test={test} />
808
+ ))}
809
+ </Trace>
810
+ </TraceCollapsibleContent>
811
+ </TraceCollapsible>
812
+ );
813
+ })}
814
+ </Trace>
815
+ </TraceCollapsibleContent>
816
+ </TraceCollapsible>
817
+ );
818
+ }
819
+
820
+ export interface StackFrame {
821
+ line: string;
822
+ name?: string;
823
+ file?: string;
824
+ lineNumber?: string;
825
+ /** From node_modules: folded with the other framework frames. */
826
+ internal: boolean;
827
+ }
828
+
829
+ /** Splits a stack into its error and frames (`at name (file:line:column)`). */
830
+ export function parseStack(stack: string) {
831
+ const [error = "", ...lines] = stack
832
+ .split("\n")
833
+ .map((line) => line.trim())
834
+ .filter(Boolean);
835
+ const frames: StackFrame[] = lines.map((line) => {
836
+ const match = line.match(/^at (.+) \((.+):(\d+):(\d+)\)$/);
837
+ return {
838
+ line,
839
+ name: match?.[1],
840
+ file: match?.[2],
841
+ lineNumber: match?.[3],
842
+ internal: line.includes("node_modules"),
843
+ };
844
+ });
845
+ return { error, frames };
846
+ }
847
+
848
+ export interface StackTraceProps {
849
+ stack: string;
850
+ /** Links one of your frames to its file and line. */
851
+ frameHref?: (frame: StackFrame) => string | undefined;
852
+ defaultOpen?: boolean;
853
+ }
854
+
855
+ /**
856
+ * A failure and its stack (shadcn AI Elements Stack Trace): the error is the
857
+ * title; your frames come first (links with `frameHref`) and framework frames
858
+ * fold into a line of their own.
859
+ */
860
+ export function StackTrace({ stack, frameHref, defaultOpen }: StackTraceProps) {
861
+ const messages = useUiMessages();
862
+ const { error, frames } = parseStack(stack);
863
+ const own = frames.filter((frame) => !frame.internal);
864
+ const internal = frames.filter((frame) => frame.internal);
865
+ return (
866
+ <TraceCollapsible defaultOpen={defaultOpen}>
867
+ <TraceCollapsibleTrigger>
868
+ <TraceLine status="error">
869
+ <TraceIcon>
870
+ <CircleXIcon />
871
+ </TraceIcon>
872
+ <TraceTitle>{messages.failedWith(error)}</TraceTitle>
873
+ </TraceLine>
874
+ </TraceCollapsibleTrigger>
875
+ <TraceCollapsibleContent keepMounted className="flex flex-col gap-2">
876
+ <p className="font-mono text-xs text-destructive">{error}</p>
877
+ <Trace>
878
+ {own.map((frame, index) => {
879
+ const line = (
880
+ <TraceLine>
881
+ <TraceIcon>
882
+ <FileCodeIcon />
883
+ </TraceIcon>
884
+ <TraceTitle>
885
+ {frame.name && frame.file
886
+ ? `${frame.name} · ${frame.file}:${frame.lineNumber}`
887
+ : frame.line}
888
+ </TraceTitle>
889
+ </TraceLine>
890
+ );
891
+ const href = frameHref?.(frame);
892
+ return href ? (
893
+ <a key={`${index}-${frame.line}`} href={href}>
894
+ {line}
895
+ </a>
896
+ ) : (
897
+ <div key={`${index}-${frame.line}`}>{line}</div>
898
+ );
899
+ })}
900
+ {internal.length ? (
901
+ <TraceCollapsible>
902
+ <TraceCollapsibleTrigger>
903
+ <TraceLine>
904
+ <TraceIcon>
905
+ <LayersIcon />
906
+ </TraceIcon>
907
+ <TraceTitle>
908
+ {messages.frameworkFrames(internal.length)}
909
+ </TraceTitle>
910
+ </TraceLine>
911
+ </TraceCollapsibleTrigger>
912
+ <TraceCollapsibleContent>
913
+ <ol className="flex flex-col gap-1 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs">
914
+ {internal.map((frame, index) => (
915
+ <li
916
+ key={`${index}-${frame.line}`}
917
+ className="whitespace-nowrap"
918
+ >
919
+ {frame.line}
920
+ </li>
921
+ ))}
922
+ </ol>
923
+ </TraceCollapsibleContent>
924
+ </TraceCollapsible>
925
+ ) : null}
926
+ </Trace>
927
+ </TraceCollapsibleContent>
928
+ </TraceCollapsible>
929
+ );
930
+ }