All files / src/pages/flowsheet-page/flowsheet/LeftSideBar TasksPanel.tsx

88.05% Statements 59/67
71.42% Branches 40/56
100% Functions 18/18
88.05% Lines 59/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                            2788x                             2578x                   21878x   21878x                             21878x   12036x       1052x           8787x           3x               33x 641x 641x   641x               21878x 21878x 21878x       21878x       21878x     21878x   21878x       21878x 21878x       21878x 19637x 2241x 2241x 2241x                 21878x   21878x     21878x 21878x   21878x 1x 1x 1x         1x           21878x                                                   1608x 1608x 1608x       642x 642x       642x   642x                                           929x 633x               296x       929x             210x                                                                           1608x     21876x 21876x                                       1415x     1415x       1415x                 1065x   1065x 1065x         1065x                                                      
import { Separator } from "@/ahuora-design-system/ui/separator";
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from "../../../../ahuora-design-system/ui/accordion";
import { NoTabsLeftSideBar } from "./sidebar-structure";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Spinner } from "@/ahuora-design-system/ui/spinner";
import { ReadyState } from "react-use-websocket";
import {
  StatusEnum,
  TaskMetaRead,
  TaskRead,
  useCoreTasksChildrenListQuery,
  useCoreTasksListQuery, useIdaesCancelSolveCreateMutation,
} from "@/api/apiStore.gen.ts";
import { ReactElement, useCallback, useState } from "react";
import { useProjectId } from "@/hooks/project.ts";
import { Ban, Check, Circle, CircleDot } from "lucide-react";
import { cn } from "@/lib/utils";
import { useNotificationConnection } from "@/hooks/notifications/useNotificationConnection.ts";
import { TruncateText } from "../../../../ahuora-design-system/ui/truncate-text";
import Paginator from "@/ahuora-design-system/ui/paginator";
import { X } from "lucide-react";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
 
 
function TimingItem({ name, value }: { name: string; value: object }) {
    return (
        // if the value is an object, loop through the object and display the key value pairs
        // otherwise, display the key value pair
        <>
            <div className="flex flex-row">
                <p className="text-sm text-zinc-500">{name}</p>
                <p className="text-sm break-all">{value["duration"]?.toFixed(3)}</p>
            </div>
            {Object.keys(value["children"]).length > 0 && (
                <div className=" flex flex-row">
                    <div className="min-h-full">
                        <Separator orientation="vertical" />
                    </div>
                    <div>
                        {Object.entries(value["children"]).map(([name, value], i) => (
                            <TimingItem key={i} name={name} value={value} />
                        ))}
                    </div>
                </div>
            )}
        </>
    );
}
 
function TaskStatusBadge({ status }: { status: StatusEnum }) {
    const createStatusBadge = useCallback(
        (status: StatusEnum, icon: ReactElement, extraCSS: string) => {
            return (
                <Badge
                    className={cn(
                        "capitalize flex flex-row gap-2 h-fit items-center mr-1 text-muted-foreground border-none pointer-events-none",
                        extraCSS
                    )}
                >
                    {status}
                    {icon}
                </Badge>
            );
        },
        []
    );
 
  switch (status) {
    case StatusEnum.Completed:
      return createStatusBadge(status, <Check color="white" />, "bg-primary");
    case StatusEnum.Failed:
      return createStatusBadge(status, <Ban color="white" />, "bg-destructive");
    case StatusEnum.Running:
      return createStatusBadge(
        status,
        <Spinner size="small" color="white" />,
        "bg-blue-500",
      );
    case StatusEnum.Pending:
      return createStatusBadge(
        status,
        <CircleDot color="white" />,
        "bg-amber-600",
      );
    case StatusEnum.Cancelled:
      return createStatusBadge(
          status,
          <Ban color="white" />,
          "bg-gray-500",
      );
  }
}
 
const ParentTaskDetails = ({ task }: { task: TaskRead }) => {
    const metadata = task.metadata as TaskMetaRead;
    const finished_tasks = metadata.failed_tasks + metadata.successful_tasks;
 
    return (
        <small className="text-zinc-300">
            {finished_tasks}/{metadata.scheduled_tasks} subtasks completed
        </small>
    );
};
 
