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.

feat(queue): add server-backed queue widget

joshistoast9de16cc20507
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
index e7bff19d49..64ed692e44 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
@@ -14,7 +14,6 @@ import type {
const defaultBottomInstanceIds: WidgetInstanceId[] = [
'server-status',
'diagnostics:bottom',
- 'queue:bottom',
'gallery:bottom',
'notifications',
'autosave-status',
@@ -36,7 +35,6 @@ const defaultInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {
preview: 'preview',
project: 'project',
queue: 'queue',
- 'queue:bottom': 'queue',
'server-status': 'server-status',
'version-status': 'version-status',
workflow: 'workflow',
@@ -119,7 +117,7 @@ export const layoutPresets: LayoutPreset[] = [
panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },
widgetRegions: {
bottom: createRegion({
- activeInstanceId: 'queue:bottom',
+ activeInstanceId: 'gallery:bottom',
instanceIds: defaultBottomInstanceIds,
isCollapsed: true,
sizePx: 180,
@@ -169,7 +167,7 @@ export const layoutPresets: LayoutPreset[] = [
panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },
widgetRegions: {
bottom: createRegion({
- activeInstanceId: 'queue:bottom',
+ activeInstanceId: 'gallery:bottom',
instanceIds: defaultBottomInstanceIds,
isCollapsed: true,
sizePx: 180,
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
index 78938f01c1..c30e22ca7c 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
@@ -43,6 +43,7 @@ import {
DatabaseIcon,
FolderIcon,
KeyboardIcon,
+ ListOrderedIcon,
PaletteIcon,
RotateCcwIcon,
SettingsIcon,
@@ -224,6 +225,12 @@ const SettingsTabs = () => {
label: 'Project',
value: 'project',
},
+ {
+ children: <QueueSection />,
+ icon: ListOrderedIcon,
+ label: 'Queue',
+ value: 'queue',
+ },
{
children: <WorkflowSection />,
icon: WorkflowIcon,
@@ -590,6 +597,27 @@ const WorkflowSection = () => {
);
};
+const QueueSection = () => {
+ const { queueJobsScope } = useWorkbenchPreferences();
+ const updateQueueJobsScope = useCallback((value: string) => {
+ updatePreferences({ queueJobsScope: value === 'active-project' ? 'active-project' : 'all' });
+ }, []);
+
+ return (
+ <SettingsSection description="Choose which jobs the Queue widget includes in its counts and lists." title="Queue">
+ <SettingSelect
+ description="Show jobs from only the active project, or all queue jobs visible to you."
+ label="Show jobs from"
+ value={queueJobsScope}
+ onChange={updateQueueJobsScope}
+ >
+ <option value="active-project">Active project</option>
+ <option value="all">All</option>
+ </SettingSelect>
+ </SettingsSection>
+ );
+};
+
const DeveloperSection = () => {
const { developerLogEnabled, developerLogLevel, developerLogNamespaces } = useWorkbenchPreferences();
const enabledNamespaces = useMemo(() => new Set(developerLogNamespaces), [developerLogNamespaces]);
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
index a87be30b6d..09dcbea437 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
@@ -223,3 +223,18 @@ describe('normalizeProjectSettings', () => {
);
});
});
+
+describe('normalizeWorkbenchPreferences queue scope', () => {
+ it('defaults queue jobs to all jobs for older preferences', () => {
+ expect(store.normalizeWorkbenchPreferences({}).queueJobsScope).toBe('all');
+ });
+
+ it('accepts only supported queue job scopes', () => {
+ expect(store.normalizeWorkbenchPreferences({ queueJobsScope: 'active-project' }).queueJobsScope).toBe(
+ 'active-project'
+ );
+ expect(store.normalizeWorkbenchPreferences({ queueJobsScope: 'all' }).queueJobsScope).toBe('all');
+ expect(store.normalizeWorkbenchPreferences({ queueJobsScope: 'all-projects' }).queueJobsScope).toBe('all');
+ expect(store.normalizeWorkbenchPreferences({ queueJobsScope: 'current-project' }).queueJobsScope).toBe('all');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.ts
index 136a2a952e..4efc7ff33e 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts
@@ -77,6 +77,7 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {
enableInformationalPopovers: true,
enableModelDescriptions: true,
language: 'en',
+ queueJobsScope: 'all',
reduceMotion: false,
showFocusRegionHighlight: true,
themeId: DEFAULT_THEME_ID,
@@ -169,7 +170,8 @@ export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): P
useCpuNoise: typeof settings?.useCpuNoise === 'boolean' ? settings.useCpuNoise : DEFAULT_PROJECT_SETTINGS.useCpuNoise,
});
-type WorkbenchPreferencesInput = Omit<Partial<WorkbenchPreferences>, 'workflowEdgeStyle'> & {
+type WorkbenchPreferencesInput = Omit<Partial<WorkbenchPreferences>, 'queueJobsScope' | 'workflowEdgeStyle'> & {
+ queueJobsScope?: unknown;
workflowEdgeStyle?: unknown;
};
@@ -196,6 +198,12 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferences
? preferences.enableModelDescriptions
: DEFAULT_PREFERENCES.enableModelDescriptions,
language: isWorkbenchLanguage(preferences?.language) ? preferences.language : DEFAULT_PREFERENCES.language,
+ queueJobsScope:
+ preferences?.queueJobsScope === 'all-projects'
+ ? 'all'
+ : preferences?.queueJobsScope === 'active-project' || preferences?.queueJobsScope === 'all'
+ ? preferences.queueJobsScope
+ : DEFAULT_PREFERENCES.queueJobsScope,
reduceMotion:
typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion,
showFocusRegionHighlight:
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx
index e5110f9f73..338a3981e8 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx
@@ -1,142 +1,12 @@
-import { Group, Icon, Menu, Portal } from '@chakra-ui/react';
+import { Group, Menu, Portal } from '@chakra-ui/react';
import { IconButton, Tooltip } from '@workbench/components/ui';
-import {
- cancelAllExceptCurrentQueueItems,
- cancelCurrentQueueItem,
- pauseQueueProcessor,
- resumeQueueProcessor,
-} from '@workbench/generation/api';
-import { useNotify } from '@workbench/useNotify';
-import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
-import { getQueueActionState } from '@workbench/widgets/queue/queueViewModel';
-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';
-import { ChevronDownIcon, ListOrderedIcon, PauseIcon, PlayIcon, XIcon } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-
-const ERROR_ITEM_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' };
+import { QueueMenuItems, useQueueMenuActions } from '@workbench/widgets/queue/queueMenuActions';
+import { ChevronDownIcon, XIcon } from 'lucide-react';
/** Queue cancel cluster and processor actions. */
export const QueueActions = () => {
- const activeProjectId = useWorkbenchSelector((snapshot) => snapshot.state.activeProjectId);
- const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
- const { cancellableCount, currentItemId, hasPendingQueueWork, hasRunningItem } = useActiveProjectSelector((project) =>
- getQueueActionState(project.queue.items)
- );
- const dispatch = useWorkbenchDispatch();
- const notify = useNotify();
- const openWorkbenchWidget = useOpenWorkbenchWidget();
- const isConnected = backendConnectionStatus === 'connected';
-
- const cancelCurrent = useCallback(() => {
- cancelCurrentQueueItem()
- .then((queueItem) => {
- if (!queueItem) {
- notify.info('No current item', 'The backend queue has no in-progress item to cancel.');
- return;
- }
-
- notify.success('Cancellation requested', `Backend queue item ${queueItem.item_id}.`);
- dispatch({ type: 'refreshBackendData' });
- })
- .catch((error: unknown) =>
- notify.error('Failed to cancel current item', error instanceof Error ? error.message : String(error))
- );
- }, [dispatch, notify]);
-
- const cancelAllExceptCurrent = useCallback(() => {
- cancelAllExceptCurrentQueueItems()
- .then(() => {
- dispatch({
- currentQueueItemId: currentItemId,
- projectId: activeProjectId,
- type: 'cancelAllQueueItemsExceptCurrent',
- });
- dispatch({ type: 'refreshBackendData' });
- notify.success('Queue cancellation requested', 'All pending items except the current item were requested.');
- })
- .catch((error: unknown) =>
- notify.error('Failed to cancel queue items', error instanceof Error ? error.message : String(error))
- );
- }, [activeProjectId, currentItemId, dispatch, notify]);
-
- const runProcessorAction = useCallback(
- (label: 'pause' | 'resume') => {
- const action = label === 'pause' ? pauseQueueProcessor : resumeQueueProcessor;
-
- action()
- .then(() => notify.success(label === 'pause' ? 'Processor paused' : 'Processor resumed'))
- .catch((error: unknown) =>
- notify.error(
- label === 'pause' ? 'Failed to pause processor' : 'Failed to resume processor',
- error instanceof Error ? error.message : String(error)
- )
- );
- },
- [notify]
- );
- const cancelAll = useCallback(
- () => dispatch({ projectId: activeProjectId, type: 'cancelAllQueueItems' }),
- [activeProjectId, dispatch]
- );
- const resumeProcessor = useCallback(() => runProcessorAction('resume'), [runProcessorAction]);
- const pauseProcessor = useCallback(() => runProcessorAction('pause'), [runProcessorAction]);
- const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);
-
- const queueEndActions = useMemo(
- () => [
- {
- label: 'Cancel Current Item',
- icon: XIcon,
- disabled: !isConnected || !hasRunningItem,
- onClick: cancelCurrent,
- },
- {
- label: 'Cancel All Items',
- icon: XIcon,
- disabled: cancellableCount === 0,
- onClick: cancelAll,
- },
- {
- label: 'Cancel all except current item',
- icon: XIcon,
- disabled: !isConnected || !hasPendingQueueWork,
- onClick: cancelAllExceptCurrent,
- },
- ],
- [
- cancelAll,
- cancelAllExceptCurrent,
- cancelCurrent,
- cancellableCount,
- hasPendingQueueWork,
- hasRunningItem,
- isConnected,
- ]
- );
-
- const queueProcessorActions = useMemo(
- () => [
- {
- label: 'Resume Processor',
- icon: PlayIcon,
- disabled: !isConnected,
- onClick: resumeProcessor,
- },
- {
- label: 'Pause Processor',
- icon: PauseIcon,
- disabled: !isConnected,
- onClick: pauseProcessor,
- },
- {
- label: 'Open Queue',
- icon: ListOrderedIcon,
- disabled: false,
- onClick: openQueue,
- },
- ],
- [isConnected, openQueue, pauseProcessor, resumeProcessor]
- );
+ const actions = useQueueMenuActions();
+ const cancelCurrent = actions[0];
return (
<Menu.Root>
@@ -144,12 +14,12 @@ export const QueueActions = () => {
<Tooltip content="Cancel current item" showArrow>
<IconButton
aria-label="Cancel current queue item"
- disabled={!isConnected || !hasRunningItem}
+ disabled={cancelCurrent?.disabled}
variant="outline"
size="sm"
roundedEnd="none"
borderColor="border.subtle"
- onClick={cancelCurrent}
+ onClick={cancelCurrent?.onClick}
>
<XIcon />
</IconButton>
@@ -173,30 +43,7 @@ export const QueueActions = () => {
<Portal>
<Menu.Positioner>
<Menu.Content>
- <Menu.ItemGroup>
- {queueEndActions.map((action, index) => (
- <Menu.Item
- key={index}
- onClick={action.onClick}
- value={action.label}
- color="fg.error"
- disabled={action.disabled}
- _hover={ERROR_ITEM_HOVER_PROPS}
- >
- <Icon as={action.icon} boxSize="3" />
- <span>{action.label}</span>
- </Menu.Item>
- ))}
- </Menu.ItemGroup>
- <Menu.Separator />
- <Menu.ItemGroup>
- {queueProcessorActions.map((action, index) => (
- <Menu.Item key={index} disabled={action.disabled} onClick={action.onClick} value={action.label}>
- <Icon as={action.icon} boxSize="3" />
- <span>{action.label}</span>
- </Menu.Item>
- ))}
- </Menu.ItemGroup>
+ <QueueMenuItems actions={actions} />
</Menu.Content>
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index a14e241918..cf9a78afbd 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -297,6 +297,7 @@ export type SettingsSectionId =
| 'behavior'
| 'hotkeys'
| 'project'
+ | 'queue'
| 'workflow'
| 'developer'
| 'workspace';
@@ -697,6 +698,7 @@ export interface WorkbenchPreferences {
reduceMotion: boolean;
showFocusRegionHighlight: boolean;
confirmImageDeletion: boolean;
+ queueJobsScope: 'active-project' | 'all';
language: WorkbenchLanguage;
enableInformationalPopovers: boolean;
enableModelDescriptions: boolean;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsx
new file mode 100644
index 0000000000..0a46e27100
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/CancelQueueItemButton.tsx
@@ -0,0 +1,54 @@
+import type { MouseEvent as ReactMouseEvent } from 'react';
+
+import { Icon } from '@chakra-ui/react';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { IconButton, Tooltip } from '@workbench/components/ui';
+import { useNotify } from '@workbench/useNotify';
+import { XIcon } from 'lucide-react';
+import { useCallback, useState } from 'react';
+
+import { refreshQueue } from './queueDataStore';
+import { cancelQueueItem } from './queueServerApi';
+
+/**
+ * Cancel a single queue item by its backend id. Works for any in-flight item
+ * regardless of which client submitted it; the coordinator settles local items
+ * off the resulting `queue_item_status_changed` event. `stopPropagation` keeps a
+ * click from also toggling the row it sits in.
+ */
+export const CancelQueueItemButton = ({ itemId }: { itemId: number }) => {
+ const notify = useNotify();
+ const [busy, setBusy] = useState(false);
+
+ const onCancel = useCallback(
+ async (event: ReactMouseEvent) => {
+ event.stopPropagation();
+ setBusy(true);
+
+ try {
+ await cancelQueueItem(itemId);
+ await refreshQueue();
+ } catch (error) {
+ notify.error('Cancel failed', getApiErrorMessage(error, 'Could not cancel this item.'));
+ } finally {
+ setBusy(false);
+ }
+ },
+ [itemId, notify]
+ );
+
+ return (
+ <Tooltip content={`Cancel queue item #${itemId}`}>
+ <IconButton
+ aria-label={`Cancel queue item #${itemId}`}
+ color="fg.muted"
+ loading={busy}
+ size="2xs"
+ variant="ghost"
+ onClick={onCancel}
+ >
+ <Icon as={XIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsx
new file mode 100644
index 0000000000..13e8ba6eec
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/ModelCacheFooter.tsx
@@ -0,0 +1,133 @@
+import { Collapsible, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { Button } from '@workbench/components/ui';
+import { formatBytes } from '@workbench/models/taxonomy';
+import { useNotify } from '@workbench/useNotify';
+import { ChevronUpIcon, DatabaseIcon, Trash2Icon } from 'lucide-react';
+import { useCallback, useEffect, useState } from 'react';
+
+import {
+ clearModelCache,
+ getModelCacheClearToast,
+ getModelCacheUsage,
+ refreshModelCacheStats,
+ useModelCacheStats,
+} from './modelCacheStore';
+
+const INDICATOR_OPEN = { transform: 'rotate(180deg)' } as const;
+const TRIGGER_HOVER = { color: 'fg' } as const;
+
+const CacheStat = ({ label, value }: { label: string; value: number }) => (
+ <Text color="fg.subtle" fontSize="2xs">
+ {label}{' '}
+ <Text as="span" color="fg" fontVariantNumeric="tabular-nums" fontWeight="600">
+ {value}
+ </Text>
+ </Text>
+);
+
+/**
+ * Collapsible MODEL CACHE footer (manifest `footer` slot). Collapsed: a label, a
+ * RAM-used / budget readout, and a fill bar. Expanded: hit/miss/loaded counts and
+ * a Clear action. The cache has no enable/disable endpoint, so there is no
+ * "Disable" toggle. Mirrors the model manager's `InstallQueueBar` collapse shape.
+ */
+export const ModelCacheFooter = () => {
+ const { stats } = useModelCacheStats();
+ const notify = useNotify();
+ const [expanded, setExpanded] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ void refreshModelCacheStats();
+ }, []);
+
+ const { total, used } = getModelCacheUsage(stats);
+ const ratio = total > 0 ? Math.min(1, used / total) : 0;
+
+ const handleOpenChange = useCallback((event: { open: boolean }) => setExpanded(event.open), []);
+ const handleClear = useCallback(async () => {
+ setBusy(true);
+
+ try {
+ const clearResult = await clearModelCache();
+ const toast = getModelCacheClearToast(clearResult);
+ notify[toast.status](toast.title, toast.description);
+ } catch (error) {
+ notify.error('Clear cache failed', getApiErrorMessage(error, 'Could not clear the model cache.'));
+ } finally {
+ setBusy(false);
+ }
+ }, [notify]);
+
+ return (
+ <Collapsible.Root
+ bg="bg.subtle"
+ borderTopWidth={1}
+ open={expanded}
+ overflow="hidden"
+ onOpenChange={handleOpenChange}
+ >
+ <Collapsible.Content>
+ <Stack borderBottomWidth={1} gap="2" px="3" py="2.5">
+ <HStack gap="3">
+ <CacheStat label="Hits" value={stats?.hits ?? 0} />
+ <CacheStat label="Misses" value={stats?.misses ?? 0} />
+ <CacheStat label="Loaded" value={stats?.in_cache ?? 0} />
+ </HStack>
+ <HStack>
+ <Button loading={busy} size="2xs" variant="surface" onClick={handleClear}>
+ <Icon as={Trash2Icon} boxSize="3" />
+ Clear cache
+ </Button>
+ </HStack>
+ </Stack>
+ </Collapsible.Content>
+
+ <Stack gap="0">
+ <Progress.Root
+ aria-label="Model cache usage"
+ aria-valuetext={`${formatBytes(used)} of ${formatBytes(total)} used`}
+ colorPalette="accent"
+ max={1}
+ size="xs"
+ value={ratio}
+ >
+ <Progress.Track bg="transparent">
+ <Progress.Range />
+ </Progress.Track>
+ </Progress.Root>
+ <Collapsible.Trigger
+ alignItems="center"
+ bg="transparent"
+ color="inherit"
+ display="flex"
+ gap="2"
+ px="3"
+ py="2"
+ textAlign="start"
+ w="full"
+ _hover={TRIGGER_HOVER}
+ >
+ <Icon as={DatabaseIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />
+ <Text
+ color="fg.muted"
+ flex="1"
+ fontSize="2xs"
+ fontWeight="700"
+ letterSpacing="0.06em"
+ textTransform="uppercase"
+ >
+ Model Cache
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {formatBytes(used)} / {formatBytes(total)}
+ </Text>
+ <Collapsible.Indicator _open={INDICATOR_OPEN} transition="transform var(--wb-motion-duration-slow)">
+ <Icon as={ChevronUpIcon} boxSize="4" color="fg.subtle" flexShrink={0} />
+ </Collapsible.Indicator>
+ </Collapsible.Trigger>
+ </Stack>
+ </Collapsible.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsx
new file mode 100644
index 0000000000..91493b65ee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/NowNextSection.tsx
@@ -0,0 +1,26 @@
+import { Stack } from '@chakra-ui/react';
+
+import { QueueItemRow } from './QueueItemRow';
+import { useScopedCurrentBatchItems } from './queueScope';
+import { SectionHeader } from './SectionHeader';
+
+/** CURRENT BATCH — the running item plus every pending item in the same backend batch. */
+export const CurrentBatchSection = () => {
+ const items = useScopedCurrentBatchItems();
+ const count = items.length;
+
+ if (count === 0) {
+ return null;
+ }
+
+ return (
+ <Stack gap="2">
+ <SectionHeader count={count} title="Current Batch" />
+ <Stack gap="1">
+ {items.map((item) => (
+ <QueueItemRow key={item.item_id} item={item} />
+ ))}
+ </Stack>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.ts
new file mode 100644
index 0000000000..8111be0aa7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.test.ts
@@ -0,0 +1,151 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ clearAllProgress: vi.fn(),
+ clearProgress: vi.fn(),
+ setProgress: vi.fn(),
+ onConnectionChange: vi.fn(),
+ refreshModelCacheStats: vi.fn(),
+ refreshQueue: vi.fn(),
+ socketOn: vi.fn(),
+}));
+
+vi.mock('@workbench/backend/events', () => ({
+ isTerminalBackendStatus: (status: string) => status === 'completed' || status === 'failed' || status === 'canceled',
+}));
+
+vi.mock('@workbench/backend/itemProgressStore', () => ({
+ itemProgressStore: {
+ clear: mocks.clearProgress,
+ clearAll: mocks.clearAllProgress,
+ set: mocks.setProgress,
+ },
+}));
+
+vi.mock('@workbench/backend/socketHub', () => ({
+ socketHub: {
+ on: mocks.socketOn,
+ onConnectionChange: mocks.onConnectionChange,
+ },
+}));
+
+vi.mock('./modelCacheStore', () => ({
+ refreshModelCacheStats: mocks.refreshModelCacheStats,
+}));
+
+vi.mock('./queueDataStore', () => ({
+ ensureQueueLoaded: vi.fn(),
+ refreshQueue: mocks.refreshQueue,
+ setQueueScope: vi.fn(),
+ useCurrentBatchItems: vi.fn(() => []),
+ useQueueCounts: vi.fn(() => ({
+ canceled: 0,
+ completed: 0,
+ failed: 0,
+ in_progress: 0,
+ pending: 0,
+ queue_id: 'default',
+ total: 0,
+ })),
+ useRecentItems: vi.fn(() => []),
+}));
+
+vi.mock('@workbench/settings/store', () => ({
+ useWorkbenchPreferences: vi.fn(() => ({ queueJobsScope: 'all' })),
+}));
+
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useOptionalWorkbenchSelector: vi.fn((_selector: unknown, fallback: unknown) => fallback),
+}));
+
+describe('QueueDataRuntime queue refresh events', () => {
+ beforeEach(() => {
+ mocks.clearAllProgress.mockReset();
+ mocks.clearProgress.mockReset();
+ mocks.onConnectionChange.mockReset();
+ mocks.refreshModelCacheStats.mockReset();
+ mocks.refreshQueue.mockReset();
+ mocks.setProgress.mockReset();
+ mocks.socketOn.mockReset();
+ mocks.socketOn.mockReturnValue(vi.fn());
+ mocks.onConnectionChange.mockReturnValue(vi.fn());
+ });
+
+ it('refreshes queue data for all queue mutation socket events', async () => {
+ const { attachQueueDataRuntime } = await import('./QueueDataRuntime');
+
+ attachQueueDataRuntime();
+
+ const handlersByEvent = new Map<string, (payload: never) => void>(
+ mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])
+ );
+
+ handlersByEvent.get('batch_enqueued')?.({} as never);
+ handlersByEvent.get('queue_cleared')?.({} as never);
+ handlersByEvent.get('queue_items_retried')?.({} as never);
+
+ expect(mocks.refreshQueue).toHaveBeenCalledTimes(3);
+ });
+
+ it('stores live denoise preview images by backend queue item id', async () => {
+ const { attachQueueDataRuntime } = await import('./QueueDataRuntime');
+
+ attachQueueDataRuntime();
+
+ const handlersByEvent = new Map<string, (payload: never) => void>(
+ mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])
+ );
+
+ handlersByEvent.get('invocation_progress')?.({
+ image: { dataURL: 'data:image/png;base64,preview', height: 32, width: 64 },
+ item_id: 42,
+ message: 'Denoising',
+ percentage: 0.5,
+ } as never);
+
+ expect(mocks.setProgress).toHaveBeenCalledWith(42, {
+ image: { dataUrl: 'data:image/png;base64,preview', height: 32, width: 64 },
+ message: 'Denoising',
+ percentage: 0.5,
+ });
+ });
+
+ it('does not clear the last live preview when later invocations start for the same queue item', async () => {
+ const { attachQueueDataRuntime } = await import('./QueueDataRuntime');
+
+ attachQueueDataRuntime();
+
+ const handlersByEvent = new Map<string, (payload: never) => void>(
+ mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])
+ );
+
+ handlersByEvent.get('invocation_progress')?.({
+ image: { dataURL: 'data:image/png;base64,last-denoise', height: 32, width: 64 },
+ item_id: 42,
+ message: 'Denoising',
+ percentage: 1,
+ } as never);
+ handlersByEvent.get('invocation_started')?.({ item_id: 42 } as never);
+
+ expect(mocks.setProgress).toHaveBeenLastCalledWith(42, {
+ message: '',
+ percentage: null,
+ });
+ });
+
+ it('keeps completed item progress images until the refreshed queue item has a final result', async () => {
+ const { attachQueueDataRuntime } = await import('./QueueDataRuntime');
+
+ attachQueueDataRuntime();
+
+ const handlersByEvent = new Map<string, (payload: never) => void>(
+ mocks.socketOn.mock.calls.map((call) => [call[0] as string, call[1] as (payload: never) => void])
+ );
+
+ handlersByEvent.get('queue_item_status_changed')?.({ item_id: 42, status: 'completed' } as never);
+ handlersByEvent.get('queue_item_status_changed')?.({ item_id: 43, status: 'failed' } as never);
+
+ expect(mocks.clearProgress).not.toHaveBeenCalledWith(42);
+ expect(mocks.clearProgress).toHaveBeenCalledWith(43);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsx
new file mode 100644
index 0000000000..22e7593aff
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueDataRuntime.tsx
@@ -0,0 +1,102 @@
+import type {
+ InvocationProgressEvent,
+ InvocationStartedEvent,
+ QueueItemStatusChangedEvent,
+} from '@workbench/backend/events';
+
+import { isTerminalBackendStatus } from '@workbench/backend/events';
+import { itemProgressStore } from '@workbench/backend/itemProgressStore';
+import { socketHub } from '@workbench/backend/socketHub';
+import { ConfirmDialog } from '@workbench/components/ui';
+import { useEffect } from 'react';
+
+import { refreshModelCacheStats } from './modelCacheStore';
+import { clearQueueConfirmation, useQueueConfirmation } from './queueConfirmationStore';
+import { ensureQueueLoaded, refreshQueue, setQueueScope } from './queueDataStore';
+import { useQueueQueryScope } from './queueScope';
+
+/**
+ * Singleton runtime for the Queue widget (mounted via `manifest.host`). It owns
+ * the live wiring: socket lifecycle events refresh the server-queue store and
+ * feed per-item progress, replacing the RTK Query tag-invalidation the legacy v6
+ * app used. Pure side effects — renders nothing.
+ */
+export const attachQueueDataRuntime = (): (() => void) => {
+ ensureQueueLoaded();
+ void refreshModelCacheStats();
+
+ const refresh = () => {
+ void refreshQueue();
+ };
+ const detachers = [
+ socketHub.on('queue_item_status_changed', (payload: never) => {
+ const event = payload as unknown as QueueItemStatusChangedEvent;
+
+ if (isTerminalBackendStatus(event.status) && event.status !== 'completed') {
+ itemProgressStore.clear(event.item_id);
+ }
+
+ refresh();
+ }),
+ socketHub.on('batch_enqueued', refresh),
+ socketHub.on('queue_cleared', refresh),
+ socketHub.on('queue_items_retried', refresh),
+ socketHub.on('invocation_started', (payload: never) => {
+ const event = payload as unknown as InvocationStartedEvent;
+ itemProgressStore.set(event.item_id, { message: '', percentage: null });
+ }),
+ socketHub.on('invocation_progress', (payload: never) => {
+ const event = payload as unknown as InvocationProgressEvent;
+ itemProgressStore.set(event.item_id, {
+ image: event.image?.dataURL
+ ? { dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width }
+ : undefined,
+ message: event.message,
+ percentage: event.percentage,
+ });
+ }),
+ socketHub.on('model_load_complete', () => {
+ void refreshModelCacheStats();
+ }),
+ ];
+
+ const detachConnection = socketHub.onConnectionChange((status) => {
+ if (status === 'connected') {
+ itemProgressStore.clearAll();
+ void refreshQueue();
+ void refreshModelCacheStats();
+ }
+ });
+
+ return () => {
+ for (const detach of detachers) {
+ detach();
+ }
+
+ detachConnection();
+ };
+};
+
+export const QueueDataRuntime = () => {
+ const scope = useQueueQueryScope();
+ const confirmation = useQueueConfirmation();
+
+ useEffect(() => {
+ setQueueScope(scope);
+ }, [scope, scope.originPrefix]);
+
+ useEffect(() => {
+ return attachQueueDataRuntime();
+ }, []);
+
+ return confirmation ? (
+ <ConfirmDialog
+ body={confirmation.body}
+ confirmLabel={confirmation.confirmLabel}
+ isOpen={true}
+ title={confirmation.title}
+ onClose={clearQueueConfirmation}
+ onConfirm={confirmation.onConfirm}
+ />
+ ) : null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueFilterTabs.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueFilterTabs.tsx
new file mode 100644
index 0000000000..0c9f8cc05f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueFilterTabs.tsx
@@ -0,0 +1,42 @@
+import { SegmentGroup } from '@chakra-ui/react';
+import { useCallback } from 'react';
+
+import type { QueueFilterId } from './queueFilters';
+
+import { QUEUE_FILTERS } from './queueFilters';
+
+/** Status filter pills for the RECENT list (All · Active · Done · Failed · Canceled). */
+export const QueueFilterTabs = ({
+ value,
+ onChange,
+}: {
+ value: QueueFilterId;
+ onChange: (filter: QueueFilterId) => void;
+}) => {
+ const onValueChange = useCallback(
+ (details: { value: string | null }) => {
+ if (details.value) {
+ onChange(details.value as QueueFilterId);
+ }
+ },
+ [onChange]
+ );
+
+ return (
+ <SegmentGroup.Root
+ aria-label="Filter recent queue items by status"
+ colorPalette="accent"
+ size="xs"
+ value={value}
+ onValueChange={onValueChange}
+ >
+ <SegmentGroup.Indicator />
+ {QUEUE_FILTERS.map((filter) => (
+ <SegmentGroup.Item key={filter.id} value={filter.id}>
+ <SegmentGroup.ItemHiddenInput />
+ <SegmentGroup.ItemText>{filter.label}</SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ ))}
+ </SegmentGroup.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.test.ts
new file mode 100644
index 0000000000..d6ce68b536
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { getQueueHeaderCancelState } from './QueueHeaderActions';
+
+describe('getQueueHeaderCancelState', () => {
+ it('enables cancelling when connected with an in-progress current item', () => {
+ expect(getQueueHeaderCancelState({ currentStatus: 'in_progress', isConnected: true })).toEqual({
+ disabled: false,
+ itemLabel: 'Cancel Current',
+ });
+ });
+
+ it('disables cancelling when disconnected or there is no current in-progress item', () => {
+ expect(getQueueHeaderCancelState({ currentStatus: 'in_progress', isConnected: false }).disabled).toBe(true);
+ expect(getQueueHeaderCancelState({ currentStatus: 'pending', isConnected: true }).disabled).toBe(true);
+ expect(getQueueHeaderCancelState({ currentStatus: null, isConnected: true }).disabled).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsx
new file mode 100644
index 0000000000..f876158d14
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderActions.tsx
@@ -0,0 +1,62 @@
+import { Icon } from '@chakra-ui/react';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { Button } from '@workbench/components/ui';
+import { useNotify } from '@workbench/useNotify';
+import { useWorkbenchSelector } from '@workbench/WorkbenchContext';
+import { XIcon } from 'lucide-react';
+import { useCallback, useState } from 'react';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { refreshQueue, useNowNextItems } from './queueDataStore';
+import { cancelQueueItem } from './queueServerApi';
+
+export const getQueueHeaderCancelState = ({
+ currentStatus,
+ isConnected,
+}: {
+ currentStatus: QueueServerItem['status'] | null;
+ isConnected: boolean;
+}): { disabled: boolean; itemLabel: string } => ({
+ disabled: !isConnected || currentStatus !== 'in_progress',
+ itemLabel: 'Cancel Current',
+});
+
+/**
+ * Cancel the current queue item from the manifest `headerActions` slot, so the
+ * most common interruption action sits inline beside the actions menu.
+ */
+export const QueueHeaderActions = () => {
+ const isConnected = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status === 'connected');
+ const { current } = useNowNextItems();
+ const notify = useNotify();
+ const [busy, setBusy] = useState(false);
+ const { disabled, itemLabel } = getQueueHeaderCancelState({
+ currentStatus: current?.status ?? null,
+ isConnected,
+ });
+
+ const onCancel = useCallback(async () => {
+ if (disabled || !current) {
+ return;
+ }
+
+ setBusy(true);
+
+ try {
+ await cancelQueueItem(current.item_id);
+ await refreshQueue();
+ } catch (error) {
+ notify.error('Cancel failed', getApiErrorMessage(error, 'Could not cancel the current item.'));
+ } finally {
+ setBusy(false);
+ }
+ }, [current, disabled, notify]);
+
+ return (
+ <Button disabled={disabled} loading={busy} size="2xs" variant="outline" onClick={onCancel}>
+ <Icon as={XIcon} boxSize="3.5" />
+ {itemLabel}
+ </Button>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsx
new file mode 100644
index 0000000000..ac50439034
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderLabel.tsx
@@ -0,0 +1,28 @@
+import { Stack, Text } from '@chakra-ui/react';
+
+import { useScopedQueueCounts } from './queueScope';
+
+/**
+ * The Queue widget's header title: "Queue" over a live "N generating · M waiting"
+ * summary. Rendered as the manifest `label`, so it sits in the standard frame
+ * header. Counts come straight from the server-wide status, with tabular
+ * numerals so the summary doesn't jitter as items move through the queue.
+ */
+export const QueueHeaderLabel = () => {
+ const counts = useScopedQueueCounts();
+ const isGenerating = counts.in_progress > 0;
+
+ return (
+ <Stack gap="0.5" minW="0">
+ <Text fontSize="xs" fontWeight="700" lineHeight="1.15">
+ Queue
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums" lineHeight="1.15" truncate mb="-1.5">
+ <Text as="span" color={isGenerating ? 'accent.solid' : 'fg.subtle'} fontWeight={isGenerating ? '600' : '400'}>
+ {counts.in_progress} generating
+ </Text>{' '}
+ · {counts.pending} waiting
+ </Text>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsx
new file mode 100644
index 0000000000..4b0df0d9b4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueHeaderMenu.tsx
@@ -0,0 +1,93 @@
+import { Icon, Menu } from '@chakra-ui/react';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { useNotify } from '@workbench/useNotify';
+import { Trash2Icon, TrashIcon } from 'lucide-react';
+import { useCallback } from 'react';
+
+import { requestQueueConfirmation } from './queueConfirmationStore';
+import { refreshQueue, useQueueCounts } from './queueDataStore';
+import { QueueMenuItems, useQueueMenuActions } from './queueMenuActions';
+import { useQueueQueryScope } from './queueScope';
+import { clearFailedQueueItems, clearScopedQueue } from './queueServerApi';
+
+const ERROR_ITEM_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' };
+
+/**
+ * Queue actions contributed to the frame's shared actions menu via the manifest
+ * `headerMenu` slot. This intentionally uses the same action model as the
+ * topbar queue menu so backend mutations keep local run coordination in sync.
+ */
+export const QueueHeaderMenu = () => {
+ const actions = useQueueMenuActions();
+ const counts = useQueueCounts();
+ const scope = useQueueQueryScope();
+ const notify = useNotify();
+
+ const clearFailed = useCallback(async () => {
+ try {
+ await clearFailedQueueItems(scope);
+ await refreshQueue();
+ notify.success('Failed queue items cleared');
+ } catch (error) {
+ notify.error('Failed to clear queue items', getApiErrorMessage(error, 'Could not clear failed queue items.'));
+ }
+ }, [notify, scope]);
+
+ const clearAll = useCallback(async () => {
+ try {
+ await clearScopedQueue(scope);
+ await refreshQueue();
+ notify.success('Queue cleared');
+ } catch (error) {
+ notify.error('Failed to clear queue', getApiErrorMessage(error, 'Could not clear the queue.'));
+ }
+ }, [notify, scope]);
+ const onClearFailed = useCallback(() => {
+ requestQueueConfirmation({
+ body: 'This permanently removes failed queue items in the current queue scope.',
+ confirmLabel: 'Clear Failed Items',
+ onConfirm: clearFailed,
+ title: 'Clear failed queue items?',
+ });
+ }, [clearFailed]);
+ const onClearAll = useCallback(() => {
+ requestQueueConfirmation({
+ body: 'This permanently clears queue items in the current queue scope.',
+ confirmLabel: 'Clear Queue',
+ onConfirm: clearAll,
+ title: 'Clear queue?',
+ });
+ }, [clearAll]);
+
+ return (
+ <>
+ <QueueMenuItems actions={actions} label="Queue" />
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Clear
+ </Menu.ItemGroupLabel>
+ <Menu.Item
+ color="fg.error"
+ disabled={counts.failed === 0}
+ value="clear-failed-items"
+ _hover={ERROR_ITEM_HOVER_PROPS}
+ onClick={onClearFailed}
+ >
+ <Icon as={Trash2Icon} boxSize="3" />
+ <Menu.ItemText>Clear Failed Items</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item
+ color="fg.error"
+ disabled={counts.total === 0}
+ value="clear-all-items"
+ _hover={ERROR_ITEM_HOVER_PROPS}
+ onClick={onClearAll}
+ >
+ <Icon as={TrashIcon} boxSize="3" />
+ <Menu.ItemText>Clear All Items</Menu.ItemText>
+ </Menu.Item>
+ </Menu.ItemGroup>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsx
new file mode 100644
index 0000000000..b199094372
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemActions.tsx
@@ -0,0 +1,109 @@
+import type { GenerateWidgetValues } from '@workbench/generation/types';
+
+import { ButtonGroup, Dialog, Icon, Portal } from '@chakra-ui/react';
+import { Button, CloseButton, JsonPreview, Tooltip } from '@workbench/components/ui';
+import { useNotify } from '@workbench/useNotify';
+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
+import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';
+import { FileTextIcon, UndoIcon, WandSparklesIcon } from 'lucide-react';
+import { useCallback, useState } from 'react';
+
+import type { QueueServerItem } from './queueServerApi';
+
+/**
+ * Per-item actions for the RECENT details panel.
+ *
+ * - **Use again** recalls the exact submission snapshot into Generate (only the
+ * submitting client has it; otherwise disabled — recall from the gallery).
+ * - **Send to canvas** is deferred (no canvas-import path exists in webv2 yet),
+ * so it reports "coming soon" rather than silently no-op'ing.
+ * - **View JSON** opens the raw queue item (incl. its session) in a dialog.
+ */
+export const QueueItemActions = ({
+ item,
+ localGenerateValues,
+}: {
+ item: QueueServerItem;
+ localGenerateValues: GenerateWidgetValues | null;
+}) => {
+ const dispatch = useWorkbenchDispatch();
+ const openWidget = useOpenWorkbenchWidget();
+ const notify = useNotify();
+ const [jsonOpen, setJsonOpen] = useState(false);
+
+ const canRecall = localGenerateValues !== null;
+
+ const onUseAgain = useCallback(() => {
+ if (!localGenerateValues) {
+ return;
+ }
+
+ dispatch({ type: 'setGenerateSettings', values: localGenerateValues });
+ openWidget('generate', { preferredRegions: ['left'] });
+ notify.success('Settings recalled', 'Loaded these settings into Generate.');
+ }, [dispatch, localGenerateValues, notify, openWidget]);
+
+ const onSendToCanvas = useCallback(
+ () => notify.info('Send to canvas', 'Sending queue results to the canvas is coming soon.'),
+ [notify]
+ );
+
+ const openJson = useCallback(() => setJsonOpen(true), []);
+ const closeJson = useCallback(() => setJsonOpen(false), []);
+
+ return (
+ <>
+ {/*<HStack flexWrap="wrap" gap="1.5">
+ <Tooltip content={canRecall ? 'Load these settings into Generate' : 'Recall this generation from the gallery'}>
+ <Button disabled={!canRecall} size="2xs" variant="surface" onClick={onUseAgain}>
+ Recall All
+ </Button>
+ </Tooltip>
+ <Button color="fg.subtle" size="2xs" variant="ghost" onClick={onSendToCanvas}>
+ Send to canvas
+ </Button>
+ <Button size="2xs" variant="surface" onClick={openJson}>
+ View JSON
+ </Button>
+ </HStack>*/}
+
+ <ButtonGroup size="2xs" variant="subtle">
+ <Tooltip content={canRecall ? 'Load these settings into Generate' : 'Recall this generation from the gallery'}>
+ <Button onClick={onUseAgain} disabled={!canRecall}>
+ <Icon as={UndoIcon} boxSize="3" />
+ Recall All
+ </Button>
+ </Tooltip>
+ <Button disabled variant="ghost" onClick={onSendToCanvas}>
+ <Icon as={WandSparklesIcon} boxSize="3" />
+ Send to canvas
+ </Button>
+ <Button size="2xs" onClick={openJson}>
+ <Icon as={FileTextIcon} boxSize="3" />
+ View JSON
+ </Button>
+ </ButtonGroup>
+
+ <Dialog.Root open={jsonOpen} placement="center" scrollBehavior="inside" size="lg" onOpenChange={closeJson}>
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">
+ <Dialog.Header>
+ <Dialog.Title fontSize="sm" fontWeight="700">
+ Queue item #{item.item_id}
+ </Dialog.Title>
+ </Dialog.Header>
+ <Dialog.Body>
+ <JsonPreview label={`Queue item ${item.item_id} JSON`} maxH="60vh" value={item} />
+ </Dialog.Body>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsx
new file mode 100644
index 0000000000..74cef8c7bb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemDetails.tsx
@@ -0,0 +1,60 @@
+import type { ReactNode } from 'react';
+
+import { DataList, Separator, Text } from '@chakra-ui/react';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { extractGenerationMeta } from './fieldValues';
+import { formatDuration } from './formatDuration';
+import { QueueItemActions } from './QueueItemActions';
+import { useLocalGenerateValues } from './useLocalGenerateValues';
+
+const DetailRow = ({ label, children }: { label: string; children: ReactNode }) => (
+ <DataList.Item key={label} alignItems="start">
+ <DataList.ItemLabel>{label}</DataList.ItemLabel>
+ <DataList.ItemValue fontFamily="mono" fontSize="2xs">
+ {children}
+ </DataList.ItemValue>
+ </DataList.Item>
+);
+
+/** Expanded detail grid + actions for a RECENT queue item row. */
+export const QueueItemDetails = ({ item }: { item: QueueServerItem }) => {
+ const meta = extractGenerationMeta(item);
+ const localGenerateValues = useLocalGenerateValues(item.origin);
+ const duration = formatDuration(item.started_at, item.completed_at);
+
+ return (
+ <DataList.Root gap="1.5" orientation="horizontal" size="sm">
+ <DetailRow label="Prompt">{meta.positivePrompt ?? '—'}</DetailRow>
+ <DetailRow label="Negative">{meta.negativePrompt ?? '—'}</DetailRow>
+ <DetailRow label="Seed">
+ <Text as="span" fontVariantNumeric="tabular-nums">
+ {meta.seed ?? '—'}
+ </Text>
+ </DetailRow>
+ <DetailRow label="Created">{new Date(item.created_at).toLocaleString()}</DetailRow>
+ <DetailRow label="Took">{duration ?? '—'}</DetailRow>
+ <DetailRow label="Batch">
+ <Text as="span" truncate>
+ {item.batch_id}
+ </Text>
+ </DetailRow>
+ <DetailRow label="Item">
+ <Text as="span" fontVariantNumeric="tabular-nums">
+ #{item.item_id}
+ </Text>
+ </DetailRow>
+ {item.error_message ? (
+ <DetailRow label="Error">
+ <Text as="span" color="fg.error">
+ {item.error_message}
+ </Text>
+ </DetailRow>
+ ) : null}
+
+ <Separator borderColor="border.subtle" my="0.5" />
+ <QueueItemActions item={item} localGenerateValues={localGenerateValues} />
+ </DataList.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsx
new file mode 100644
index 0000000000..d15e787a9d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemRow.tsx
@@ -0,0 +1,98 @@
+import type { SystemStyleObject } from '@chakra-ui/react';
+
+import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';
+import { useItemProgress } from '@workbench/backend/itemProgressStore';
+import { Row } from '@workbench/components/ui';
+import { ChevronRightIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { CancelQueueItemButton } from './CancelQueueItemButton';
+import { extractGenerationMeta, getResultImageName } from './fieldValues';
+import { formatCompactAge, formatDuration } from './formatDuration';
+import { QueueItemDetails } from './QueueItemDetails';
+import { QueueItemThumbnail } from './QueueItemThumbnail';
+import { QueueStatusDot } from './QueueStatusDot';
+import { QueueStepProgress } from './QueueStepProgress';
+import { getStatusMeta } from './statusMeta';
+
+const CHEVRON_OPEN = { transform: 'rotate(90deg)' } as const;
+
+const QUEUE_ITEM_BUTTON_SX: SystemStyleObject = {
+ display: 'flex',
+ alignItems: 'center',
+ flex: 1,
+ gap: 2.5,
+ minH: 11,
+ minW: 0,
+ px: 2,
+ py: 1.5,
+ textAlign: 'start',
+ rounded: 'none',
+ transitionDuration: 'fastest',
+} as const;
+
+export const QueueItemRow = memo(({ item }: { item: QueueServerItem }) => {
+ const [expanded, setExpanded] = useState(false);
+ const toggle = useCallback(() => setExpanded((open) => !open), []);
+ const meta = extractGenerationMeta(item);
+ const duration = formatDuration(item.started_at, item.completed_at);
+ const age = formatCompactAge(item.completed_at ?? item.created_at);
+ const ageLabel = [duration, age].filter(Boolean).join(' · ');
+ const isFailed = item.status === 'failed';
+ const isCancellable = item.status === 'pending' || item.status === 'in_progress';
+ const progress = useItemProgress(item.item_id);
+ const liveImage = progress?.image ?? null;
+ const resultImageName = getResultImageName(item);
+ const statusLabel = getStatusMeta(item.status).label;
+
+ const showBorder = expanded || isFailed;
+ const borderColor = showBorder ? (isFailed ? 'fg.error' : 'border') : 'transparent';
+
+ return (
+ <Box overflow="hidden" rounded="md" borderWidth={1} borderColor={borderColor}>
+ <HStack gap="0">
+ <Row aria-expanded={expanded} as="button" css={QUEUE_ITEM_BUTTON_SX} onClick={toggle}>
+ <QueueItemThumbnail boxSize="8" imageName={resultImageName} liveImage={liveImage} />
+ <Stack flex="1" gap="0.5" minW="0">
+ <Text fontSize="xs" truncate>
+ {meta.positivePrompt?.trim() || 'No prompt'}
+ </Text>
+ <HStack gap="1.5" minW="0">
+ <QueueStatusDot status={item.status} />
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums" truncate>
+ {[statusLabel, ageLabel].filter(Boolean).join(' · ')}
+ </Text>
+ </HStack>
+ </Stack>
+ <Icon
+ as={ChevronRightIcon}
+ boxSize="4"
+ color="fg.muted"
+ flexShrink={0}
+ transition="transform var(--wb-motion-duration-fast) ease"
+ css={expanded ? CHEVRON_OPEN : undefined}
+ />
+ </Row>
+ {isCancellable ? (
+ <Box flexShrink={0} pe="1">
+ <CancelQueueItemButton itemId={item.item_id} />
+ </Box>
+ ) : null}
+ </HStack>
+
+ {item.status === 'in_progress' ? (
+ <Box px="2.5" pb="2">
+ <QueueStepProgress message={progress?.message ?? ''} percentage={progress?.percentage ?? null} />
+ </Box>
+ ) : null}
+
+ {expanded ? (
+ <Box pb="2.5" pt="1" px="2.5">
+ <QueueItemDetails item={item} />
+ </Box>
+ ) : null}
+ </Box>
+ );
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsx
new file mode 100644
index 0000000000..de350aad0d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueItemThumbnail.tsx
@@ -0,0 +1,53 @@
+import { Icon, type SystemStyleObject } from '@chakra-ui/react';
+import { absolutizeApiUrl } from '@workbench/backend/http';
+import { StreamingImageFrame } from '@workbench/images/StreamingImageFrame';
+import { imageUrlToStreamingSource, progressImageToStreamingSource } from '@workbench/images/streamingImageSource';
+import { ImageOffIcon } from 'lucide-react';
+
+/**
+ * Square result preview for a queue item. Falls back to a deterministic gradient
+ * derived from the item id, so items without a (yet) resolvable image still read
+ * as distinct tiles — and the real thumbnail cross-fades in once loaded. A
+ * hairline inset outline (theme border token) gives the tile consistent edge
+ * depth without picking up the surface color underneath.
+ */
+const QUEUE_ITEM_THUMBNAIL_SX: SystemStyleObject = {
+ boxShadow: 'inset 0 0 0 1px {colors.border.subtle}',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+} as const;
+const IMAGE_OFF_PLACEHOLDER = <Icon as={ImageOffIcon} w="4" h="4" />;
+
+export const QueueItemThumbnail = ({
+ imageName,
+ liveImage,
+ // seed,
+ boxSize = '8',
+ rounded = 'md',
+}: {
+ imageName: string | null;
+ liveImage?: { dataUrl: string; width: number; height: number } | null;
+ // seed: number;
+ boxSize?: string;
+ rounded?: string;
+}) => {
+ const finalImage = imageUrlToStreamingSource({
+ alt: imageName ?? '',
+ src: imageName ? absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`) : null,
+ });
+
+ return (
+ <StreamingImageFrame
+ bg="bg.subtle"
+ boxSize={boxSize}
+ flexShrink={0}
+ finalImage={finalImage}
+ liveImage={progressImageToStreamingSource(liveImage)}
+ rounded={rounded}
+ css={QUEUE_ITEM_THUMBNAIL_SX}
+ >
+ {IMAGE_OFF_PLACEHOLDER}
+ </StreamingImageFrame>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsx
new file mode 100644
index 0000000000..0b74bf1663
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStats.tsx
@@ -0,0 +1,28 @@
+import { SimpleGrid, Stat } from '@chakra-ui/react';
+
+import { useScopedQueueCounts } from './queueScope';
+
+/**
+ * The four headline counts (done / failed / canceled / total) as a row of cards.
+ * Numbers are tabular so they stay aligned as the queue churns; the failed count
+ * turns danger-colored only when there's something to call out.
+ */
+const QueueStatCard = ({ value, label, danger }: { value: number; label: string; danger?: boolean }) => (
+ <Stat.Root size="sm" colorScheme={danger ? 'red' : undefined} gap="0">
+ <Stat.ValueText>{value}</Stat.ValueText>
+ <Stat.Label fontSize="xs">{label}</Stat.Label>
+ </Stat.Root>
+);
+
+export const QueueStats = () => {
+ const counts = useScopedQueueCounts();
+
+ return (
+ <SimpleGrid columns={4}>
+ <QueueStatCard label="done" value={counts.completed} />
+ <QueueStatCard danger={counts.failed > 0} label="failed" value={counts.failed} />
+ <QueueStatCard label="canceled" value={counts.canceled} />
+ <QueueStatCard label="total" value={counts.total} />
+ </SimpleGrid>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsx
new file mode 100644
index 0000000000..12987859b6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStatusDot.tsx
@@ -0,0 +1,24 @@
+import type { BackendQueueItemStatus } from '@workbench/backend/events';
+
+import { Box } from '@chakra-ui/react';
+
+import { getStatusMeta } from './statusMeta';
+
+const ACTIVE_HALO = { boxShadow: '0 0 0 3px {colors.accent.subtle}' } as const;
+
+/** Small status indicator dot; the running state gets a soft accent halo. */
+export const QueueStatusDot = ({ status, boxSize = '2' }: { status: BackendQueueItemStatus; boxSize?: string }) => {
+ const { dotColor, label } = getStatusMeta(status);
+
+ return (
+ <Box
+ aria-label={label}
+ bg={dotColor}
+ boxSize={boxSize}
+ flexShrink={0}
+ rounded="full"
+ role="img"
+ css={status === 'in_progress' ? ACTIVE_HALO : undefined}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStepProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStepProgress.tsx
new file mode 100644
index 0000000000..0a9ccf6dcd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueStepProgress.tsx
@@ -0,0 +1,33 @@
+import { Progress, Stack, Text } from '@chakra-ui/react';
+
+/**
+ * Thin denoising progress bar with a "step 12/30 · 39%" caption. `percentage` is
+ * 0..1 (null → indeterminate). The caption uses tabular numerals so the live
+ * step count and percent don't shift the layout as they tick.
+ */
+export const QueueStepProgress = ({ message, percentage }: { message: string; percentage: number | null }) => {
+ const percentLabel = percentage !== null ? `${Math.round(percentage * 100)}%` : '';
+ const caption = [message.trim(), percentLabel].filter(Boolean).join(' · ');
+
+ return (
+ <Stack gap="1.5" w="full">
+ <Progress.Root
+ aria-label="Queue item progress"
+ colorPalette="accent"
+ max={1}
+ size="xs"
+ value={percentage}
+ w="full"
+ >
+ <Progress.Track rounded="full">
+ <Progress.Range rounded="full" transition="width var(--wb-motion-duration-fast) ease" />
+ </Progress.Track>
+ </Progress.Root>
+ {caption ? (
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {caption}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
index 9d1560a879..99eb5951a4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
@@ -1,130 +1,49 @@
import type { WidgetViewProps } from '@workbench/types';
-import { Badge, HStack, Progress, Stack, Text } from '@chakra-ui/react';
-import { useQueueItemProgress } from '@workbench/backend/progressStore';
-import { Button } from '@workbench/components/ui';
-import { getDestinationLabel, getSourceLabel } from '@workbench/invocation';
+import { Stack } from '@chakra-ui/react';
import { StatusWidgetChip } from '@workbench/widget-frame';
-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';
import { ListOrderedIcon } from 'lucide-react';
-import { useCallback } from 'react';
-
-import { areQueueRowsEqual, createQueueRowsSelector, getPendingQueueCount } from './queueViewModel';
-
-const selectQueueRows = createQueueRowsSelector();
-
+import { useState } from 'react';
+
+import type { QueueFilterId } from './queueFilters';
+
+import { CurrentBatchSection } from './NowNextSection';
+import { QueueFilterTabs } from './QueueFilterTabs';
+import { useScopedQueueCounts } from './queueScope';
+import { QueueStats } from './QueueStats';
+import { RecentSection } from './RecentSection';
+
+/**
+ * Queue console: server-wide stats, status filters, a live NOW & NEXT card, and
+ * the RECENT history. Header (title/Pause/menu) and the MODEL CACHE footer are
+ * provided through the manifest's chrome slots; this view is just the scrolling
+ * body. In a collapsed bottom dock it degrades to a single status chip.
+ */
export const QueueWidgetView = ({ presentation, region }: WidgetViewProps) => {
- const pendingQueueCount = useActiveProjectSelector((project) => getPendingQueueCount(project.queue.items));
+ const counts = useScopedQueueCounts();
if (region === 'bottom' && presentation !== 'expanded') {
- return <StatusWidgetChip icon={ListOrderedIcon}>{pendingQueueCount} queued</StatusWidgetChip>;
- }
+ const isGenerating = counts.in_progress > 0;
- if (region === 'bottom') {
- return <QueueContents />;
+ return (
+ <StatusWidgetChip icon={ListOrderedIcon} tone={isGenerating ? 'accent' : undefined}>
+ {isGenerating ? `${counts.in_progress} generating` : `${counts.pending} queued`}
+ </StatusWidgetChip>
+ );
}
- return <QueueContents />;
+ return <QueueContent />;
};
-const QueueItemLiveProgress = ({ queueItemId }: { queueItemId: string }) => {
- const progress = useQueueItemProgress(queueItemId);
-
- if (!progress || (!progress.message && progress.percentage === null)) {
- return null;
- }
+const QueueContent = () => {
+ const [filter, setFilter] = useState<QueueFilterId>('all');
return (
- <Stack gap="1">
- <Progress.Root
- aria-label={progress.message || 'Generation progress'}
- max={1}
- size="xs"
- value={progress.percentage}
- >
- <Progress.Track>
- <Progress.Range />
- </Progress.Track>
- </Progress.Root>
- {progress.message ? (
- <Text color="fg.subtle" fontSize="2xs">
- {progress.message}
- </Text>
- ) : null}
+ <Stack gap="3" p="3">
+ <QueueStats />
+ <QueueFilterTabs value={filter} onChange={setFilter} />
+ <CurrentBatchSection />
+ <RecentSection filter={filter} />
</Stack>
);
};
-
-const QueueContents = () => {
- const queueRows = useWorkbenchSelector((snapshot) => selectQueueRows(snapshot.state.projects), areQueueRowsEqual);
-
- return (
- <Stack gap="2" p="2">
- {queueRows.length === 0 ? (
- <Text color="fg.subtle" fontSize="2xs">
- Queue submissions will appear here.
- </Text>
- ) : (
- queueRows.map(({ item, projectId, projectName }) => {
- const backendIds = item.backendItemIds?.length ? ` backend ${item.backendItemIds.join(', ')}` : '';
- const resultCount = item.resultImages?.length ? `${item.resultImages.length} image(s)` : 'No results yet';
- const generateValues = item.snapshot.widgetStates.generate.values as Record<string, unknown>;
- const prompt = typeof generateValues.positivePrompt === 'string' ? generateValues.positivePrompt.trim() : '';
- const promptSummary = prompt ? prompt.slice(0, 72) : 'No prompt snapshot';
- const canCancel = item.cancellable && (item.status === 'pending' || item.status === 'running');
-
- return (
- <Stack
- key={item.id}
- bg="bg.subtle"
- borderWidth="1px"
- borderColor={item.status === 'failed' ? 'fg.error' : 'border.subtle'}
- gap="1"
- p="2"
- rounded="md"
- >
- <HStack justify="space-between">
- <Text fontSize="2xs" fontWeight="700">
- {projectName}
- </Text>
- <Badge colorPalette={item.status === 'failed' ? 'red' : item.status === 'completed' ? 'green' : 'blue'}>
- {item.status}
- </Badge>
- </HStack>
- <Text color="fg.subtle" fontSize="2xs">
- {getSourceLabel(item.snapshot.sourceId)} to {getDestinationLabel(item.snapshot.destination)} · Graph{' '}
- {item.snapshot.graph.label || item.snapshot.graph.id}
- </Text>
- <Text color="fg.subtle" fontSize="2xs">
- {promptSummary}
- </Text>
- {item.status === 'running' ? <QueueItemLiveProgress queueItemId={item.id} /> : null}
- <HStack justify="space-between">
- <Text color={item.status === 'failed' ? 'fg.error' : 'fg.subtle'} fontSize="2xs">
- {item.id}
- {backendIds} · {resultCount}
- {item.error ? ` · ${item.error}` : ''}
- </Text>
- {canCancel ? <CancelQueueItemButton projectId={projectId} queueItemId={item.id} /> : null}
- </HStack>
- </Stack>
- );
- })
- )}
- </Stack>
- );
-};
-
-const CancelQueueItemButton = ({ projectId, queueItemId }: { projectId: string; queueItemId: string }) => {
- const dispatch = useWorkbenchDispatch();
- const handleCancel = useCallback(
- () => dispatch({ projectId, queueItemId, type: 'cancelQueueItem' }),
- [dispatch, projectId, queueItemId]
- );
-
- return (
- <Button size="2xs" variant="outline" onClick={handleCancel}>
- Cancel
- </Button>
- );
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsx
new file mode 100644
index 0000000000..731ed3c833
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/RecentSection.tsx
@@ -0,0 +1,43 @@
+import { Stack, Text } from '@chakra-ui/react';
+import { useMemo } from 'react';
+
+import type { QueueFilterId } from './queueFilters';
+
+import { useQueueLoadState } from './queueDataStore';
+import { matchesFilter } from './queueFilters';
+import { QueueItemRow } from './QueueItemRow';
+import { useScopedCurrentBatchItems, useScopedRecentItems } from './queueScope';
+import { SectionHeader } from './SectionHeader';
+
+/**
+ * RECENT — the windowed queue history, filtered by the active tab. The running
+ * and next items are excluded here since NOW & NEXT already shows them.
+ */
+export const RecentSection = ({ filter }: { filter: QueueFilterId }) => {
+ const currentBatchItems = useScopedCurrentBatchItems();
+ const items = useScopedRecentItems();
+ const { error, loadState } = useQueueLoadState();
+
+ const excluded = useMemo(() => new Set(currentBatchItems.map((item) => item.item_id)), [currentBatchItems]);
+ const filtered = useMemo(
+ () => items.filter((item) => !excluded.has(item.item_id) && matchesFilter(item.status, filter)),
+ [excluded, filter, items]
+ );
+
+ return (
+ <Stack gap="2">
+ <SectionHeader count={filtered.length} title="Recent" />
+ {filtered.length === 0 ? (
+ <Text color={loadState === 'error' ? 'fg.error' : 'fg.subtle'} fontSize="2xs" px="1">
+ {loadState === 'loading' ? 'Loading queue…' : loadState === 'error' ? error : 'Nothing here yet.'}
+ </Text>
+ ) : (
+ <Stack gap="1">
+ {filtered.map((item) => (
+ <QueueItemRow key={item.item_id} item={item} />
+ ))}
+ </Stack>
+ )}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/SectionHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/SectionHeader.tsx
new file mode 100644
index 0000000000..c47af01bfc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/SectionHeader.tsx
@@ -0,0 +1,15 @@
+import { HStack, Text } from '@chakra-ui/react';
+
+/** Small uppercase section label with an optional count, e.g. "RECENT 13". */
+export const SectionHeader = ({ title, count }: { title: string; count?: number }) => (
+ <HStack gap="2" px="1">
+ <Text color="fg.muted" fontSize="2xs" fontWeight="700" letterSpacing="0.06em" textTransform="uppercase">
+ {title}
+ </Text>
+ {count !== undefined ? (
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {count}
+ </Text>
+ ) : null}
+ </HStack>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.ts
new file mode 100644
index 0000000000..efb918a64d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { getCurrentBatchItems } from './currentBatchItems';
+
+const createItem = (item_id: number, batch_id: string, status: QueueServerItem['status']): QueueServerItem => ({
+ batch_id,
+ created_at: '2026-06-26T00:00:00Z',
+ item_id,
+ session_id: `session-${item_id}`,
+ status,
+ updated_at: '2026-06-26T00:00:00Z',
+});
+
+describe('getCurrentBatchItems', () => {
+ it('shows the current item and every pending item from the current batch', () => {
+ const current = createItem(2, 'batch-a', 'in_progress');
+ const items = [
+ createItem(4, 'batch-b', 'pending'),
+ createItem(3, 'batch-a', 'pending'),
+ current,
+ createItem(1, 'batch-a', 'completed'),
+ ];
+
+ expect(
+ getCurrentBatchItems({ current, items, next: createItem(3, 'batch-a', 'pending') }).map((item) => item.item_id)
+ ).toEqual([2, 3]);
+ });
+
+ it('uses the next item batch when there is no current item', () => {
+ const next = createItem(5, 'batch-c', 'pending');
+ const items = [createItem(6, 'batch-c', 'pending'), next, createItem(4, 'batch-b', 'pending')];
+
+ expect(getCurrentBatchItems({ current: null, items, next }).map((item) => item.item_id)).toEqual([5, 6]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.ts
new file mode 100644
index 0000000000..f494480517
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/currentBatchItems.ts
@@ -0,0 +1,40 @@
+import type { QueueServerItem } from './queueServerApi';
+
+const isCurrentBatchStatus = (status: QueueServerItem['status']): boolean =>
+ status === 'pending' || status === 'in_progress';
+
+export const getCurrentBatchItems = ({
+ current,
+ items,
+ next,
+}: {
+ current: QueueServerItem | null;
+ items: QueueServerItem[];
+ next: QueueServerItem | null;
+}): QueueServerItem[] => {
+ const batchId = current?.batch_id ?? next?.batch_id ?? null;
+
+ if (!batchId) {
+ return [];
+ }
+
+ const itemsById = new Map<number, QueueServerItem>();
+
+ for (const item of [current, next, ...items]) {
+ if (item && item.batch_id === batchId && isCurrentBatchStatus(item.status)) {
+ itemsById.set(item.item_id, item);
+ }
+ }
+
+ return [...itemsById.values()].sort((left, right) => {
+ if (left.status === 'in_progress' && right.status !== 'in_progress') {
+ return -1;
+ }
+
+ if (left.status !== 'in_progress' && right.status === 'in_progress') {
+ return 1;
+ }
+
+ return left.item_id - right.item_id;
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.ts
new file mode 100644
index 0000000000..4e27f471f8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/fieldValues.ts
@@ -0,0 +1,68 @@
+import type { QueueServerItem } from './queueServerApi';
+
+/**
+ * Best-effort recovery of the human-facing generation parameters for a queue
+ * item. The reliable source is the local submission snapshot (matched in the
+ * view by origin), but server items from other clients/sources only carry
+ * `field_values` — generic `{node_path, field_name, value}` substitutions. For
+ * webv2 generate batches these are exactly the seed (number) + positive/negative
+ * prompts (strings), so we recover them by value type and order, degrading
+ * gracefully for unknown graphs.
+ */
+
+export interface QueueGenerationMeta {
+ positivePrompt?: string;
+ negativePrompt?: string;
+ seed?: number;
+}
+
+export const extractGenerationMeta = (item: QueueServerItem): QueueGenerationMeta => {
+ const meta: QueueGenerationMeta = {};
+ const prompts: string[] = [];
+
+ for (const fieldValue of item.field_values ?? []) {
+ const { value } = fieldValue;
+
+ if (typeof value === 'number' && meta.seed === undefined) {
+ meta.seed = value;
+ } else if (typeof value === 'string' && value.trim().length > 0) {
+ prompts.push(value);
+ }
+ }
+
+ if (prompts[0] !== undefined) {
+ meta.positivePrompt = prompts[0];
+ }
+
+ if (prompts[1] !== undefined) {
+ meta.negativePrompt = prompts[1];
+ }
+
+ return meta;
+};
+
+/** First result image name from a completed item's session, or null. */
+export const getResultImageName = (item: QueueServerItem): string | null => {
+ for (const result of Object.values(item.session?.results ?? {})) {
+ if (!result || typeof result !== 'object') {
+ continue;
+ }
+
+ const image = (result as { image?: { image_name?: unknown } }).image;
+ if (typeof image?.image_name === 'string') {
+ return image.image_name;
+ }
+
+ const collection = (result as { collection?: unknown }).collection;
+ if (Array.isArray(collection)) {
+ for (const entry of collection) {
+ const imageName = entry && typeof entry === 'object' ? (entry as { image_name?: unknown }).image_name : null;
+ if (typeof imageName === 'string') {
+ return imageName;
+ }
+ }
+ }
+ }
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/formatDuration.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/formatDuration.ts
new file mode 100644
index 0000000000..afb885348c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/formatDuration.ts
@@ -0,0 +1,61 @@
+/**
+ * Compact execution-time labels for queue items ("4.37s", "1m 23s"). Computed
+ * from the backend's `started_at`/`completed_at` ISO timestamps; returns null
+ * when either is missing so callers can omit the field.
+ */
+export const formatDuration = (startedAt?: string | null, completedAt?: string | null): string | null => {
+ if (!startedAt || !completedAt) {
+ return null;
+ }
+
+ const seconds = (new Date(completedAt).getTime() - new Date(startedAt).getTime()) / 1000;
+
+ if (!Number.isFinite(seconds) || seconds < 0) {
+ return null;
+ }
+
+ if (seconds < 60) {
+ return `${seconds.toFixed(2)}s`;
+ }
+
+ const minutes = Math.floor(seconds / 60);
+
+ if (minutes < 60) {
+ return `${minutes}m ${Math.round(seconds % 60)}s`;
+ }
+
+ const hours = Math.floor(minutes / 60);
+
+ return `${hours}h ${minutes % 60}m`;
+};
+
+/** Ultra-compact "age" label for a timestamp ("now", "12s", "19m", "1h", "3d"). */
+export const formatCompactAge = (timestamp?: string | null): string => {
+ if (!timestamp) {
+ return '';
+ }
+
+ const seconds = (Date.now() - new Date(timestamp).getTime()) / 1000;
+
+ if (!Number.isFinite(seconds) || seconds < 0) {
+ return '';
+ }
+
+ if (seconds < 5) {
+ return 'now';
+ }
+
+ if (seconds < 60) {
+ return `${Math.floor(seconds)}s`;
+ }
+
+ const minutes = Math.floor(seconds / 60);
+
+ if (minutes < 60) {
+ return `${minutes}m`;
+ }
+
+ const hours = Math.floor(minutes / 60);
+
+ return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
index f1bf31d0e6..1d8ac3e1e4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
@@ -2,16 +2,29 @@ import type { WidgetManifest } from '@workbench/types';
import { ListOrderedIcon } from 'lucide-react';
+import { ModelCacheFooter } from './ModelCacheFooter';
+import { QueueDataRuntime } from './QueueDataRuntime';
+import { QueueHeaderActions } from './QueueHeaderActions';
+import { QueueHeaderLabel } from './QueueHeaderLabel';
+import { QueueHeaderMenu } from './QueueHeaderMenu';
import { QueueWidgetView } from './QueueWidgetView';
export const queueWidgetManifest: WidgetManifest = {
allowMultiple: false,
- allowedRegions: ['right', 'bottom'],
- failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ allowedRegions: ['right'],
+ failurePolicy: {
+ isolateRenderFailure: true,
+ onRegistrationFailure: 'disable',
+ },
+ footer: ModelCacheFooter,
+ headerActions: QueueHeaderActions,
+ headerMenu: QueueHeaderMenu,
+ host: QueueDataRuntime,
icon: ListOrderedIcon,
id: 'queue',
- label: 'Queue',
+ label: QueueHeaderLabel,
labelText: 'Queue',
+ settingsSection: 'queue',
version: 1,
view: QueueWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.test.ts
new file mode 100644
index 0000000000..822d4a6d38
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { getModelCacheClearToast, getModelCacheUsage, normalizeModelCacheClearResult } from './modelCacheStore';
+
+describe('model cache stats helpers', () => {
+ it('uses current cache usage instead of the historical high watermark', () => {
+ expect(
+ getModelCacheUsage({
+ cache_size: 100,
+ cache_used: 12,
+ cleared: 0,
+ high_watermark: 90,
+ hits: 0,
+ in_cache: 1,
+ misses: 0,
+ })
+ ).toEqual({ total: 100, used: 12 });
+ });
+
+ it('reports whether clear cache actually cleared models', () => {
+ expect(getModelCacheClearToast({ bytes_freed: 1024, models_cleared: 2 })).toEqual({
+ description: 'Cleared 2 cached models and freed 1.0 KB.',
+ status: 'success',
+ title: 'Model cache cleared',
+ });
+
+ expect(getModelCacheClearToast({ bytes_freed: 0, models_cleared: 0 })).toEqual({
+ description:
+ 'No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use.',
+ status: 'info',
+ title: 'No cached models cleared',
+ });
+ });
+
+ it('normalizes legacy null clear-cache responses', () => {
+ expect(normalizeModelCacheClearResult(null)).toEqual({ bytes_freed: 0, models_cleared: 0 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.ts
new file mode 100644
index 0000000000..e15879c4e6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/modelCacheStore.ts
@@ -0,0 +1,102 @@
+import { apiFetchJson, getApiErrorMessage } from '@workbench/backend/http';
+import { createExternalStore } from '@workbench/externalStore';
+import { formatBytes } from '@workbench/models/taxonomy';
+
+/**
+ * RAM/VRAM model-cache statistics for the Queue widget's footer. Pull-based:
+ * the backend exposes `GET /api/v2/models/stats` (no socket events for cache
+ * stats), so we refresh on mount, after a model loads, and after a clear.
+ */
+
+export interface ModelCacheStats {
+ hits: number;
+ misses: number;
+ /** Peak bytes resident in the cache. */
+ high_watermark: number;
+ /** Current bytes resident in the cache. */
+ cache_used?: number;
+ /** Number of models currently held in the cache. */
+ in_cache: number;
+ cleared: number;
+ /** Configured cache budget, in bytes. */
+ cache_size: number;
+ loaded_model_sizes?: Record<string, number>;
+}
+
+export interface ModelCacheClearResult {
+ models_cleared: number;
+ bytes_freed: number;
+}
+
+const EMPTY_MODEL_CACHE_CLEAR_RESULT: ModelCacheClearResult = { bytes_freed: 0, models_cleared: 0 };
+
+export const normalizeModelCacheClearResult = (result: ModelCacheClearResult | null): ModelCacheClearResult =>
+ result ?? EMPTY_MODEL_CACHE_CLEAR_RESULT;
+
+export const getModelCacheUsage = (stats: ModelCacheStats | null): { used: number; total: number } => ({
+ total: stats?.cache_size ?? 0,
+ used: stats?.cache_used ?? stats?.high_watermark ?? 0,
+});
+
+export const getModelCacheClearToast = ({
+ bytes_freed,
+ models_cleared,
+}: ModelCacheClearResult): { title: string; description: string; status: 'info' | 'success' } => {
+ if (models_cleared === 0) {
+ return {
+ description:
+ 'No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use.',
+ status: 'info',
+ title: 'No cached models cleared',
+ };
+ }
+
+ return {
+ description: `Cleared ${models_cleared} cached model${models_cleared === 1 ? '' : 's'} and freed ${formatBytes(bytes_freed)}.`,
+ status: 'success',
+ title: 'Model cache cleared',
+ };
+};
+
+interface ModelCacheSnapshot {
+ stats: ModelCacheStats | null;
+ loadState: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+const store = createExternalStore<ModelCacheSnapshot>({ error: null, loadState: 'idle', stats: null });
+
+let inflight: Promise<void> | null = null;
+
+export const refreshModelCacheStats = (): Promise<void> => {
+ if (inflight) {
+ return inflight;
+ }
+
+ if (store.getSnapshot().loadState === 'idle') {
+ store.patchSnapshot({ loadState: 'loading' });
+ }
+
+ inflight = apiFetchJson<ModelCacheStats | null>('/api/v2/models/stats')
+ .then((stats) => {
+ store.patchSnapshot({ error: null, loadState: 'loaded', stats });
+ })
+ .catch((error: unknown) => {
+ store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load cache stats'), loadState: 'error' });
+ })
+ .finally(() => {
+ inflight = null;
+ });
+
+ return inflight;
+};
+
+export const clearModelCache = async (): Promise<ModelCacheClearResult> => {
+ const result = await apiFetchJson<ModelCacheClearResult | null>('/api/v2/models/empty_model_cache', {
+ method: 'POST',
+ });
+ await refreshModelCacheStats();
+ return normalizeModelCacheClearResult(result);
+};
+
+export const useModelCacheStats = (): ModelCacheSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.test.ts
new file mode 100644
index 0000000000..a997a5fda3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.test.ts
@@ -0,0 +1,27 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { clearQueueConfirmation, getQueueConfirmation, requestQueueConfirmation } from './queueConfirmationStore';
+
+describe('queueConfirmationStore', () => {
+ beforeEach(() => {
+ clearQueueConfirmation();
+ });
+
+ it('keeps confirmation state outside the menu item lifecycle until explicitly cleared', () => {
+ const onConfirm = vi.fn();
+
+ requestQueueConfirmation({
+ body: 'Clear queued work?',
+ confirmLabel: 'Clear Queue',
+ onConfirm,
+ title: 'Clear queue?',
+ });
+
+ expect(getQueueConfirmation()).toMatchObject({
+ body: 'Clear queued work?',
+ confirmLabel: 'Clear Queue',
+ onConfirm,
+ title: 'Clear queue?',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.ts
new file mode 100644
index 0000000000..e83a53bdd7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueConfirmationStore.ts
@@ -0,0 +1,25 @@
+import type { ReactNode } from 'react';
+
+import { createExternalStore } from '@workbench/externalStore';
+
+export interface QueueConfirmation {
+ body: ReactNode;
+ confirmLabel: string;
+ onConfirm: () => Promise<void> | void;
+ title: string;
+}
+
+const queueConfirmationStore = createExternalStore<{ confirmation: QueueConfirmation | null }>({ confirmation: null });
+
+export const requestQueueConfirmation = (confirmation: QueueConfirmation): void => {
+ queueConfirmationStore.setSnapshot({ confirmation });
+};
+
+export const clearQueueConfirmation = (): void => {
+ queueConfirmationStore.setSnapshot({ confirmation: null });
+};
+
+export const getQueueConfirmation = (): QueueConfirmation | null => queueConfirmationStore.getSnapshot().confirmation;
+
+export const useQueueConfirmation = (): QueueConfirmation | null =>
+ queueConfirmationStore.useSelector((snapshot) => snapshot.confirmation, Object.is);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.ts
new file mode 100644
index 0000000000..d0058d60ee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueDataStore.ts
@@ -0,0 +1,165 @@
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { createExternalStore } from '@workbench/externalStore';
+import { shallowEqual } from '@workbench/workbenchSelectors';
+
+import type { QueueAndProcessorStatus, QueueQueryScope, QueueServerItem, QueueStatusCounts } from './queueServerApi';
+
+import { getCurrentBatchItems } from './currentBatchItems';
+import { clearProgressForQueueItemsWithResults } from './queueProgressCleanup';
+import {
+ getCurrentQueueItem,
+ getNextQueueItem,
+ getQueueItemIds,
+ getQueueItemsByIds,
+ getQueueStatus,
+} from './queueServerApi';
+
+/**
+ * Read model for the whole backend session queue, shared by the Queue widget's
+ * header, stats, CURRENT BATCH, and RECENT sections. A single external store fed by
+ * one debounced `refreshQueue()` keeps every section consistent and lets each
+ * subscribe to just the slice it renders (composition: one lifted store, many
+ * thin readers). Socket events drive refresh via `QueueDataRuntime`.
+ */
+
+/** How many of the most-recent items we hydrate for the RECENT list. */
+export const RECENT_WINDOW = 50;
+const REFRESH_DEBOUNCE_MS = 300;
+
+const EMPTY_COUNTS: QueueStatusCounts = {
+ canceled: 0,
+ completed: 0,
+ failed: 0,
+ in_progress: 0,
+ pending: 0,
+ queue_id: 'default',
+ total: 0,
+};
+
+interface QueueDataSnapshot {
+ status: QueueAndProcessorStatus | null;
+ current: QueueServerItem | null;
+ next: QueueServerItem | null;
+ items: QueueServerItem[];
+ scope: QueueQueryScope;
+ loadState: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+const store = createExternalStore<QueueDataSnapshot>({
+ current: null,
+ error: null,
+ items: [],
+ loadState: 'idle',
+ next: null,
+ scope: {},
+ status: null,
+});
+
+let inflight: Promise<void> | null = null;
+let refreshTimer: ReturnType<typeof setTimeout> | null = null;
+let needsRefresh = false;
+let refreshSequence = 0;
+
+const runRefresh = async (): Promise<void> => {
+ const scope = store.getSnapshot().scope;
+ const sequence = ++refreshSequence;
+
+ if (store.getSnapshot().loadState === 'idle') {
+ store.patchSnapshot({ loadState: 'loading' });
+ }
+
+ try {
+ // Independent reads run together to avoid a request waterfall; the window
+ // fetch is the only one that must wait (it needs the ordered ids first).
+ const [status, current, next, idsResult] = await Promise.all([
+ getQueueStatus(scope),
+ getCurrentQueueItem(scope),
+ getNextQueueItem(scope),
+ getQueueItemIds('desc', scope),
+ ]);
+ const items = await getQueueItemsByIds(idsResult.item_ids.slice(0, RECENT_WINDOW));
+
+ if (sequence === refreshSequence) {
+ clearProgressForQueueItemsWithResults([current, next, ...items].filter((item) => item !== null));
+ store.patchSnapshot({ current, error: null, items, loadState: 'loaded', next, status });
+ }
+ } catch (error) {
+ if (sequence === refreshSequence) {
+ store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load queue'), loadState: 'error' });
+ }
+ }
+};
+
+const runRefreshLoop = async (): Promise<void> => {
+ do {
+ needsRefresh = false;
+ await runRefresh();
+ } while (needsRefresh);
+};
+
+/** Coalesced refresh — many socket events in a burst collapse into one fetch. */
+export const refreshQueue = (): Promise<void> => {
+ if (inflight !== null && refreshTimer === null) {
+ needsRefresh = true;
+ return inflight;
+ }
+
+ if (refreshTimer !== null) {
+ return inflight ?? Promise.resolve();
+ }
+
+ inflight = new Promise<void>((resolve) => {
+ refreshTimer = setTimeout(() => {
+ refreshTimer = null;
+ void runRefreshLoop().finally(() => {
+ inflight = null;
+ resolve();
+ });
+ }, REFRESH_DEBOUNCE_MS);
+ });
+
+ return inflight;
+};
+
+export const setQueueScope = (scope: QueueQueryScope): void => {
+ const previous = store.getSnapshot().scope;
+ const isSameScope = previous.originPrefix === scope.originPrefix;
+
+ if (isSameScope) {
+ return;
+ }
+
+ store.patchSnapshot({ current: null, error: null, items: [], loadState: 'loading', next: null, scope, status: null });
+ void refreshQueue();
+};
+
+/** First load — idempotent; safe to call from every mounting surface. */
+export const ensureQueueLoaded = (): void => {
+ if (store.getSnapshot().loadState === 'idle') {
+ void refreshQueue();
+ }
+};
+
+// --- Selectors / hooks -----------------------------------------------------
+
+export const useQueueCounts = (): QueueStatusCounts =>
+ store.useSelector((snapshot) => snapshot.status?.queue ?? EMPTY_COUNTS, shallowEqual);
+
+/** The processor is "paused" when it has been stopped (`is_started` false). */
+export const useIsProcessorPaused = (): boolean =>
+ store.useSelector((snapshot) => snapshot.status?.processor.is_started === false);
+
+export const useNowNextItems = (): { current: QueueServerItem | null; next: QueueServerItem | null } =>
+ store.useSelector((snapshot) => ({ current: snapshot.current, next: snapshot.next }), shallowEqual);
+
+export const useCurrentBatchItems = (): QueueServerItem[] =>
+ store.useSelector(
+ (snapshot) => getCurrentBatchItems({ current: snapshot.current, items: snapshot.items, next: snapshot.next }),
+ shallowEqual
+ );
+
+export const useRecentItems = (): QueueServerItem[] => store.useSelector((snapshot) => snapshot.items);
+
+export const useQueueLoadState = (): { loadState: QueueDataSnapshot['loadState']; error: string | null } =>
+ store.useSelector((snapshot) => ({ error: snapshot.error, loadState: snapshot.loadState }), shallowEqual);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.ts
new file mode 100644
index 0000000000..5a0650351d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueFilters.ts
@@ -0,0 +1,44 @@
+import type { BackendQueueItemStatus } from '@workbench/backend/events';
+
+import type { QueueStatusCounts } from './queueServerApi';
+
+/** Status filters for the RECENT list, matching the screenshot's tab row. */
+export type QueueFilterId = 'all' | 'active' | 'completed' | 'failed' | 'canceled';
+
+export const QUEUE_FILTERS: { id: QueueFilterId; label: string }[] = [
+ { id: 'all', label: 'All' },
+ { id: 'active', label: 'Active' },
+ { id: 'completed', label: 'Done' },
+ { id: 'failed', label: 'Failed' },
+ { id: 'canceled', label: 'Canceled' },
+];
+
+export const matchesFilter = (status: BackendQueueItemStatus, filter: QueueFilterId): boolean => {
+ if (filter === 'all') {
+ return true;
+ }
+
+ if (filter === 'active') {
+ return status === 'pending' || status === 'in_progress';
+ }
+
+ return status === filter;
+};
+
+/** Count for a filter, derived from the server-wide status counts (not the windowed list). */
+export const getFilterCount = (counts: QueueStatusCounts, filter: QueueFilterId): number => {
+ switch (filter) {
+ case 'all':
+ return counts.total;
+ case 'active':
+ return counts.pending + counts.in_progress;
+ case 'completed':
+ return counts.completed;
+ case 'failed':
+ return counts.failed;
+ case 'canceled':
+ return counts.canceled;
+ default:
+ return 0;
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.test.ts
new file mode 100644
index 0000000000..66da0a4c02
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getQueueMenuActions } from './queueMenuActions';
+
+describe('getQueueMenuActions', () => {
+ it('uses the same cancellation and processor actions for topbar and widget menus', () => {
+ const actions = getQueueMenuActions({
+ cancellableCount: 2,
+ canManageProcessor: true,
+ hasPendingQueueWork: true,
+ hasRunningItem: true,
+ isConnected: true,
+ onCancelAll: vi.fn(),
+ onCancelAllExceptCurrent: vi.fn(),
+ onCancelCurrent: vi.fn(),
+ onOpenQueue: vi.fn(),
+ onPauseProcessor: vi.fn(),
+ onResumeProcessor: vi.fn(),
+ });
+
+ expect(actions.map((action) => action.label)).toEqual([
+ 'Cancel Current Item',
+ 'Cancel All Items',
+ 'Cancel all except current item',
+ 'Resume Processor',
+ 'Pause Processor',
+ 'Open Queue',
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsx
new file mode 100644
index 0000000000..6ca7b44109
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueMenuActions.tsx
@@ -0,0 +1,246 @@
+import { Icon, Menu } from '@chakra-ui/react';
+import { useCapabilities } from '@workbench/auth/capabilities';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { useNotify } from '@workbench/useNotify';
+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
+import { useWorkbenchSelector } from '@workbench/WorkbenchContext';
+import { ListOrderedIcon, PauseIcon, PlayIcon, XIcon, type LucideIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+
+import { requestQueueConfirmation } from './queueConfirmationStore';
+import { refreshQueue, useNowNextItems, useQueueCounts } from './queueDataStore';
+import { useQueueQueryScope } from './queueScope';
+import { cancelQueueItem, cancelScopedQueueItems, pauseQueueProcessor, resumeQueueProcessor } from './queueServerApi';
+
+const ERROR_ITEM_HOVER_PROPS = { bg: 'bg.error', color: 'fg.error' };
+
+interface QueueMenuActionInputs {
+ cancellableCount: number;
+ hasPendingQueueWork: boolean;
+ hasRunningItem: boolean;
+ isConnected: boolean;
+ canManageProcessor: boolean;
+ onCancelAll: () => void;
+ onCancelAllExceptCurrent: () => void;
+ onCancelCurrent: () => void;
+ onOpenQueue: () => void;
+ onPauseProcessor: () => void;
+ onResumeProcessor: () => void;
+}
+
+export interface QueueMenuAction {
+ label: string;
+ icon: LucideIcon;
+ disabled: boolean;
+ destructive?: boolean;
+ onClick: () => void;
+}
+
+export const getQueueMenuActions = ({
+ cancellableCount,
+ hasPendingQueueWork,
+ hasRunningItem,
+ isConnected,
+ canManageProcessor,
+ onCancelAll,
+ onCancelAllExceptCurrent,
+ onCancelCurrent,
+ onOpenQueue,
+ onPauseProcessor,
+ onResumeProcessor,
+}: QueueMenuActionInputs): QueueMenuAction[] => [
+ {
+ destructive: true,
+ disabled: !isConnected || !hasRunningItem,
+ icon: XIcon,
+ label: 'Cancel Current Item',
+ onClick: onCancelCurrent,
+ },
+ {
+ destructive: true,
+ disabled: cancellableCount === 0,
+ icon: XIcon,
+ label: 'Cancel All Items',
+ onClick: onCancelAll,
+ },
+ {
+ destructive: true,
+ disabled: !isConnected || !hasPendingQueueWork,
+ icon: XIcon,
+ label: 'Cancel all except current item',
+ onClick: onCancelAllExceptCurrent,
+ },
+ {
+ disabled: !isConnected || !canManageProcessor,
+ icon: PlayIcon,
+ label: 'Resume Processor',
+ onClick: onResumeProcessor,
+ },
+ {
+ disabled: !isConnected || !canManageProcessor,
+ icon: PauseIcon,
+ label: 'Pause Processor',
+ onClick: onPauseProcessor,
+ },
+ {
+ disabled: false,
+ icon: ListOrderedIcon,
+ label: 'Open Queue',
+ onClick: onOpenQueue,
+ },
+];
+
+export const useQueueMenuActions = (): QueueMenuAction[] => {
+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
+ const counts = useQueueCounts();
+ const { current } = useNowNextItems();
+ const scope = useQueueQueryScope();
+ const { canManageModels } = useCapabilities();
+ const notify = useNotify();
+ const openWorkbenchWidget = useOpenWorkbenchWidget();
+ const isConnected = backendConnectionStatus === 'connected';
+ const cancellableCount = counts.pending + counts.in_progress;
+ const hasRunningItem = current?.status === 'in_progress';
+ const hasPendingQueueWork = counts.pending > 0;
+
+ const cancelCurrent = useCallback(() => {
+ if (!current) {
+ notify.info('No current item', 'The scoped queue has no in-progress item to cancel.');
+ return;
+ }
+
+ cancelQueueItem(current.item_id)
+ .then(() => refreshQueue())
+ .then(() => notify.success('Cancellation requested', `Backend queue item ${current.item_id}.`))
+ .catch((error: unknown) =>
+ notify.error('Failed to cancel current item', getApiErrorMessage(error, 'Could not cancel the current item.'))
+ );
+ }, [current, notify]);
+
+ const cancelAllExceptCurrent = useCallback(() => {
+ cancelScopedQueueItems(scope, current?.item_id ?? null)
+ .then(() => refreshQueue())
+ .then(() =>
+ notify.success(
+ 'Queue cancellation requested',
+ 'All pending scoped items except the current item were requested.'
+ )
+ )
+ .catch((error: unknown) =>
+ notify.error('Failed to cancel queue items', getApiErrorMessage(error, 'Could not cancel scoped queue items.'))
+ );
+ }, [current?.item_id, notify, scope]);
+
+ const runProcessorAction = useCallback(
+ (label: 'pause' | 'resume') => {
+ const action = label === 'pause' ? pauseQueueProcessor : resumeQueueProcessor;
+
+ action()
+ .then(() => notify.success(label === 'pause' ? 'Processor paused' : 'Processor resumed'))
+ .then(() => refreshQueue())
+ .catch((error: unknown) =>
+ notify.error(
+ label === 'pause' ? 'Failed to pause processor' : 'Failed to resume processor',
+ getApiErrorMessage(error, 'Could not change the queue processor.')
+ )
+ );
+ },
+ [notify]
+ );
+ const cancelAll = useCallback(() => {
+ cancelScopedQueueItems(scope)
+ .then(() => refreshQueue())
+ .then(() => notify.success('Queue cancellation requested', 'All scoped queue items were requested.'))
+ .catch((error: unknown) =>
+ notify.error('Failed to cancel queue items', getApiErrorMessage(error, 'Could not cancel scoped queue items.'))
+ );
+ }, [notify, scope]);
+ const resumeProcessor = useCallback(() => runProcessorAction('resume'), [runProcessorAction]);
+ const pauseProcessor = useCallback(() => runProcessorAction('pause'), [runProcessorAction]);
+ const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);
+
+ return useMemo(
+ () =>
+ getQueueMenuActions({
+ cancellableCount,
+ canManageProcessor: canManageModels,
+ hasPendingQueueWork,
+ hasRunningItem,
+ isConnected,
+ onCancelAll: cancelAll,
+ onCancelAllExceptCurrent: cancelAllExceptCurrent,
+ onCancelCurrent: cancelCurrent,
+ onOpenQueue: openQueue,
+ onPauseProcessor: pauseProcessor,
+ onResumeProcessor: resumeProcessor,
+ }),
+ [
+ cancelAll,
+ cancelAllExceptCurrent,
+ cancelCurrent,
+ cancellableCount,
+ canManageModels,
+ hasPendingQueueWork,
+ hasRunningItem,
+ isConnected,
+ openQueue,
+ pauseProcessor,
+ resumeProcessor,
+ ]
+ );
+};
+
+export const QueueMenuItems = ({ actions, label }: { actions: QueueMenuAction[]; label?: string }) => {
+ const destructiveActions = actions.filter((action) => action.destructive);
+ const processorActions = actions.filter((action) => !action.destructive);
+
+ return (
+ <>
+ <Menu.ItemGroup>
+ {label ? (
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ {label}
+ </Menu.ItemGroupLabel>
+ ) : null}
+ {destructiveActions.map((action) => (
+ <DestructiveQueueMenuItem key={action.label} action={action} />
+ ))}
+ </Menu.ItemGroup>
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ {processorActions.map((action) => (
+ <Menu.Item key={action.label} disabled={action.disabled} value={action.label} onClick={action.onClick}>
+ <Icon as={action.icon} boxSize="3" />
+ <Menu.ItemText>{action.label}</Menu.ItemText>
+ </Menu.Item>
+ ))}
+ </Menu.ItemGroup>
+ </>
+ );
+};
+
+const DestructiveQueueMenuItem = ({ action }: { action: QueueMenuAction }) => {
+ const onClick = useCallback(
+ () =>
+ requestQueueConfirmation({
+ body: 'This requests cancellation for queue work in the current scope. In-progress items may stop after the backend acknowledges cancellation.',
+ confirmLabel: action.label,
+ onConfirm: action.onClick,
+ title: `${action.label}?`,
+ }),
+ [action]
+ );
+
+ return (
+ <Menu.Item
+ color="fg.error"
+ disabled={action.disabled}
+ value={action.label}
+ _hover={ERROR_ITEM_HOVER_PROPS}
+ onClick={onClick}
+ >
+ <Icon as={action.icon} boxSize="3" />
+ <Menu.ItemText>{action.label}</Menu.ItemText>
+ </Menu.Item>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.ts
new file mode 100644
index 0000000000..03d7eec07a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { getQueueItemIdsWithResultImages } from './queueProgressCleanup';
+
+const createItem = (itemId: number, results: Record<string, unknown> = {}): QueueServerItem => ({
+ batch_id: 'batch-1',
+ created_at: '2026-06-27T00:00:00Z',
+ item_id: itemId,
+ session: { results },
+ session_id: 'session-1',
+ status: 'completed',
+ updated_at: '2026-06-27T00:00:00Z',
+});
+
+describe('getQueueItemIdsWithResultImages', () => {
+ it('returns queue item ids that have final image results', () => {
+ expect(
+ getQueueItemIdsWithResultImages([
+ createItem(1),
+ createItem(2, { node: { image: { image_name: 'result.png' } } }),
+ createItem(3, { node: { collection: [{ image_name: 'batch-result.png' }] } }),
+ ])
+ ).toEqual([2, 3]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.ts
new file mode 100644
index 0000000000..00dfc40566
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueProgressCleanup.ts
@@ -0,0 +1,23 @@
+import { itemProgressStore } from '@workbench/backend/itemProgressStore';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { getResultImageName } from './fieldValues';
+
+export const getQueueItemIdsWithResultImages = (items: QueueServerItem[]): number[] => {
+ const itemIds: number[] = [];
+
+ for (const item of items) {
+ if (getResultImageName(item)) {
+ itemIds.push(item.item_id);
+ }
+ }
+
+ return itemIds;
+};
+
+export const clearProgressForQueueItemsWithResults = (items: QueueServerItem[]): void => {
+ for (const itemId of getQueueItemIdsWithResultImages(items)) {
+ itemProgressStore.clear(itemId);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.ts
new file mode 100644
index 0000000000..2d6bacc8c0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.test.ts
@@ -0,0 +1,69 @@
+import type { Project, QueueItem } from '@workbench/types';
+
+import { buildQueueItemOrigin, buildProjectQueueItemOriginPrefix } from '@workbench/backend/events';
+import { describe, expect, it } from 'vitest';
+
+import type { QueueServerItem } from './queueServerApi';
+
+import { getQueueQueryScope, isQueueServerItemInProject } from './queueScope';
+
+const createProject = (items: QueueItem[]): Project =>
+ ({
+ id: 'project-1',
+ name: 'Project 1',
+ queue: { items },
+ }) as Project;
+
+const createLocalQueueItem = ({
+ backendItemIds,
+ id,
+ status,
+}: {
+ backendItemIds?: number[];
+ id: string;
+ status: QueueItem['status'];
+}): QueueItem =>
+ ({
+ backendItemIds,
+ id,
+ status,
+ }) as QueueItem;
+
+const createServerQueueItem = ({ itemId, origin }: { itemId: number; origin?: string | null }): QueueServerItem =>
+ ({
+ item_id: itemId,
+ origin,
+ }) as QueueServerItem;
+
+describe('isQueueServerItemInProject', () => {
+ it('matches server queue items by webv2 origin', () => {
+ const project = createProject([createLocalQueueItem({ id: 'local-1', status: 'pending' })]);
+
+ expect(
+ isQueueServerItemInProject(
+ createServerQueueItem({ itemId: 7, origin: buildQueueItemOrigin('local-1', 'project-1') }),
+ project
+ )
+ ).toBe(true);
+ expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 7, origin: 'webv2:local-1' }), project)).toBe(
+ true
+ );
+ expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 8, origin: 'webv2:local-2' }), project)).toBe(
+ false
+ );
+ });
+
+ it('falls back to backend item ids when origin is unavailable', () => {
+ const project = createProject([createLocalQueueItem({ backendItemIds: [7, 8], id: 'local-1', status: 'running' })]);
+
+ expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 8, origin: null }), project)).toBe(true);
+ expect(isQueueServerItemInProject(createServerQueueItem({ itemId: 9, origin: null }), project)).toBe(false);
+ });
+ it('builds backend origin-prefix scopes from the active project', () => {
+ expect(getQueueQueryScope({ projectId: 'project-1', queueJobsScope: 'active-project' })).toEqual({
+ originPrefix: buildProjectQueueItemOriginPrefix('project-1'),
+ });
+
+ expect(getQueueQueryScope({ projectId: 'project-1', queueJobsScope: 'all' })).toEqual({});
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.ts
new file mode 100644
index 0000000000..f2358803f0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueScope.ts
@@ -0,0 +1,48 @@
+import type { Project, WorkbenchPreferences } from '@workbench/types';
+
+import { buildProjectQueueItemOriginPrefix, parseQueueItemOrigin } from '@workbench/backend/events';
+import { useWorkbenchPreferences } from '@workbench/settings/store';
+import { useOptionalWorkbenchSelector } from '@workbench/WorkbenchContext';
+import { useMemo } from 'react';
+
+import type { QueueQueryScope, QueueServerItem } from './queueServerApi';
+
+import { useCurrentBatchItems, useQueueCounts, useRecentItems } from './queueDataStore';
+
+export type QueueJobsScope = WorkbenchPreferences['queueJobsScope'];
+
+export const isQueueServerItemInProject = (serverItem: QueueServerItem, project: Pick<Project, 'queue'>): boolean => {
+ const localQueueItemId = parseQueueItemOrigin(serverItem.origin);
+
+ if (localQueueItemId && project.queue.items.some((item) => item.id === localQueueItemId)) {
+ return true;
+ }
+
+ return project.queue.items.some((item) => item.backendItemIds?.includes(serverItem.item_id) ?? false);
+};
+
+export const useQueueJobsScope = (): QueueJobsScope => useWorkbenchPreferences().queueJobsScope;
+
+export const getQueueQueryScope = ({
+ projectId,
+ queueJobsScope,
+}: {
+ projectId: string | null;
+ queueJobsScope: QueueJobsScope;
+}): QueueQueryScope =>
+ queueJobsScope === 'active-project' && projectId
+ ? { originPrefix: buildProjectQueueItemOriginPrefix(projectId) }
+ : {};
+
+export const useQueueQueryScope = (): QueueQueryScope => {
+ const queueJobsScope = useQueueJobsScope();
+ const projectId = useOptionalWorkbenchSelector((snapshot) => snapshot.activeProject.id, null);
+
+ return useMemo(() => getQueueQueryScope({ projectId, queueJobsScope }), [projectId, queueJobsScope]);
+};
+
+export const useScopedQueueCounts = useQueueCounts;
+
+export const useScopedCurrentBatchItems = useCurrentBatchItems;
+
+export const useScopedRecentItems = useRecentItems;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.ts
new file mode 100644
index 0000000000..65105d004d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@workbench/backend/http', () => ({
+ apiFetchJson: mocks.apiFetchJson,
+}));
+
+describe('queueServerApi', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchJson.mockResolvedValue({ item_ids: [], total_count: 0 });
+ });
+
+ it('uses backend SQLiteDirection values for queue item ordering', async () => {
+ const { getQueueItemIds } = await import('./queueServerApi');
+
+ await getQueueItemIds('desc');
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/queue/default/item_ids?order_dir=DESC');
+ });
+
+ it('deletes only failed queue items when clearing failed items', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url === '/api/v1/queue/default/item_ids?order_dir=DESC') {
+ return Promise.resolve({ item_ids: [3, 2, 1], total_count: 3 });
+ }
+
+ if (url === '/api/v1/queue/default/items_by_ids') {
+ return Promise.resolve([
+ { item_id: 3, status: 'completed' },
+ { item_id: 2, status: 'failed' },
+ { item_id: 1, status: 'pending' },
+ ]);
+ }
+
+ return Promise.resolve({});
+ });
+
+ const { clearFailedQueueItems } = await import('./queueServerApi');
+
+ await clearFailedQueueItems();
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/queue/default/i/2', { method: 'DELETE' });
+ expect(mocks.apiFetchJson).not.toHaveBeenCalledWith('/api/v1/queue/default/i/1', { method: 'DELETE' });
+ expect(mocks.apiFetchJson).not.toHaveBeenCalledWith('/api/v1/queue/default/i/3', { method: 'DELETE' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.ts
new file mode 100644
index 0000000000..40ae400768
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueServerApi.ts
@@ -0,0 +1,208 @@
+import type { BackendQueueItemStatus } from '@workbench/backend/events';
+
+import { apiFetchJson } from '@workbench/backend/http';
+
+/**
+ * Server-wide session-queue REST layer for the Queue widget. This mirrors the
+ * legacy v6 queue API surface (`frontend/web/src/services/api/endpoints/queue.ts`)
+ * — the same status/list/current/next reads, the `item_ids → items_by_ids`
+ * windowed pagination, and the clear/prune/cancel/pause mutations — ported to
+ * webv2's `apiFetchJson` idiom. Socket events drive refresh (see
+ * `queueDataStore` + `QueueDataRuntime`) in place of RTK Query tag invalidation.
+ *
+ * Unlike the local in-session queue (`project.queue.items`, which only tracks
+ * this client's submissions), this reads the whole backend queue: counts and
+ * items from every source and every client.
+ */
+
+const QUEUE_ID = 'default';
+const buildQueueUrl = (path = ''): string => `/api/v1/queue/${QUEUE_ID}/${path}`;
+
+export interface QueueQueryScope {
+ originPrefix?: string;
+}
+
+const buildQueryString = (params: Record<string, string | undefined>): string => {
+ const searchParams = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined) {
+ searchParams.set(key, value);
+ }
+ }
+
+ const queryString = searchParams.toString();
+
+ return queryString ? `?${queryString}` : '';
+};
+
+/** A single batch substitution recorded for a queue item (prompt / seed / image field). */
+export interface QueueNodeFieldValue {
+ node_path: string;
+ field_name: string;
+ value: string | number | { image_name?: string } | null;
+}
+
+/**
+ * The backend `SessionQueueItem` shape, narrowed to the fields the widget reads.
+ * `session` is the heavy execution graph; we only ever touch `session.results`
+ * to resolve a result image, so it is loosely typed here.
+ */
+export interface QueueServerItem {
+ item_id: number;
+ status: BackendQueueItemStatus;
+ batch_id: string;
+ origin?: string | null;
+ destination?: string | null;
+ session_id: string;
+ error_type?: string | null;
+ error_message?: string | null;
+ error_traceback?: string | null;
+ created_at: string;
+ updated_at: string;
+ started_at?: string | null;
+ completed_at?: string | null;
+ field_values?: QueueNodeFieldValue[] | null;
+ retried_from_item_id?: number | null;
+ session?: { results?: Record<string, unknown> };
+}
+
+export interface QueueStatusCounts {
+ queue_id: string;
+ item_id?: number | null;
+ batch_id?: string | null;
+ session_id?: string | null;
+ pending: number;
+ in_progress: number;
+ completed: number;
+ failed: number;
+ canceled: number;
+ total: number;
+}
+
+export interface QueueProcessorStatus {
+ is_started: boolean;
+ is_processing: boolean;
+}
+
+export interface QueueAndProcessorStatus {
+ queue: QueueStatusCounts;
+ processor: QueueProcessorStatus;
+}
+
+export interface QueueItemIdsResult {
+ item_ids: number[];
+ total_count: number;
+}
+
+// --- Reads -----------------------------------------------------------------
+
+export const getQueueStatus = (scope: QueueQueryScope = {}): Promise<QueueAndProcessorStatus> =>
+ apiFetchJson<QueueAndProcessorStatus>(
+ buildQueueUrl(`status${buildQueryString({ origin_prefix: scope.originPrefix })}`)
+ );
+
+export const getCurrentQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItem | null> =>
+ apiFetchJson<QueueServerItem | null>(
+ buildQueueUrl(`current${buildQueryString({ origin_prefix: scope.originPrefix })}`)
+ );
+
+export const getNextQueueItem = (scope: QueueQueryScope = {}): Promise<QueueServerItem | null> =>
+ apiFetchJson<QueueServerItem | null>(buildQueueUrl(`next${buildQueryString({ origin_prefix: scope.originPrefix })}`));
+
+export const getQueueItem = (itemId: number): Promise<QueueServerItem> =>
+ apiFetchJson<QueueServerItem>(buildQueueUrl(`i/${itemId}`));
+
+export const getQueueItemIds = (
+ orderDir: 'asc' | 'desc' = 'desc',
+ scope: QueueQueryScope = {}
+): Promise<QueueItemIdsResult> =>
+ apiFetchJson<QueueItemIdsResult>(
+ buildQueueUrl(
+ `item_ids${buildQueryString({ order_dir: orderDir.toUpperCase(), origin_prefix: scope.originPrefix })}`
+ )
+ );
+
+/** Fetch full items for the given ids, preserving order. Mirrors legacy `items_by_ids`. */
+export const getQueueItemsByIds = (itemIds: number[]): Promise<QueueServerItem[]> => {
+ if (itemIds.length === 0) {
+ return Promise.resolve([]);
+ }
+
+ return apiFetchJson<QueueServerItem[]>(buildQueueUrl('items_by_ids'), {
+ body: JSON.stringify({ item_ids: itemIds }),
+ method: 'POST',
+ });
+};
+
+// --- Mutations -------------------------------------------------------------
+
+export const clearQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('clear'), { method: 'PUT' });
+
+export const pruneQueue = (): Promise<unknown> => apiFetchJson(buildQueueUrl('prune'), { method: 'PUT' });
+
+export const deleteQueueItem = (itemId: number): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl(`i/${itemId}`), { method: 'DELETE' });
+
+export const deleteQueueItems = async (itemIds: number[]): Promise<void> => {
+ await Promise.all(itemIds.map(deleteQueueItem));
+};
+
+export const cancelQueueItems = async (itemIds: number[]): Promise<void> => {
+ await Promise.all(itemIds.map(cancelQueueItem));
+};
+
+export const clearFailedQueueItems = async (scope: QueueQueryScope = {}): Promise<void> => {
+ const idsResult = await getQueueItemIds('desc', scope);
+ const items = await getQueueItemsByIds(idsResult.item_ids);
+ const failedItemIds = items.filter((item) => item.status === 'failed').map((item) => item.item_id);
+
+ await deleteQueueItems(failedItemIds);
+};
+
+export const clearScopedQueue = async (scope: QueueQueryScope = {}): Promise<void> => {
+ if (!scope.originPrefix) {
+ await clearQueue();
+ return;
+ }
+
+ const idsResult = await getQueueItemIds('desc', scope);
+ await deleteQueueItems(idsResult.item_ids);
+};
+
+export const cancelAllExceptCurrent = (): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('cancel_all_except_current'), { method: 'PUT' });
+
+export const cancelQueueItem = (itemId: number): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT' });
+
+export const cancelScopedQueueItems = async (
+ scope: QueueQueryScope = {},
+ currentItemId?: number | null
+): Promise<void> => {
+ const idsResult = await getQueueItemIds('desc', scope);
+ const items = await getQueueItemsByIds(idsResult.item_ids);
+ const cancellableItemIds = items
+ .filter((item) => item.item_id !== currentItemId && (item.status === 'pending' || item.status === 'in_progress'))
+ .map((item) => item.item_id);
+
+ await cancelQueueItems(cancellableItemIds);
+};
+
+export const cancelByBatchIds = (batchIds: string[]): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('cancel_by_batch_ids'), {
+ body: JSON.stringify({ batch_ids: batchIds }),
+ method: 'PUT',
+ });
+
+export const retryItemsById = (itemIds: number[]): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('retry_items_by_id'), {
+ body: JSON.stringify(itemIds),
+ method: 'PUT',
+ });
+
+export const pauseQueueProcessor = (): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('processor/pause'), { method: 'PUT' });
+
+export const resumeQueueProcessor = (): Promise<unknown> =>
+ apiFetchJson(buildQueueUrl('processor/resume'), { method: 'PUT' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.ts
new file mode 100644
index 0000000000..42ad65cb3b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/statusMeta.ts
@@ -0,0 +1,22 @@
+import type { BackendQueueItemStatus } from '@workbench/backend/events';
+
+/**
+ * Presentation metadata for each backend queue status: the human label, the
+ * Chakra `colorPalette` for badges, and the dot color used in list rows and the
+ * NOW & NEXT card. One table so status styling stays consistent everywhere.
+ */
+export interface QueueStatusMeta {
+ label: string;
+ colorPalette: string;
+ dotColor: string;
+}
+
+const STATUS_META: Record<BackendQueueItemStatus, QueueStatusMeta> = {
+ canceled: { colorPalette: 'orange', dotColor: 'orange.solid', label: 'Canceled' },
+ completed: { colorPalette: 'green', dotColor: 'green.solid', label: 'Completed' },
+ failed: { colorPalette: 'red', dotColor: 'red.solid', label: 'Failed' },
+ in_progress: { colorPalette: 'accent', dotColor: 'accent.solid', label: 'Generating' },
+ pending: { colorPalette: 'gray', dotColor: 'fg.muted', label: 'Pending' },
+};
+
+export const getStatusMeta = (status: BackendQueueItemStatus): QueueStatusMeta => STATUS_META[status];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts
new file mode 100644
index 0000000000..0965a48ef9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts
@@ -0,0 +1,32 @@
+import type { GenerateWidgetValues } from '@workbench/generation/types';
+
+import { parseQueueItemOrigin } from '@workbench/backend/events';
+import { useWorkbenchSelector } from '@workbench/WorkbenchContext';
+
+/**
+ * The full Generate settings snapshot for a server queue item, if this client
+ * submitted it. webv2 stamps the local submission id into each item's `origin`,
+ * so we decode it and look the snapshot up in local state. Present → "Use again"
+ * can recall the exact settings (model, steps, LoRAs, …); absent (item from
+ * another client, or a cleared snapshot) → only field_values are recoverable.
+ */
+export const useLocalGenerateValues = (origin?: string | null): GenerateWidgetValues | null =>
+ useWorkbenchSelector((snapshot) => {
+ const localId = parseQueueItemOrigin(origin);
+
+ if (!localId) {
+ return null;
+ }
+
+ for (const project of snapshot.state.projects) {
+ const localItem = project.queue.items.find((queueItem) => queueItem.id === localId);
+
+ if (localItem) {
+ const generate = (localItem.snapshot.widgetStates as Record<string, { values?: unknown }>).generate;
+
+ return (generate?.values as GenerateWidgetValues | undefined) ?? null;
+ }
+ }
+
+ return null;
+ });