Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

10.0 KB
Raw Blame
import type { QueueActivity } from '@features/queue/core/queueActivity';

import { Box, Stack, VisuallyHidden } from '@chakra-ui/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { LIST_ROW_GAP_PX } from '@platform/ui/list/listLayout';
import { ListSectionHeader } from '@platform/ui/list/ListSectionHeader';
import { RetryBoundary } from '@platform/ui/RetryBoundary';
import { Scrollable } from '@platform/ui/Scrollable';
import { StatusWidgetChip } from '@platform/ui/StatusWidgetChip';
import { CloudOffIcon, ListOrderedIcon, PauseIcon, type LucideIcon } from 'lucide-react';
import {
  lazy,
  Suspense,
  useEffectEvent,
  useState,
  useSyncExternalStore,
  type ComponentProps,
  type ComponentType,
} from 'react';
import { useTranslation } from 'react-i18next';

import type * as LocalRunListExports from './LocalRunList';
import type { QueueFilterId } from './queueFilters';
import type { QueueLocalRun } from './QueueUiContext';

import { CurrentBatchSection } from './NowNextSection';
import { useQueueReadModelData } from './queueDataStore';
import { QueueFilterTabs } from './QueueFilterTabs';
import { useShownLocalRuns } from './queueScope';
import { useQueueUi } from './QueueUiContext';
import { usePendingQueueItemReveal } from './queueUiStore';
import { RecentSection } from './RecentSection';
import { useQueueWidgetActivity } from './useQueueWidgetActivity';

type LocalRunListModule = Pick<typeof LocalRunListExports, 'LocalRunList'>;

type LocalRunListRows = ComponentType<ComponentProps<typeof LocalRunListExports.LocalRunList>>;

export interface LocalRunListLoader {
  /** Replaced on Retry, since `React.lazy` keeps its first rejection. */
  getSnapshot(): { Rows: LocalRunListRows };
  preload(): void;
  retry(): Promise<unknown>;
  subscribe(listener: () => void): () => void;
}

