Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python
12.4 KB
Raw Blame
"use client";

import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { AlertCircle, ChevronDown, Flag, XCircle } from "lucide-react";
import { useMemo, useState } from "react";
import { IncidentReporterIcon } from "@/components/icons/incident-reporter-icon";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
} from "@/components/ui/accordion";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { type Task, useTask } from "@/contexts/task-context";
import {
  formatApiComponent,
  isFileCancelled,
  resolveTaskFileError,
} from "@/lib/task-error-display";
import {
  getFailedFileCount,
  getSuccessfulFileCount,
  getTaskFileName,
  getTaskIssueFileEntries,
  getWarningFileEntries,
  isCompletedTotalFailure,
  isTaskFileWarning,
  isTerminalFailedTask,
} from "@/lib/task-utils";
import { formatTaskTimestamp, parseTimestamp } from "@/lib/time-utils";
import { cn } from "@/lib/utils";

/** Stops both click and keyboard events from bubbling to parent handlers. */
const stopEvent = (e: React.SyntheticEvent) => e.stopPropagation();

interface TaskErrorContentProps {
  task: Task;
  mode?: "recent" | "past";
  nowMs?: number;
  showHeader?: boolean;
  defaultExpanded?: boolean;
  headerEnd?: React.ReactNode;
}

