Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
12.2 KB
Raw Blame
import { Check16, Clock16, Dismiss16, Download16, Warning16, WorkQueue32 } from "./ui/icons";
import { useState, useSyncExternalStore, type RefObject } from "react";
import { GENERATION_FRAME_RATE } from "../lib/project";
import { isWorkActive, type WorkItem, type WorkQueue } from "../lib/workQueue";
import { loadGeneratorTemplateSettings } from "../lib/settings";
import { cancelExportJob, clearFinishedExports, exportFraction, isExportActive, useExportJobs } from "../lib/exportJob";
import { cancelQueuedWeightDownload, getQueuedWeightDownloads, cancelWeightDownload, retryWeightDownload, getWeightDownloadState, subscribeWeightDownloads, weightDownloadProgress, type DownloadState } from "../lib/weightDownloads";
import { Flyout, ProgressBar, ProgressRing } from "./ui";

/* The work queue, as a flyout hanging from its title-bar button: no scrim, no
   focus trap, light dismiss (a click outside, Esc, the window losing focus).
   One flat list — what is running, the weight download, what is up next,
   what has finished — each row an icon, a title, one caption line and, while
   it runs, a 3px bar. The render settings a row was queued with sit in its
   tooltip rather than on a third line. */

const settingsLine = (item: WorkItem) => item.kind === "music" ? `Music · ${item.settings.steps} steps · Seed ${item.settings.seed}` : item.kind === "refmod" ? "Safetensors refmod" : `${item.settings.canvasWidth} × ${item.settings.canvasHeight} · ${item.kind === "reference-icons" ? "JPG icons" : item.kind === "album-cover" ? "Album cover" : item.kind === "image" ? "JPG image" : `${(item.settings.frames / GENERATION_FRAME_RATE).toFixed(1)}s`} · ${item.settings.steps} steps${item.settings.audioSteps !== undefined ? ` · ${item.settings.audioSteps} audio steps` : ""} · ${item.settings.seed === -1 ? "Random seed" : `Seed ${item.settings.seed}`}`;

function StateGlyph({ item }: { item: WorkItem }) {
  if (item.status === "completed") return <Check16 />;
  if (item.status === "failed") return <Warning16 />;
  if (item.status === "queued") return <Clock16 />;
  if (item.status === "cancelled") return <Dismiss16 />;
  return <ProgressRing size={16} />;
}

export type WorkQueueTarget = { kind: "work"; item: WorkItem }
  | { kind: "download"; download: DownloadState }
  | { kind: "export"; folderPath: string; exportKind?: "video" | "image" | "music" };