function TaskItemHeader({ task, index }: { task: TaskRead; index: number }) {
    const getStartTimeMessage = (task: TaskRead): string => {
        const startTime = new Date(task.start_time);
        const completed_time = task.completed_time
            ? new Date(task.completed_time)
            : null;
 
        Iif (startTime === undefined) {
            return "Unknown start time";
        }
 
        const taskIsDone = [StatusEnum.Completed, StatusEnum.Failed].includes(
            task.status as StatusEnum
        );
        const secondsSinceStarted =
            (new Date().getTime() - startTime.getTime()) / 1000;
        const secondsSinceCompleted = completed_time
            ? (new Date().getTime() - completed_time.getTime()) / 1000
            : null;
 
        let timeUnit: string = "";
        const secondsDuration = taskIsDone
            ? (secondsSinceCompleted as number)
            : secondsSinceStarted;
 
        if (secondsDuration < 60) {
            timeUnit = `${Math.floor(secondsDuration)} seconds ago`;
        } else if (secondsDuration < 3600) {
            const minutes = Math.floor(secondsDuration / 60);
            timeUnit = `${minutes} ${minutes > 1 ? "minutes" : "minute"} ago`;
        E} else if (secondsDuration < 86400) {
            const hours = Math.floor(secondsDuration / 3600);
            timeUnit = `${hours} ${hours > 1 ? "hours" : "hour"} ago`;
        } else {
            const days = Math.floor(secondsDuration / 86400);
            timeUnit = `${days} ${days > 1 ? "days" : "day"} ago`;
        }
 
        const prefix = taskIsDone ? "Finished" : "Started";
 
        return `${prefix} ${timeUnit}.`;
    };
 
  const isParentTask = task.metadata != undefined;
  const [requestCancel] = useIdaesCancelSolveCreateMutation()
 
  const handleCancel = async (e) => {
    e.preventDefault() // stop it from propagating to the accordion item
    try {
      const response = await requestCancel({
        cancelTaskRequest: {
          task_id: task.id, // Dynamically pass the task ID
        },
      }).unwrap();
      console.log("Task canceled successfully:", response);
    } catch (error) {
      console.error("Error canceling task:", error);
    }
  };
 
    return (
        <div className="w-full h-full flex flex-row py-2 gap-1 items-center">
            <div className="w-full flex flex-col gap-1 text-left">
                <h3>Task {index + 1}: {task.task_type}</h3>
                {isParentTask && <ParentTaskDetails task={task} />}
                <span className="text-xs text-zinc-400 italic">
                    {getStartTimeMessage(task)}
                </span>
            </div>
            <TaskStatusBadge status={task.status} />
            {(task.status === StatusEnum.Running || task.status === StatusEnum.Pending) && (
              <ToolTipCover content="Cancel Task">
              <button
                onClick={handleCancel}
                className="text-xs text-red-500 underline p-1"
                aria-label="Cancel Task"
              >
                <X size={16} />
              </button>
              </ToolTipCover>
            )}
        </div>
    );
}
 
function getMaxNumber(data, page) {
    const count = data?.count || 0;
    const pageSize = data?.page_size || 1;
    return count - (page - 1) * pageSize;
}
 
function ParentTaskItemContent({ task }: { task: TaskRead }) {
    const [page, setPage] = useState(1)
    const { data: tasksPage } = useCoreTasksChildrenListQuery({
        id: task.id,
        page: page,
    });
    const childTasks = tasksPage?.results || [];
 
    return (
        <div className="flex flex-col gap-2">
            <div className="px-4 flex justify-between">
                <p className="text-sm text-zinc-500">Subtasks:</p>
                <Paginator
                    page={page}
                    setPage={setPage}
                    data={tasksPage}
                    minimal
                />
            </div>
            {childTasks.length > 0 ? (
                <TaskList tasks={childTasks} max={getMaxNumber(tasksPage, page)} />
            ) : (
                <p className="text-sm text-zinc-500">No subtasks found.</p>
            )}
        </div>
    );
}
 