export function TaskErrorContent({
  task,
  mode = "recent",
  nowMs = Date.now(),
  showHeader = true,
  defaultExpanded = false,
  headerEnd,
}: TaskErrorContentProps) {
  const isCloudBrand = useIsCloudBrand();
  const { openTaskDialog } = useTask();
  const [accordionValue, setAccordionValue] = useState(
    defaultExpanded ? "failed-files" : "",
  );
  const isExpanded = accordionValue === "failed-files";

  const issueEntries = useMemo(() => getTaskIssueFileEntries(task), [task]);

  const totalFailedCount = getFailedFileCount(task);
  // Count cancelled files separately using centralized detection
  const cancelledCount = task.files
    ? Object.values(task.files).filter(
        (file) =>
          (file.status === "failed" || file.status === "error") &&
          isFileCancelled(file),
      ).length
    : 0;
  const failedCount = totalFailedCount - cancelledCount;
  const warningCount = getWarningFileEntries(task).length;
  const successCount = getSuccessfulFileCount(task);
  const ingestedSuccessCount = Math.max(0, successCount - warningCount);
  const timestamp =
    parseTimestamp(task.created_at) ?? parseTimestamp(task.updated_at);

  // Determine if this is a cancellation-only task (no actual failures)
  const isCancelledOnly = cancelledCount > 0 && failedCount === 0;
  const isFailedStatus =
    !isCancelledOnly &&
    (isTerminalFailedTask(task) || isCompletedTotalFailure(task));
  const statusLabel = isCancelledOnly
    ? "Cancelled"
    : isFailedStatus
      ? "Failed"
      : warningCount > 0
        ? "Warning"
        : "Complete";
  // Pill colors: failed (red) vs partial success (amber/orange) vs cancelled (gray), each with IBM tokens or OSS borders.
  const statusPillClassName = cn(
    "shrink-0 rounded-full px-2 py-1 text-xs",
    isCancelledOnly
      ? "border border-muted bg-muted/50 text-muted-foreground"
      : isFailedStatus
        ? isCloudBrand
          ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
          : "border border-failure-pill bg-failure-soft text-destructive"
        : isCloudBrand
          ? "border-0 bg-task-status-partial text-task-status-partial-foreground"
          : "border border-brand-amber-30 bg-brand-amber-10 text-brand-amber",
  );

  if (failedCount <= 0 && cancelledCount <= 0 && issueEntries.length === 0) {
    return null;
  }

  const ossIconColumn = showHeader && !isCloudBrand;
  const toggleAccordion = () =>
    setAccordionValue((value) =>
      value === "failed-files" ? "" : "failed-files",
    );

  const accordionSummary = (
    <div className="flex min-w-0 flex-1 items-center gap-1 leading-4">
      <span className="text-xs leading-4">
        {ingestedSuccessCount} success
        {warningCount > 0 ? ` · ${warningCount} warning` : ""}
        {failedCount > 0 ? ` · ${failedCount} failed` : ""}
        {cancelledCount > 0 ? ` · ${cancelledCount} cancelled` : ""}
      </span>
      <ChevronDown className="size-4 shrink-0 transition-transform group-data-[state=open]:rotate-180" />
    </div>
  );

  const openTaskDialogButton = (
    <button
      type="button"
      aria-label="Open task details"
      className="inline-flex shrink-0 items-center justify-center text-muted-foreground hover:text-foreground"
      onClick={(event) => {
        event.stopPropagation();
        openTaskDialog(task.task_id);
      }}
    >
      <IncidentReporterIcon className="size-4" />
    </button>
  );

  const accordionHeader = (
    <AccordionPrimitive.Header className="flex w-full min-w-0 items-center gap-2 leading-4">
      {ossIconColumn ? <div className="size-5 shrink-0" aria-hidden /> : null}
      <AccordionPrimitive.Trigger
        className="group inline-flex min-w-0 flex-1 items-center justify-start gap-1 p-0 text-sm text-muted-foreground transition-colors hover:text-foreground"
        onClick={(event) => event.stopPropagation()}
      >
        {accordionSummary}
      </AccordionPrimitive.Trigger>
    </AccordionPrimitive.Header>
  );

  return (
    <div
      className={cn(
        "w-full",
        showHeader &&
          cn(
            "py-mmd px-4 transition-colors hover:bg-muted/60",
            isCloudBrand
              ? "border-t border-muted"
              : "rounded-mmd border border-muted",
          ),
        !showHeader && "pt-1",
      )}
    >
      <div className="flex w-full min-w-0 flex-col">
        {showHeader && (
          <div
            className="flex min-w-0 w-full cursor-pointer items-start gap-3"
            role="button"
            tabIndex={0}
            aria-expanded={isExpanded}
            onClick={toggleAccordion}
            onKeyDown={(event) => {
              if (event.key === "Enter" || event.key === " ") {
                event.preventDefault();
                toggleAccordion();
              }
            }}
          >
            {ossIconColumn &&
              (isCancelledOnly ? (
                <XCircle
                  className="size-4 mt-0.5 shrink-0 text-muted-foreground"
                  aria-hidden
                />
              ) : isFailedStatus ? (
                <XCircle
                  className="size-4 mt-1.5 shrink-0 text-destructive"
                  aria-hidden
                />
              ) : (
                <AlertCircle
                  className="size-4 mt-0.5 shrink-0 text-brand-amber"
                  aria-hidden
                />
              ))}
            <div className="flex min-w-0 flex-1 flex-col gap-0">
              <div className="flex min-w-0 items-center justify-between gap-1.5 leading-4">
                <p className="truncate text-xs font-medium leading-4">
                  Task {task.task_id.slice(0, 8)}...
                </p>
                <div className="flex shrink-0 items-center gap-1.5">
                  {!isExpanded && (
                    <p className={statusPillClassName}>{statusLabel}</p>
                  )}
                  {/* biome-ignore lint/a11y/noStaticElementInteractions: presentation wrapper; stopPropagation only, no interactive semantics */}
                  <div
                    role="presentation"
                    onClick={stopEvent}
                    onKeyDown={stopEvent}
                  >
                    {openTaskDialogButton}
                  </div>
                  {/* biome-ignore lint/a11y/noStaticElementInteractions: stop-propagation wrapper */}
                  <span onClick={(event) => event.stopPropagation()}>
                    {headerEnd}
                  </span>
                </div>
              </div>
              <p className="text-xs leading-4 text-muted-foreground">
                {formatTaskTimestamp(timestamp, mode, nowMs)}
              </p>
            </div>
          </div>
        )}

        <Accordion
          type="single"
          collapsible
          className="w-full rounded-mmd border-0"
          value={accordionValue}
          onValueChange={(value) =>
            setAccordionValue(value === "failed-files" ? "failed-files" : "")
          }
        >
          <AccordionItem value="failed-files" className="border-0 rounded-none">
            {accordionHeader}
            <AccordionContent className="w-full p-1 pt-1">
              <div className="flex w-full flex-col gap-1">
                {issueEntries.map(([filePath, fileInfo], index) => {
                  const fileName = getTaskFileName(filePath, fileInfo);
                  const line = resolveTaskFileError(fileInfo, task.error);
                  const componentCause = formatApiComponent(fileInfo.component);
                  const isWarning = isTaskFileWarning(fileInfo);
                  const isCancelled = isFileCancelled(fileInfo);

                  return (
                    <div
                      key={`${task.task_id}-${filePath}-${index}`}
                      className={cn(
                        "task-failed-file-card min-w-0",
                        isCloudBrand
                          ? cn(
                              "flex flex-col items-start gap-2 self-stretch rounded-none rounded-r border-l-[1.5px] bg-border p-2",
                              isCancelled
                                ? "border-l-muted-foreground"
                                : isWarning
                                  ? "border-l-brand-amber"
                                  : "border-l-destructive",
                            )
                          : cn(
                              "flex flex-col gap-1 rounded p-2",
                              isCancelled
                                ? "border border-muted bg-muted/50"
                                : isWarning
                                  ? "border border-brand-amber-30 bg-brand-amber-10"
                                  : "border-destructive/20 bg-failure-soft",
                            ),
                      )}
                    >
                      <div className="flex min-w-0 w-full items-center gap-1">
                        <p
                          className={cn(
                            "min-w-0 flex-1 truncate text-xs",
                            isCancelled
                              ? "font-normal text-muted-foreground"
                              : isCloudBrand
                                ? "font-normal text-foreground"
                                : "font-semibold text-failure-file",
                          )}
                        >
                          {fileName}
                        </p>
                      </div>
                      <p
                        className={cn(
                          "w-full truncate text-xs",
                          isCancelled
                            ? "text-muted-foreground"
                            : isCloudBrand
                              ? "text-muted-foreground"
                              : "text-failure-message",
                        )}
                        title={line}
                      >
                        {line}
                      </p>
                      {componentCause ? (
                        <div className="flex min-w-0 items-center gap-1">
                          <Flag
                            className={cn(
                              "size-3 shrink-0",
                              isCancelled
                                ? "text-muted-foreground"
                                : "text-destructive",
                            )}
                            aria-hidden
                          />
                          <span
                            className={cn(
                              "truncate text-xs",
                              isCancelled
                                ? "text-muted-foreground"
                                : isCloudBrand
                                  ? "text-muted-foreground"
                                  : "text-failure-component-cause",
                            )}
                          >
                            {componentCause}
                          </span>
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>
    </div>
  );
}