export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClose, onNavigate }: {
  queue: WorkQueue;
  items: readonly WorkItem[];
  /** Default true, so it can be rendered conditionally. */
  open?: boolean;
  /** The title-bar button it hangs from. */
  anchor?: RefObject<HTMLElement | null> | null;
  onClose: () => void;
  onNavigate?: (target: WorkQueueTarget) => void;
}) {
  // Downloads are observed here, never enqueued in the GPU generation scheduler.
  const download = useSyncExternalStore(subscribeWeightDownloads, getWeightDownloadState);
  const queuedDownloads = useSyncExternalStore(subscribeWeightDownloads, getQueuedWeightDownloads);
  const [downloadError, setDownloadError] = useState<string | null>(null);
  const downloadName = download ? download.name ?? loadGeneratorTemplateSettings().templates.find((template) => template.id === download.templateId)?.name ?? "Generator weights" : "";
  /* A running export lives in lib/exportJob.ts, not in the generation queue;
     it is shown here so it can be followed (and stopped) from anywhere. */
  const exports = useExportJobs();
  const finishedExports = exports.filter((job) => !isExportActive(job));
  const current = items.filter((item) => isWorkActive(item) && item.status !== "queued");
  const upcoming = items.filter((item) => item.status === "queued").sort((a, b) => Number(a.kind === "reference-icons") - Number(b.kind === "reference-icons"));
  const finished = items.filter((item) => !isWorkActive(item)).slice().reverse();
  const openTarget = (target: WorkQueueTarget) => { onClose(); onNavigate?.(target); };

  const row = (item: WorkItem) => {
    const running = isWorkActive(item) && item.status !== "queued";
    return <li className={`work-queue__row${onNavigate ? " work-queue__row--navigable" : ""}`} key={item.id}>
      {onNavigate && <button type="button" className="work-queue__open" aria-label={`Open ${item.title} in ${item.projectName}`} data-tooltip={`${item.title} — ${settingsLine(item)}`} onClick={() => openTarget({ kind: "work", item })} />}
      <span className={`work-queue__state work-queue__state--${item.status}`} aria-hidden="true"><StateGlyph item={item} /></span>
      <div className="work-queue__text">
        <span className="work-queue__title" data-tooltip={`${item.title} — ${settingsLine(item)}`}>{item.title}</span>
        <span className="work-queue__caption" data-tooltip={item.folderPath}>{item.projectName} · {item.detail}{running ? ` · ${Math.floor(item.progress * 100)}%` : ""}</span>
        {running && <ProgressBar value={item.progress * 100} aria-label={`${item.title} progress`} className="work-queue__progress" />}
        {item.error && <span className="work-queue__error">{item.error}</span>}
        {item.needsSave && <button type="button" className="work-queue__link" onClick={() => void queue.retrySave(item.id)}>Retry project save</button>}
      </div>
      {isWorkActive(item) && item.status !== "encoding" && (
        <button type="button" className="icon-button work-queue__cancel" disabled={item.cancelling} aria-label={`Cancel ${item.title} in ${item.projectName}`} data-tooltip="Cancel" onClick={() => void queue.cancel(item.id)}><Dismiss16 /></button>
      )}
    </li>;
  };

  return (
    <Flyout open={open} anchor={anchor} onClose={onClose} placement="bottom" aria-labelledby="work-queue-title" className="work-queue" width={360}>
      <header className="work-queue__header">
        <h2 id="work-queue-title">Work queue</h2>
        {(finished.length > 0 || finishedExports.length > 0) && <button type="button" className="work-queue__link" onClick={() => { queue.clearFinished(); clearFinishedExports(); }}>Clear finished</button>}
      </header>
      <div className="work-queue__list">
        {items.length === 0 && !download && !queuedDownloads.length && !exports.length && <div className="work-queue__empty"><WorkQueue32 aria-hidden="true" /><strong>No work yet</strong><span>Generation, exports, and downloads show up here.</span></div>}
        {current.length > 0 && <section aria-label="In progress"><ul>{current.map(row)}</ul></section>}
        {exports.length > 0 && <section aria-label="Export"><ul>{exports.map((exportJob) => {
          const exportTitle = exportJob.kind === "image" ? `Export image · ${exportJob.projectName}` : exportJob.kind === "music" ? `Export music · ${exportJob.projectName}` : `Export ${exportJob.projectName ?? ""}`;
          const exporting = exportJob.progress;
          const exportPercent = Math.floor(exportFraction(exporting) * 100);
          return <li key={exportJob.id} className={`work-queue__row${onNavigate && exportJob.folderPath ? " work-queue__row--navigable" : ""}`}>
          {onNavigate && exportJob.folderPath && <button type="button" className="work-queue__open" aria-label={`Open ${exportTitle}`} onClick={() => openTarget({ kind: "export", folderPath: exportJob.folderPath!, exportKind: exportJob.kind })} />}
          <span className={`work-queue__state work-queue__state--${exportJob.status}`} aria-hidden="true">{exportJob.status === "queued" ? <Clock16 /> : exportJob.status === "running" ? <ProgressRing size={16} /> : exportJob.status === "completed" ? <Check16 /> : exportJob.status === "failed" ? <Warning16 /> : <Dismiss16 />}</span>
          <div className="work-queue__text">
            <span className="work-queue__title" data-tooltip={exportJob.destination ?? undefined}>{exportTitle}</span>
            <span className="work-queue__caption">{exporting ? `${exporting.detail || "Exporting"} · ${exportPercent}%` : exportJob.status === "queued" ? "Queued for export" : exportJob.status === "completed" ? `Saved · ${exportJob.destination}` : exportJob.status === "failed" ? "Export failed" : "Cancelled"}</span>
            {exporting && <ProgressBar value={exportJob.kind === "image" && exportPercent === 0 ? undefined : exportPercent} aria-label={`${exportTitle} progress`} className="work-queue__progress" />}
            {exportJob.outcome?.kind === "failed" && <span className="work-queue__error">{exportJob.outcome.message}</span>}
          </div>
          {isExportActive(exportJob) && <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${exportTitle}`} data-tooltip="Cancel" disabled={exportJob.cancelling} onClick={() => cancelExportJob(exportJob.id)}><Dismiss16 /></button>}
        </li>; })}</ul></section>}
        {download && <section aria-label="Weight downloads"><ul><li className={`work-queue__row${onNavigate ? " work-queue__row--navigable" : ""}`}>
          {onNavigate && <button type="button" className="work-queue__open" aria-label={`Open ${downloadName} download`} onClick={() => openTarget({ kind: "download", download })} />}
          <span className={`work-queue__state work-queue__state--${download.active ? "preparing" : download.error ? "failed" : "completed"}`} aria-hidden="true">
            {download.active ? <Download16 /> : download.error ? <Warning16 /> : <Check16 />}
          </span>
          <div className="work-queue__text">
            <span className="work-queue__title">{downloadName}</span>
            <span className="work-queue__caption">
              {download.loraId ? "LoRA download" : "Weight download"} · {download.active
                ? download.phase === "preparing" ? "Preparing LoRA…" : `${download.currentFile ? `${download.currentFile} · ` : ""}${download.completed}/${download.files} files · ${(download.downloaded / 1024 ** 3).toFixed(2)} GB${download.total ? ` of ${(download.total / 1024 ** 3).toFixed(2)} GB` : ""} · ${Math.floor(weightDownloadProgress(download))}%`
                : download.error ? "Failed" : "Download complete"}
            </span>
            {download.active && <ProgressBar value={download.phase === "preparing" ? undefined : weightDownloadProgress(download)} aria-label={`${downloadName} download progress`} className="work-queue__progress" />}
            {download.error && <span className="work-queue__error">{download.error}</span>}
            {download.error && <button type="button" className="work-queue__link" onClick={() => { setDownloadError(null); void retryWeightDownload(); }}>Retry download</button>}
            {downloadError && <span className="work-queue__error" role="alert">{downloadError}</span>}
          </div>
          {download.active && download.phase !== "preparing" && <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${downloadName} download`} data-tooltip="Cancel" onClick={() => {
            setDownloadError(null);
            void cancelWeightDownload().catch((reason) => setDownloadError(String(reason)));
          }}><Dismiss16 /></button>}
        </li></ul></section>}
        {(upcoming.length > 0 || queuedDownloads.length > 0) && <section aria-label="Upcoming work"><h3 className="work-queue__group">Up next · {upcoming.length + queuedDownloads.length}</h3><ul>
          {queuedDownloads.map((waiting) => <li key={waiting.templateId} className={`work-queue__row${onNavigate ? " work-queue__row--navigable" : ""}`}>
            {onNavigate && <button type="button" className="work-queue__open" aria-label={`Open ${waiting.name} download`} onClick={() => openTarget({ kind: "download", download: waiting })} />}
            <span className="work-queue__state work-queue__state--queued" aria-hidden="true"><Clock16 /></span>
            <div className="work-queue__text"><span className="work-queue__title">{waiting.name ?? "Weights"}</span><span className="work-queue__caption">Queued for download</span></div>
            <button type="button" className="icon-button work-queue__cancel" aria-label={`Cancel ${waiting.name} download`} data-tooltip="Cancel" onClick={() => cancelQueuedWeightDownload(waiting.templateId)}><Dismiss16 /></button>
          </li>)}
          {upcoming.map(row)}
        </ul></section>}
        {finished.length > 0 && <section aria-label="Finished work"><h3 className="work-queue__group">Finished</h3><ul>{finished.map(row)}</ul></section>}
      </div>
    </Flyout>
  );
}