Skip to content

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

Python
23.3 KB
Raw Blame
"use client";

import {
  Bell,
  CheckCircle,
  ChevronDown,
  Clock,
  Loader2,
  X,
  XCircle,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
  useDeleteAllTerminalTasksMutation,
  useDeleteTaskMutation,
} from "@/app/api/mutations/useDeleteTaskMutation";
import { IncidentReporterIcon } from "@/components/icons/incident-reporter-icon";
import { TaskCollapsibleSection } from "@/components/task-collapsible-section";
import { TaskErrorContent } from "@/components/task-error-content";
import { TaskPanelHeader } from "@/components/task-panel-header";
import {
  type TaskProgressDetailed,
  TaskProgressDetails,
} from "@/components/task-progress-details";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { Task, useTask } from "@/contexts/task-context";
import { formatRelative } from "@/lib/status-utils";
import { hasIssueFileEntries, isCompletedTotalFailure } from "@/lib/task-utils";
import {
  formatTaskTimestamp,
  parseTimestamp,
  parseTimestampMs,
} from "@/lib/time-utils";
import { cn } from "@/lib/utils";

const getTaskIcon = (
  status: Task["status"],
  hasFailedFiles = false,
  isTotalFailure = false,
) => {
  switch (status) {
    case "completed":
      if (hasFailedFiles) {
        if (isTotalFailure) {
          return <XCircle className="size-4 text-destructive" />;
        }
        return <XCircle className="h-4 w-4 text-brand-amber" />;
      }
      return <CheckCircle className="h-4 w-4 text-green-500" />;
    case "failed":
    case "error":
      return <XCircle className="size-4 text-destructive" />;
    case "cancelled":
      return <XCircle className="size-4 text-muted-foreground" />;
    case "pending":
      return <Clock className="h-4 w-4 text-yellow-500" />;
    case "running":
    case "processing":
      return <Loader2 className="h-4 w-4 text-blue-500 animate-spin" />;
    default:
      return <Clock className="h-4 w-4 text-gray-500" />;
  }
};

const formatTaskProgress = (
  task: Task,
): { basic: string; detailed: TaskProgressDetailed } | null => {
  const total = task.total_files || 0;
  const processed = task.processed_files || 0;
  const successful = task.successful_files || 0;
  const failed = task.failed_files || 0;
  const running = task.running_files || 0;
  const pending = task.pending_files || 0;

  if (total > 0) {
    return {
      basic: `${processed}/${total} files`,
      detailed: {
        total,
        processed,
        successful,
        failed,
        running,
        pending,
        remaining: total - processed,
      },
    };
  }
  return null;
};

const formatDuration = (seconds?: number) => {
  if (!seconds || seconds < 0) return null;

  if (seconds < 60) {
    return `${Math.round(seconds)}s`;
  } else if (seconds < 3600) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.round(seconds % 60);
    return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
  } else {
    const hours = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
  }
};

// ─── status badge ─────────────────────────────────────────────────────────────

const getStatusBadge = (
  status: Task["status"],
  isCloudBrand: boolean,
  hasFailedFiles = false,
  isTotalFailure = false,
) => {
  const statusBadgeBase = "shrink-0 rounded-full px-2 py-1 text-xs font-normal";
  switch (status) {
    case "completed":
      if (hasFailedFiles && isTotalFailure) {
        return (
          <Badge
            variant="outline"
            className={cn(
              statusBadgeBase,
              isCloudBrand
                ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
                : "bg-red-500/10 text-red-500 border-red-500/20",
            )}
          >
            FAILED
          </Badge>
        );
      }
      if (hasFailedFiles) {
        return (
          <Badge
            variant="outline"
            className={cn(
              statusBadgeBase,
              isCloudBrand
                ? "border-0 bg-task-status-partial text-task-status-partial-foreground"
                : "bg-brand-amber-10 text-brand-amber border-brand-amber-30",
            )}
          >
            Completed
          </Badge>
        );
      }
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            isCloudBrand
              ? "border-0 bg-task-status-complete text-task-status-complete-foreground"
              : "border border-green-500/20 bg-green-500/10 text-green-500",
          )}
        >
          Completed
        </Badge>
      );
    case "failed":
    case "error":
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            isCloudBrand
              ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
              : "bg-red-500/10 text-red-500 border-red-500/20",
          )}
        >
          FAILED
        </Badge>
      );
    case "cancelled":
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            "bg-muted text-muted-foreground border-muted-foreground/20",
          )}
        >
          CANCELLED
        </Badge>
      );
    case "pending":
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            "bg-yellow-500/10 text-yellow-500 border-yellow-500/20",
          )}
        >
          Pending
        </Badge>
      );
    case "running":
    case "processing":
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            "bg-blue-500/10 text-blue-500 border-blue-500/20",
          )}
        >
          Processing
        </Badge>
      );
    default:
      return (
        <Badge
          variant="outline"
          className={cn(
            statusBadgeBase,
            "bg-gray-500/10 text-gray-500 border-gray-500/20",
          )}
        >
          Unknown
        </Badge>
      );
  }
};