/** Loads with the first unaccepted run, not the widget; a failed import stays failed until Retry. */
export const createLocalRunListLoader = (importer: () => Promise<LocalRunListModule>): LocalRunListLoader => {
  const listeners = new Set<() => void>();
  let failed = false;
  let rows: Promise<{ default: typeof LocalRunListExports.LocalRunList }> | null = null;
  const load = () => {
    if (!rows) {
      const next = importer().then((module) => ({ default: module.LocalRunList }));
      rows = next;
      next.catch(() => {
        if (rows === next) {
          failed = true;
        }
      });
    }

    return rows;
  };
  let snapshot: { Rows: LocalRunListRows } = { Rows: lazy(load) };

  return {
    getSnapshot: () => snapshot,
    preload: () => {
      void load().catch(() => undefined);
    },
    retry: () => {
      if (failed) {
        failed = false;
        rows = null;
        snapshot = { Rows: lazy(load) };
        listeners.forEach((listener) => listener());
      }

      return load();
    },
    subscribe: (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
  };
};

const localRunList = createLocalRunListLoader(() => import('./LocalRunList'));

/** Queue cannot import Workbench. */
export interface QueueWidgetRuntime {
  commands: {
    register(command: { handler: () => unknown; id: string; title: string }): () => void;
  };
}

type QueueWidgetRegion = 'bottom' | 'center' | 'dialog' | 'floating' | 'left' | 'popover' | 'right';

export const QueueWidgetView = ({
  presentation,
  region,
  runtime,
}: {
  presentation?: 'compact' | 'expanded' | 'tooltip';
  region: QueueWidgetRegion;
  runtime: QueueWidgetRuntime;
}) => {
  if (region === 'bottom' && presentation !== 'expanded') {
    return <QueueStatusChip />;
  }

  return <QueueContent region={region} runtime={runtime} />;
};

/** The Workbench's hotkey catalog binds `queue.recallAll` (A) to it, claimed only on a row offering recall. */
const QUEUE_RECALL_ALL_COMMAND = 'queue.recallAll';

/** The key goes to the focused element, so that is the row it names. */
const QueueRecallAllCommand = ({ runtime }: { runtime: QueueWidgetRuntime }) => {
  const { t } = useTranslation();
  const { recallAllFromItem } = useQueueUi();
  const readModel = useQueueReadModelData();
  const recallFocusedItem = useEffectEvent(() => {
    const itemId = Number(
      document.activeElement?.closest('[data-queue-recall-item]')?.getAttribute('data-queue-recall-item')
    );
    const item = readModel
      ? [readModel.current, readModel.next, ...readModel.items].find((candidate) => candidate?.id === itemId)
      : undefined;

    if (item) {
      recallAllFromItem(item);
    }
  });

  /* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */
  useMountEffect(() =>
    runtime.commands.register({
      handler: () => recallFocusedItem(),
      id: QUEUE_RECALL_ALL_COMMAND,
      title: t('widgets.queue.recallAll'),
    })
  );
  /* eslint-enable react-hooks/rules-of-hooks */

  return null;
};

const QueueContent = ({ region, runtime }: { region: QueueWidgetRegion; runtime: QueueWidgetRuntime }) => {
  const { i18n, t } = useTranslation();
  const [filter, setFilter] = useState<QueueFilterId>('all');
  const revealRequest = usePendingQueueItemReveal();
  const { activeProjectId, localRuns } = useQueueUi();
  const shownLocalRuns = useShownLocalRuns();
  const [handledRevealRequestId, setHandledRevealRequestId] = useState<number | null>(null);

  // Adjust the active tab during render so it cannot hide a requested item.
  if (revealRequest !== null && revealRequest.requestId !== handledRevealRequestId) {
    setHandledRevealRequestId(revealRequest.requestId);
    setFilter('all');
  }

  // Sections bleed out of the list padding, so the extra row gap keeps row surfaces off the panel edges.
  return (
    <Stack gap="2" h="full" minH="0" pt="2">
      <QueueRecallAllCommand key={`${activeProjectId}:${region}:${i18n.language}`} runtime={runtime} />
      {localRuns.length > 0 ? <LocalRunListPreload rows={localRunList} /> : null}
      <Box flexShrink={0} px="2">
        <QueueFilterTabs localRunCount={shownLocalRuns.length} value={filter} onChange={setFilter} />
      </Box>
      <Scrollable flex="1" label={t('widgets.queue.items')} minH="0" overflowX="hidden">
        <Stack gap="3" pb="2" px={`calc(0.5rem + ${LIST_ROW_GAP_PX}px)`}>
          <LocalRunsSection filter={filter} rows={localRunList} runs={shownLocalRuns} />
          <CurrentBatchSection filter={filter} revealRequest={revealRequest} />
          <RecentSection filter={filter} revealRequest={revealRequest} />
        </Stack>
      </Scrollable>
    </Stack>
  );
};

const LocalRunListPreload = ({ rows }: { rows: LocalRunListLoader }) => {
  useMountEffect(rows.preload);
  return null;
};

/** The backend has no row for these, so this is the only place to see why they wait and cancel them. */
export const LocalRunsSection = ({
  filter,
  rows,
  runs,
}: {
  filter: QueueFilterId;
  rows: LocalRunListLoader;
  runs: readonly QueueLocalRun[];
}) => {
  const { t } = useTranslation();
  const current = useSyncExternalStore(rows.subscribe, rows.getSnapshot, rows.getSnapshot);
  const isListed = runs.length > 0 && (filter === 'all' || filter === 'active');

  return (
    <>
      <LocalRunAnnouncements runs={runs} />
      {isListed ? (
        // Row surfaces bleed into the widget padding so their content lines up with the controls above.
        <Stack gap="1" mx="-2">
          <ListSectionHeader count={runs.length} label={t('widgets.queue.localRuns.title')} />
          <RetryBoundary
            message={t('widgets.queue.localRuns.loadFailed')}
            retry={rows.retry}
            retryLabel={t('common.retry')}
          >
            <Suspense fallback={null}>
              <current.Rows filter={filter} runs={runs} />
            </Suspense>
          </RetryBoundary>
        </Stack>
      ) : null}
    </>
  );
};

const RETRY_ANNOUNCEMENT_KEYS = {
  error: 'widgets.queue.localRuns.announcement.error',
  'server-error': 'widgets.queue.localRuns.announcement.serverError',
  unavailable: 'widgets.queue.localRuns.announcement.unavailable',
  unreachable: 'widgets.queue.localRuns.announcement.unreachable',
} satisfies Record<NonNullable<QueueLocalRun['retry']>['reason'], string>;

/**
 * One line per retried run keyed by its reason, so it speaks only when retrying starts or the reason changes.
 * Stays mounted whatever the filter: a region inserted with its text is not announced.
 */
const LocalRunAnnouncements = ({ runs }: { runs: readonly QueueLocalRun[] }) => {
  const { t } = useTranslation();

  return (
    <VisuallyHidden aria-atomic="false" aria-live="polite" as="div" role="status">
      {runs.map((run) =>
        run.retry ? (
          <div key={`${run.projectId}:${run.id}:${run.retry.reason}`}>
            {t(RETRY_ANNOUNCEMENT_KEYS[run.retry.reason], {
              name: run.label || t('widgets.queue.localRuns.untitled'),
            })}
          </div>
        ) : null
      )}
    </VisuallyHidden>
  );
};

const chipIcons = {
  idle: ListOrderedIcon,
  'loading-model': ListOrderedIcon,
  offline: CloudOffIcon,
  paused: PauseIcon,
  running: ListOrderedIcon,
} satisfies Record<QueueActivity, LucideIcon>;

const QueueStatusChip = () => {
  const { t } = useTranslation();
  const { activity, inProgress, loadingModel, pending } = useQueueWidgetActivity();
  const openCount = inProgress + pending;
  const label =
    activity === 'offline'
      ? t('widgets.queueStatus.offline', { count: openCount })
      : activity === 'paused'
        ? t('widgets.queueStatus.paused', { count: openCount })
        : activity === 'loading-model'
          ? t('widgets.queue.loadingModel', { model: loadingModel })
          : inProgress > 0
            ? t('widgets.queue.generating', { count: inProgress })
            : t('widgets.queue.queued', { count: pending });

  return (
    <StatusWidgetChip
      icon={chipIcons[activity]}
      tone={
        activity === 'offline'
          ? 'warning'
          : activity === 'running' || activity === 'loading-model'
            ? 'accent'
            : undefined
      }
    >
      {label}
    </StatusWidgetChip>
  );
};