function TaskItemContent({ task }: { task: TaskRead }) {
    // If the task has metadata, it is a parent task and we need to show the subtasks
    if (task.metadata) {
        return (
            <div>
                <ParentTaskItemContent task={task} />
                <TaskDebugContent task={task} />
            </div>
        );
    }
 
    return <TaskDebugContent task={task} />;
}
 
function TaskDebugContent({ task }: { task: TaskRead }) {
    return (
        <div>
            <p>Timing:</p>
            {task.debug?.timing && (
                <div className="py-2 flex-grow flex flex-col  break-all">
                    {/* loop through the timing object and display the key value pairs */}
                    {Object.entries(task.debug.timing).map(([name, value], i) => (
                        <TimingItem key={i} name={name} value={value} />
                    ))}
                </div>
            )}
            <p>Log:</p>
            <TruncateText length={150} ariaLabel="logpanel-solver-log">
                {task.log}
            </TruncateText>
            {task.error && (
                <div className="flex flex-col text-wrap">
                    <Separator />
                    <h3 className="mt-2">Debug Information:</h3>
                    <div>
                        <p className="text-sm text-zinc-500 text-wrap">Source:</p>
                        <div className=" text-sm">{task.error.cause}</div>
                        <p className="text-sm text-zinc-500 text-wrap">Message:</p>
                        <div className="text-sm  text-wrap whitespace-pre-line">
                            {JSON.stringify(task.error.message)}
                        </div>
                        {task.error.traceback && (
                            <div className="text-wrap break-words">
                                <p className="text-sm text-zinc-500 text-wrap  break-all">
                                    Traceback:
                                </p>
                                <TruncateText length={150} ariaLabel="logpanel-traceback">
                                    {task.error.traceback}
                                </TruncateText>
                            </div>
                        )}
                    </div>
                </div>
            )}
            <Separator />
        </div>
    );
}
 
function TaskList({ tasks, max }: { tasks: TaskRead[], max: number }) {
    return (
        <Accordion type="single" className="" collapsible aria-label="task-list">
            {tasks.map((task, i) => {
                const index = max - i - 1; // Most recent solve has highest index
                return (
                    <AccordionItem key={"log-" + index} value={"log-" + index}>
                        <AccordionTrigger
                            className="py-1"
                            aria-label={"log-" + index}
                            variant="objectPanel"
                        >
                            <TaskItemHeader task={task} index={index} />
                        </AccordionTrigger>
                        <AccordionContent className="flex flex-col gap-2">
                            <TaskItemContent task={task} />
                        </AccordionContent>
                    </AccordionItem>
                );
            })}
        </Accordion>
    );
}
 
function LiveUpdatesStatus() {
    const { readyState } = useNotificationConnection(() => { });
 
    const [text, colour] =
        readyState == ReadyState.OPEN
            ? ["Receiving live updates", "fill-green-500"]
            : ["Live updates unavailable", "fill-orange-500"];
 
    return (
        <div className="flex flex-row items-center gap-2 m-4">
            <Circle className={cn("stroke-0 icon-small", colour)} />
            <p>{text}</p>
        </div>
    );
}
 
export default function TasksPanel() {
    const [page, setPage] = useState(1)
 
    const flowsheetId = useProjectId();
    const { data: tasksPage } = useCoreTasksListQuery({
        page: page,
        flowsheet: flowsheetId,
    });
 
    return (
        <NoTabsLeftSideBar
            title="Task Logs"
            noBodyMargin={true}
            body={
                <div>
 
                    <div className="px-4 flex justify-between">
                        <LiveUpdatesStatus />
                        <Paginator
                            page={page}
                            setPage={setPage}
                            data={tasksPage}
                            minimal
                        />
                    </div>
 
                    {tasksPage === undefined || tasksPage?.count === 0 ? (
                        <p className="p-4">No tasks have been run yet.</p>
                    ) : (
                        <TaskList tasks={tasksPage?.results || []} max={getMaxNumber(tasksPage, page)} />
                    )}
                </div>
            }
        />
    );
}