export function TaskNotificationMenu() {
  const isCloudBrand = useIsCloudBrand();
  const {
    tasks,
    isFetching,
    isMenuOpen,
    isRecentTasksExpanded,
    selectedTaskId,
    selectedTaskTrigger,
    cancelTask,
    closeMenu,
    openTaskDialog,
  } = useTask();
  const deleteTaskMutation = useDeleteTaskMutation();
  const deleteAllMutation = useDeleteAllTerminalTasksMutation();
  const [isPastOpen, setIsPastOpen] = useState(true);
  const [cancellingTaskIds, setCancellingTaskIds] = useState<Set<string>>(
    new Set(),
  );
  const lastHandledSelectionTriggerRef = useRef(0);

  // Reset section defaults whenever panel is opened.
  useEffect(() => {
    if (isMenuOpen) {
      setIsPastOpen(true);
    }
  }, [isMenuOpen]);

  // Sync local state with context state
  useEffect(() => {
    if (isRecentTasksExpanded) {
      setIsPastOpen(true);
    }
  }, [isRecentTasksExpanded]);

  // Clean up cancelling state when tasks actually transition to cancelled or disappear
  useEffect(() => {
    const currentTaskIds = new Set<string>();
    const terminalTaskIds = new Set<string>();

    // Single pass over tasks to build both sets
    for (const task of tasks) {
      currentTaskIds.add(task.task_id);
      if (
        task.status === "cancelled" ||
        task.status === "failed" ||
        task.status === "completed" ||
        task.status === "error"
      ) {
        terminalTaskIds.add(task.task_id);
      }
    }

    setCancellingTaskIds((prev) => {
      const next = new Set(prev);
      let changed = false;

      // Remove from cancelling set if task is now terminal or disappeared
      for (const id of next) {
        if (!currentTaskIds.has(id) || terminalTaskIds.has(id)) {
          next.delete(id);
          changed = true;
        }
      }

      return changed ? next : prev;
    });
  }, [tasks]);
  const activeTasks = tasks.filter(
    (task) =>
      task.status === "pending" ||
      task.status === "running" ||
      task.status === "processing",
  );
  const terminalTasks = useMemo(
    () =>
      tasks
        .filter(
          (task) =>
            task.status === "completed" ||
            task.status === "failed" ||
            task.status === "error" ||
            task.status === "cancelled",
        )
        .sort((a, b) => {
          const aMs =
            parseTimestampMs(a.updated_at) ??
            parseTimestampMs(a.created_at) ??
            0;
          const bMs =
            parseTimestampMs(b.updated_at) ??
            parseTimestampMs(b.created_at) ??
            0;
          return bMs - aMs;
        }),
    [tasks],
  );
  // Ensure selected task is visible in the past tasks section.
  useEffect(() => {
    if (!selectedTaskId) return;
    if (selectedTaskTrigger <= lastHandledSelectionTriggerRef.current) return;
    lastHandledSelectionTriggerRef.current = selectedTaskTrigger;

    const isInTerminal = terminalTasks.some(
      (task) => task.task_id === selectedTaskId,
    );
    if (isInTerminal) {
      setIsPastOpen(true);
    }
  }, [selectedTaskId, terminalTasks, selectedTaskTrigger]);

  // Don't render if menu is closed
  if (!isMenuOpen) return null;

  const pastTaskRowClass = cn(
    "w-full py-mmd px-4 transition-colors hover:bg-muted/60",
    isCloudBrand ? "border-t border-muted" : "rounded-mmd border border-muted",
  );

  const cancelTaskButtonClass = cn(
    "h-10 w-full shrink-0 shadow-none",
    isCloudBrand
      ? "justify-start rounded-none bg-border px-4 text-left text-muted-foreground hover:bg-accent hover:text-muted-foreground"
      : "justify-center rounded-lg border border-muted-foreground bg-task-dialog-oss-selected py-2.5 px-3 text-foreground hover:bg-accent! hover:text-foreground",
  );

  return (
    <div
      className={cn("h-full bg-background", isCloudBrand && "ibm-tasks-panel")}
    >
      <div className="flex flex-col h-full">
        <TaskPanelHeader
          activeCount={activeTasks.length}
          terminalCount={terminalTasks.filter((t) => !t.is_shared).length}
          isFetching={isFetching}
          onClose={closeMenu}
          onClearAll={() => deleteAllMutation.mutate()}
        />

        {/* Content */}
        <div className="flex-1 overflow-y-auto">
          {/* Active Tasks */}
          {activeTasks.length > 0 && (
            <div className="flex flex-col gap-2 p-4">
              <h4 className="text-sm font-medium text-muted-foreground">
                Active Tasks
              </h4>
              {activeTasks.map((task) => {
                const progress = formatTaskProgress(task);
                const hasFailedFiles = hasIssueFileEntries(task);
                const dur = formatDuration(task.duration_seconds);
                const isCancelling = cancellingTaskIds.has(task.task_id);
                const isCancelled = task.status === "cancelled";
                const canCancel =
                  !isCancelling &&
                  !isCancelled &&
                  (task.status === "pending" ||
                    task.status === "running" ||
                    task.status === "processing");
                const showTaskIcon =
                  !isCloudBrand ||
                  task.status !== "completed" ||
                  hasFailedFiles;

                return (
                  <Card
                    key={task.task_id}
                    className="bg-card/50 border-0 shadow-none py-mmd px-4"
                  >
                    <CardHeader className="p-0 pb-2">
                      <div className="flex items-center justify-between gap-2">
                        <CardTitle className="text-sm flex min-w-0 flex-1 items-center gap-2">
                          {isCancelling ? (
                            <span className="text-xs text-destructive font-medium">
                              CANCELLING...
                            </span>
                          ) : isCancelled ? (
                            <span className="text-xs text-muted-foreground font-medium">
                              CANCELLED
                            </span>
                          ) : (
                            <>
                              {showTaskIcon &&
                                getTaskIcon(
                                  task.status,
                                  hasFailedFiles,
                                  isCompletedTotalFailure(task),
                                )}
                              Task {task.task_id.substring(0, 8)}...
                            </>
                          )}
                        </CardTitle>
                        <button
                          type="button"
                          aria-label="Open task details"
                          className="inline-flex shrink-0 items-center justify-center text-muted-foreground hover:text-foreground"
                          onClick={() => openTaskDialog(task.task_id)}
                        >
                          <IncidentReporterIcon className="size-4" />
                        </button>
                      </div>
                      <CardDescription className="text-xs">
                        Started {formatRelative(task.created_at)}
                        {dur && (
                          <span className="ml-2 text-muted-foreground">
                            • {dur}
                          </span>
                        )}
                      </CardDescription>
                    </CardHeader>
                    {(progress || canCancel || isCancelling || isCancelled) && (
                      <CardContent className="p-0 pt-0">
                        {progress && !isCancelling && !isCancelled && (
                          <div className="space-y-2">
                            <div className="text-xs text-muted-foreground">
                              Progress: {progress.basic}
                            </div>
                            {progress.detailed && (
                              <TaskProgressDetails
                                detailed={progress.detailed}
                                isCloudBrand={isCloudBrand}
                              />
                            )}
                          </div>
                        )}
                        {(canCancel || isCancelling || isCancelled) && (
                          <div
                            className={cn(
                              progress &&
                                !isCancelling &&
                                !isCancelled &&
                                "mt-3",
                            )}
                          >
                            <Button
                              type="button"
                              variant="ghost"
                              ignoreTitleCase
                              disabled={isCancelling || isCancelled}
                              onClick={async () => {
                                if (canCancel) {
                                  setCancellingTaskIds((prev) =>
                                    new Set(prev).add(task.task_id),
                                  );
                                  try {
                                    await cancelTask(task.task_id);
                                    // Don't remove from cancellingTaskIds here - let the useEffect clean it up
                                    // when the backend actually returns "cancelled" status
                                  } catch (error) {
                                    // On error, remove from cancelling set immediately
                                    setCancellingTaskIds((prev) => {
                                      const next = new Set(prev);
                                      next.delete(task.task_id);
                                      return next;
                                    });
                                  }
                                }
                              }}
                              title={
                                isCancelled
                                  ? "Task cancelled"
                                  : isCancelling
                                    ? "Cancelling..."
                                    : "Cancel task"
                              }
                              className={cn(
                                cancelTaskButtonClass,
                                (isCancelling || isCancelled) &&
                                  "opacity-50 cursor-not-allowed",
                              )}
                            >
                              {isCancelled
                                ? "Cancelled"
                                : isCancelling
                                  ? "Cancelling..."
                                  : "Cancel task"}
                            </Button>
                          </div>
                        )}
                        {hasFailedFiles && (
                          <div className="mt-3">
                            <TaskErrorContent
                              key={
                                selectedTaskId === task.task_id
                                  ? `${task.task_id}-${selectedTaskTrigger}`
                                  : task.task_id
                              }
                              task={task}
                              mode="recent"
                              showHeader={false}
                              defaultExpanded={selectedTaskId === task.task_id}
                            />
                          </div>
                        )}
                      </CardContent>
                    )}
                  </Card>
                );
              })}
            </div>
          )}

          {/* Past Tasks */}
          <div>
            <TaskCollapsibleSection
              title="Past Tasks"
              items={terminalTasks}
              isOpen={isPastOpen}
              onToggle={() => setIsPastOpen((prev) => !prev)}
              emptyText="No past tasks."
              containerClassName=""
              contentClassName={cn(
                "flex flex-col transition-all duration-200",
                isCloudBrand
                  ? "p-0 [&>*:last-child]:border-b [&>*:last-child]:border-muted"
                  : "gap-2 p-4 pt-2",
              )}
              renderItem={(task) => {
                const progress = formatTaskProgress(task);
                const hasFailedFiles = hasIssueFileEntries(task);
                const isTotalFailure = isCompletedTotalFailure(task);
                const shouldExpandDetails = selectedTaskId === task.task_id;

                // Render detailed failure content only when file-level details exist.
                if (
                  task.status !== "cancelled" &&
                  (isTotalFailure || hasFailedFiles)
                ) {
                  return (
                    <div key={task.task_id} className="group/row">
                      <TaskErrorContent
                        key={
                          shouldExpandDetails
                            ? `${task.task_id}-${selectedTaskTrigger}`
                            : task.task_id
                        }
                        task={task}
                        mode="past"
                        defaultExpanded={shouldExpandDetails}
                        headerEnd={
                          <button
                            type="button"
                            aria-label="Delete task"
                            onClick={(event) => {
                              event.stopPropagation();
                              deleteTaskMutation.mutate(task.task_id);
                            }}
                            className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 hover:bg-muted hover:text-foreground transition-colors focus-visible:ring-1 focus-visible:ring-ring"
                          >
                            <X className="size-4" />
                          </button>
                        }
                      />
                    </div>
                  );
                }

                return (
                  <div
                    key={task.task_id}
                    className={`${pastTaskRowClass} group/row`}
                  >
                    <div className="flex items-start gap-3">
                      {!isCloudBrand && getTaskIcon(task.status)}
                      <div className="flex-1 min-w-0">
                        <div className="text-xs font-medium truncate">
                          Task {task.task_id.substring(0, 8)}...
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {formatTaskTimestamp(
                            parseTimestamp(task.updated_at),
                            "past",
                            Date.now(),
                          )}
                        </div>
                        {task.status === "completed" && progress?.detailed && (
                          <div className="text-xs text-muted-foreground">
                            {progress.detailed.successful} success,{" "}
                            {progress.detailed.failed} failed
                            {(progress.detailed.running || 0) > 0 && (
                              <span>, {progress.detailed.running} running</span>
                            )}
                          </div>
                        )}
                      </div>
                      <div className="self-start pt-0.5 flex items-center gap-1.5 shrink-0">
                        {getStatusBadge(task.status, isCloudBrand)}
                        <button
                          type="button"
                          aria-label="Delete task"
                          onClick={(event) => {
                            event.stopPropagation();
                            deleteTaskMutation.mutate(task.task_id);
                          }}
                          className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 hover:bg-muted hover:text-foreground transition-colors focus-visible:ring-1 focus-visible:ring-ring"
                        >
                          <X className="size-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                );
              }}
            />
          </div>

          {/* Empty State */}
          {activeTasks.length === 0 && terminalTasks.length === 0 && (
            <div className="p-8 text-center">
              <Bell className="h-12 w-12 text-muted-foreground/50 mx-auto mb-4" />
              <h4 className="text-sm font-medium text-muted-foreground mb-2">
                No tasks yet
              </h4>
              <p className="text-xs text-muted-foreground">
                Task notifications will appear here when you upload files or
                sync connectors.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}