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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(queue): stop endless enqueue retries and show waiting runs in the Queue panel (#10124)
Josh Corbett00f92afaa59f
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.pyindex 61116a6b42..74a6353c29 100644--- a/invokeai/app/services/shared/graph_validation.py+++ b/invokeai/app/services/shared/graph_validation.py@@ -242,6 +242,36 @@ def extract_collection_item_types(t: Any) -> set[Any]:return item_types+def _is_subtype(sub: Any, sup: Any) -> bool:+ """Whether every value of type form `sub` is a value of `sup`, for any form collector types resolve to.++ issubclass() raises TypeError for a union first argument and a parameterized-generic second argument; an+ escaped TypeError turns graph validation into a 500 instead of a validation error.+ """+ if sub == sup:+ return True+ sub_origin = get_origin(sub)+ if sub_origin in (Union, UnionType):+ return all(_is_subtype(arg, sup) for arg in get_args(sub))+ if sub_origin is Literal and len(get_args(sub)) > 1:+ # A Literal is the union of its values; check each, so `Literal["a", 1]` fits `str | int`.+ return all(_is_subtype(Literal[value], sup) for value in get_args(sub))+ if get_origin(sup) in (Union, UnionType):+ return any(_is_subtype(sub, arg) for arg in get_args(sup))+ if sub_origin is Literal:+ (value,) = get_args(sub)+ if get_origin(sup) is Literal:+ # Compare by equality, as pydantic does: it accepts `True` for `Literal[1]`.+ return value in get_args(sup)+ # As `_resolve_item_input_types` does, a value is of its own type: `Literal[True]` fits `int`.+ return _is_subtype(type(value), sup)+ try:+ return issubclass(sub, sup)+ except TypeError:+ # Parameterized generics and other non-class forms match only themselves.+ return False++def are_connection_types_compatible(from_type: Any, to_type: Any) -> bool:implementation = _get_facade_override("are_connection_types_compatible", are_connection_types_compatible)if implementation is not are_connection_types_compatible:@@ -1682,7 +1712,7 @@ class Graph(BaseModel):def _get_type_tree_root_types(self, input_types: set[Any]) -> list[Any]:type_tree = nx.DiGraph()type_tree.add_nodes_from(input_types)- type_tree.add_edges_from([e for e in itertools.permutations(input_types, 2) if issubclass(e[1], e[0])])+ type_tree.add_edges_from([e for e in itertools.permutations(input_types, 2) if _is_subtype(e[1], e[0])])type_degrees = type_tree.in_degree(type_tree.nodes)return [t[0] for t in type_degrees if t[1] == 0] # type: ignore@@ -1823,12 +1853,12 @@ class Graph(BaseModel):return "Collector output must connect to a collection input"# Read item types from the list branch: the first type argument of `Union[list[X], X]` or- # `Optional[list[X]]` is `list[X]` itself, which issubclass() rejects with a TypeError.+ # `Optional[list[X]]` is `list[X]` itself, not the item type.if input_root_type is not None:if not all(is_any(t)or any(- self._collector_item_matches(input_root_type, item_type)+ is_any(item_type) or _is_subtype(input_root_type, item_type)for item_type in extract_collection_item_types(t))for t in output_field_types@@ -1839,16 +1869,6 @@ class Graph(BaseModel):return None- @staticmethod- def _collector_item_matches(input_root_type: Any, item_type: Any) -> bool:- if is_any(item_type) or is_union_subtype(input_root_type, item_type):- return True- if not isinstance(input_root_type, type):- return False- # A union item type (e.g. `list[Union[Base, str]]`) matches a subclass of any of its members.- candidates = get_args(item_type) if get_origin(item_type) in (Union, UnionType) else (item_type,)- return any(isinstance(c, type) and issubclass(input_root_type, c) for c in candidates)-def _validate_downstream_collector_outputs(self,outputs: list[EdgeConnection],diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 544d234849..7a415f966c 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3963,6 +3963,27 @@"processorPausedDescription_other": "{{count}} items wait until you resume.","unavailableWhileDisconnected": "Not available while the server is disconnected.","reconnecting": "Reconnecting…",+ "localRuns": {+ "title": "Submitting",+ "untitled": "Untitled run",+ "cancel": "Cancel {{name}}",+ "errorLabel": "Why {{name}} is retrying",+ "loadFailed": "Couldn't load the runs waiting to be submitted.",+ "state": {+ "submitting": "Sending to the server…",+ "serverError": "Server error, retrying (attempt {{attempt, number}})",+ "unavailable": "Server busy or unavailable, retrying (attempt {{attempt, number}})",+ "unreachable": "Can't reach the server, retrying (attempt {{attempt, number}})",+ "error": "Couldn't submit, retrying (attempt {{attempt, number}})",+ "offline": "Offline, waiting for the connection…"+ },+ "announcement": {+ "serverError": "{{name}}: Server error, retrying",+ "unavailable": "{{name}}: Server busy or unavailable, retrying",+ "unreachable": "{{name}}: Can't reach the server, retrying",+ "error": "{{name}}: Couldn't submit, retrying"+ }+ },"itemNumber": "#{{id}}","loadingModel": "Loading {{model}}…","viewError": "View error",diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsxnew file mode 100644index 0000000000..374d5304ef--- /dev/null+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsx@@ -0,0 +1,164 @@+import type * as QueuePublicApi from '@features/queue/publicApi';+import type { Project } from '@workbench/projectContracts';+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';+import type { ComponentType } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { loadQueueWidgetImplementation } from '@features/queue/widget';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++import { QueueUiAdapterProvider } from './QueueUiAdapter';++let store: ReturnType<typeof createWorkbenchStore>;++vi.mock('@features/queue/publicApi', async (importOriginal) => ({+ ...(await importOriginal<typeof QueuePublicApi>()),+ getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),+ getQueueReadModelOptions: () => ({ queryFn: () => null, queryKey: ['queue'], staleTime: Number.POSITIVE_INFINITY }),+}));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));+vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: Project) => unknown, isEqual = shallowEqual) =>+ useExternalStoreSelector(+ store.subscribe,+ store.getSnapshot,+ (snapshot) => selector(snapshot.activeProject),+ isEqual+ ),+ useWorkbenchCommands: () => store.commands,+ useWorkbenchSelector: (selector: (snapshot: WorkbenchSnapshot) => unknown, isEqual = shallowEqual) =>+ useExternalStoreSelector(store.subscribe, store.getSnapshot, selector, isEqual),+}));++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackNS: 'translation',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const RUN_ID = 'local-run';+let projectId: string;+let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ accountLifecycle.activate('queue-ui-adapter');+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ projectId = project.id;+ // Queued long ago (restored from storage, say) and never accepted, so the widget lists it at once.+ project.queue = {+ items: [+ {+ cancellable: true,+ id: RUN_ID,+ snapshot: {+ presentation: { batchCount: 1, height: 512, positivePrompt: 'A lighthouse in fog', width: 512 },+ sourceId: 'generate',+ submittedAt: '2026-01-01T00:00:00.000Z',+ } as Project['queue']['items'][number]['snapshot'],+ status: 'pending',+ },+ ],+ };+ store = createWorkbenchStore(state);+ store.commands.queue.setConnectionStatus({ status: 'connected' });+ host = document.createElement('div');+ host.style.cssText = 'width:360px;height:600px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+});++const rowText = () =>+ host.querySelector('[role="list"][aria-label="Submitting"] > [role="listitem"]')?.textContent ?? null;++const recordServerError = (failureCount: number) =>+ act(() =>+ store.commands.queue.recordSubmissionRetry({+ projectId,+ queueItemId: RUN_ID,+ retry: {+ failedAt: Date.now(),+ failureCount,+ message: 'Internal Server Error',+ reason: 'server-error',+ serverErrorCount: failureCount,+ serverErrorSince: Date.now(),+ status: 500,+ },+ })+ );++it("lists the Workbench's unaccepted run, follows each recorded retry, and drops it once the backend accepts it", async () => {+ const { view: QueueWidgetView } = (await loadQueueWidgetImplementation()) as {+ view: ComponentType<{ region: 'right' }>;+ };+ const client = new QueryClient();+ client.setQueryData(['queue'], {+ current: null,+ items: [],+ next: null,+ scope: {},+ status: {+ processor: { isProcessing: false, isStarted: true },+ queue: {+ canceled: 0,+ completed: 0,+ failed: 0,+ inProgress: 0,+ pending: 0,+ queueId: 'default',+ total: 0,+ waiting: 0,+ },+ },+ });++ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={client}>+ <QueueUiAdapterProvider>+ <QueueWidgetView region="right" />+ </QueueUiAdapterProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );++ await expect.poll(rowText).toContain('A lighthouse in fog');+ expect(rowText()).toContain('Sending to the server…');++ await recordServerError(1);+ expect(rowText()).toContain('Server error, retrying (attempt 2)');++ // Only the retry changed: the run must still re-render with it.+ await recordServerError(2);+ expect(rowText()).toContain('Server error, retrying (attempt 3)');++ await act(() => store.commands.queue.markBackendSubmitted({ backendItemIds: [42], projectId, queueItemId: RUN_ID }));+ expect(rowText()).toBeNull();+ expect(host.textContent).not.toContain('Submitting');+});diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsxindex 7e618a2ce8..a78b0d0c9d 100644--- a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx@@ -1,7 +1,11 @@+import type { QueueItem } from '@features/queue/contracts';+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';+import { useAuthSession, useCapabilities } from '@features/identity';import { getModelLoads, subscribeModelLoads } from '@features/models';-import { getQueueItemAccess, QueueUiProvider, type QueueUiAdapter } from '@features/queue/react';-import { areArraysEqual } from '@platform/state/selectors';+import { getQueueItemSnapshotLabel } from '@features/queue/contracts';+import { getQueueItemAccess, QueueUiProvider, type QueueLocalRun, type QueueUiAdapter } from '@features/queue/react';+import { areArraysEqual, shallowEqual } from '@platform/state/selectors';import { isUnsubmittedQueueItem } from '@workbench/canvasStagingView';import { useWorkbenchPreferences } from '@workbench/settings/store';import { useNotify } from '@workbench/useNotify';@@ -12,6 +16,35 @@ import { lazy, useMemo, type ReactNode } from 'react';const importQueueItemActions = () => import('@workbench/queue-integration/QueueItemActions');const QueueItemActions = lazy(() => importQueueItemActions().then((module) => ({ default: module.QueueItemActions })));+const toQueueLocalRun = (projectId: string, item: QueueItem): QueueLocalRun => {+ const retry = item.submissionRetry;+ // Read defensively, as the snapshot readers are: a run restored from an older journal may lack parts of it.+ const submittedAt = Date.parse((item.snapshot as Partial<QueueItem['snapshot']> | undefined)?.submittedAt ?? '');++ return {+ id: item.id,+ label: getQueueItemSnapshotLabel(item),+ projectId,+ retry: retry ? { failureCount: retry.failureCount, message: retry.message, reason: retry.reason } : null,+ submittedAt: Number.isFinite(submittedAt) ? submittedAt : 0,+ };+};++const selectLocalRuns = (snapshot: WorkbenchSnapshot): QueueLocalRun[] =>+ snapshot.projects.flatMap((project) =>+ project.queue.items.filter(isUnsubmittedQueueItem).map((item) => toQueueLocalRun(project.id, item))+ );++/** Runs map to fresh objects on every Workbench change; equal fields keep the previous list and its consumers still. */+const areLocalRunsEqual = (left: QueueLocalRun[], right: QueueLocalRun[]): boolean =>+ left.length === right.length &&+ left.every((run, index) => {+ const { retry, ...fields } = run;+ const { retry: otherRetry, ...otherFields } = right[index]!;++ return shallowEqual(fields, otherFields) && shallowEqual(retry, otherRetry);+ });+/** Read by the queue's running row and status alone, so model loads re-render them rather than every queue consumer. */const loadingModel = {getLabel: (): string | null => getModelLoads()[0]?.label ?? null,@@ -32,15 +65,7 @@ export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) =>(snapshot) => snapshot.projects.map((project) => project.id),areArraysEqual);- const localUnsubmittedRuns = useWorkbenchSelector((snapshot) => {- const count = (items: readonly Parameters<typeof isUnsubmittedQueueItem>[0][]) =>- items.filter(isUnsubmittedQueueItem).length;-- return {- activeProject: count(snapshot.activeProject.queue.items),- allProjects: snapshot.projects.reduce((total, project) => total + count(project.queue.items), 0),- };- });+ const localRuns = useWorkbenchSelector(selectLocalRuns, areLocalRunsEqual);const adapter = useMemo<QueueUiAdapter>(() => {const viewer = {currentUserId: session.user?.user_id ?? null,@@ -57,11 +82,12 @@ export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) =>canManageProcessor: canManageModels,canManageItem: (item) => getQueueItemAccess(item, viewer).canManage,canViewItemDetails: (item) => getQueueItemAccess(item, viewer).canViewDetails,- cancelLocalUnsubmittedRuns: (projectId) => queue.cancelUnsubmitted(projectId ?? undefined),+ cancelLocalRun: (projectId, runId) => queue.cancel(projectId, runId),+ cancelLocalRuns: (projectId) => queue.cancelUnsubmitted(projectId ?? undefined),isConnected,isProjectOpen: (projectId) => openProjectIds.includes(projectId),loadingModel,- localUnsubmittedRuns,+ localRuns,notify,openQueue: () => openWorkbenchWidget('queue'),preloadItemActions: () => void importQueueItemActions(),@@ -74,7 +100,7 @@ export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) =>canManageAppConfig,canManageModels,isConnected,- localUnsubmittedRuns,+ localRuns,notify,openProjectIds,openWorkbenchWidget,diff --git a/invokeai/frontend/webv2/src/features/queue/README.md b/invokeai/frontend/webv2/src/features/queue/README.mdindex a3cd69f034..5ae0e4da6d 100644--- a/invokeai/frontend/webv2/src/features/queue/README.md+++ b/invokeai/frontend/webv2/src/features/queue/README.md@@ -8,6 +8,8 @@ Queue exposes board-independent active backend sessions, including preparation aRetry re-runs failed or canceled backend items under new ids; the run owning them reopens around the reruns so its captured destination receives their results. A rerun no open run adopts reaches the Gallery, or the current Canvas of a tab with its project open. Canvas reruns are staged once across every tab and browser of the account through a delivery claim the server keeps per queue item (`POST queue/{id}/i/{item_id}/delivery`): a claimant claims, stages, then confirms; a claim neither confirmed nor released lapses after two minutes. A reopened run claims its reruns as `run:<project, run>` once its tab holds the run, renews them while it lasts, and gives back what it did not stage when the tab lets the run go, so a reload restores the same claimant and a run never stages a rerun another tab staged first. A tab the browser freezes stops renewing; another tab then stages the rerun at its own current bbox. A tab staging a rerun no run adopted claims as itself, after waiting for any tab of the browser that still tracks the run, and asks again while another claimant holds the rerun. A server without the endpoint lets every tab stage.+A run the backend has not accepted keeps resubmitting, and records its latest failed attempt on the run (`QueueItem.submissionRetry`, cleared once the backend accepts the run or the run ends). Each failure is reconciled before the run submits again, and the run waits from that failure by its own consecutive failures, whatever their reason: 1 s, doubling to at most 15 s. A reconcile never shortens that wait. When the connection comes back after a disconnect, each run this tab is waiting to submit then goes within a random share of 2 s, or sooner if its own wait ends first, so a restarting server and every tab do not get them all at once. The record names why the attempt failed: `unavailable` for 408, 429, 502, 503 and 504; `unreachable` when the request got no answer (`fetch` rejected or timed out); `error` for any other failure that is not a 5xx, such as an answer that could not be read, which may still have committed the batch; all three retry without limit. Any other 5xx is a `server-error` and counts toward a budget: three consecutive ones, the last at least 10 seconds after the first (five attempts at this pace), fail the run with the server's message, unless the reconcile that follows the last finds the backend accepted it after all. Any other failure starts that count over, and so does an attempt starting more than 5 minutes after the run's previous failure, measured from the attempt's start so a slow answer cannot reset its own count; minutes, because a hidden tab's timers may fire only once a minute. The recorded message keeps at most its first 500 characters, ending with an ellipsis when cut, since a 5xx without a JSON body is the whole response page. The whole record travels with the run in the queue-run journal, written again after every failed attempt (so the pace bounds those writes), and a reload or a restarted runtime continues the budget and the remaining wait; restoring bounds the message again and drops a record it cannot read, such as one with a reason it does not know, but keeps the run. Both are judged from the recorded failure times; a clock set back before them restarts the 10 seconds without resetting the count and waits at most one delay.+`submitUtilityGraph` (`@features/queue/utility`) returns once the backend accepts the graph; its `settled` watch ends on the first of: a terminal status event for its origin; a re-read of its accepted items that finds a terminal status or answers 404 (`removed`), triggered by `queue_cleared`, a reconnect after a disconnect, `queue_items_canceled` naming an accepted id, or the periodic reconcile read, which re-arms while the item stays open; or an abort of its signal (`aborted`), which stops watching and leaves the backend item alone.Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.@@ -16,7 +18,7 @@ Gallery owns coalesced socket-completion invalidation for the account across tab`ui/queueMenuActions.tsx` is the one queue action model: the top bar's button and menu, the widget header and its menu, and shortcuts (`requestQueueAction` in `@features/queue/reveal`, taken by the queue's always-mounted host once the read model has loaded) all call an action's `trigger`, never its runner. Its policy: cancelling the running item never asks, since Retry brings it back; cancelling all, cancelling all but the current item, and clearing failed, finished or all items always confirm, naming the scope and how many items they reach, with a way out that never reads "Cancel". Results report the same scope and counts. Pause and resume are one toggle that states what waits on the processor.-Counts and scope follow what the action does for the viewer (`QueueUiAdapter.viewer`). A member's cancels count their own unfinished items; an administrator's count everyone's, since their cancel and clear reach every user. Across all projects the server counts every user's history, so a member's clears confirm without a count. Each scope (one project, all projects, all projects and users, all of a member's projects) has its own whole sentence in the catalog (`translateScoped`), never a fragment stitched into one. Cancel-all also cancels this tab's runs the backend has not accepted (`localUnsubmittedRuns`), so it stays available offline while there are any.+Counts and scope follow what the action does for the viewer (`QueueUiAdapter.viewer`). A member's cancels count their own unfinished items; an administrator's count everyone's, since their cancel and clear reach every user. Across all projects the server counts every user's history, so a member's clears confirm without a count. Each scope (one project, all projects, all projects and users, all of a member's projects) has its own whole sentence in the catalog (`translateScoped`), never a fragment stitched into one. Cancel-all also cancels this tab's runs the backend has not accepted (`QueueUiAdapter.localRuns`), so it stays available offline while there are any. The widget lists those runs in its Submitting section above the current batch, under All and Active and within the queue scope setting, and counts them in those tabs (`useShownLocalRuns`). A run shows once its enqueue has failed, while the tab is offline, or once it has gone a second unaccepted, so an ordinary Invoke never flashes a row. Each says whether it is being sent, retried after a server error, waiting on a busy or unreachable server (with the attempt it is on), or held while the tab is offline, and cancels on its own without asking, as any single cancel does. Cancel-all counts every unaccepted run in scope, shown or not. The section's rows load with the first such run; if they cannot load, the section offers Retry and the rest of the widget keeps working.The top bar's button, the status chip and the queue widget read one activity (`core/queueActivity.ts`) from the same open work: the viewer's own pending and running items within the queue scope setting (`useScopedQueueOpenWork`). The top bar and chip count the larger of that and the active project's runs, whose progress they show (`useQueueChromeActivity` in `workbench/queue-integration`), so neither reads idle while the widget, under the same scope, shows work waiting or running.diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsindex 2522427940..b5c810f795 100644--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -7,6 +7,7 @@ export type {QueueItem,QueueRunErrorCode,QueueState,+ QueueSubmissionRetry,QueueSubmissionSnapshot,RunRecord,} from './core/historyTypes';diff --git a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.tsindex 66bcbd5046..96ee3fa318 100644--- a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts@@ -43,6 +43,28 @@ export interface QueueSubmissionSnapshot {submittedAt: string;}+/** The latest failed attempt to submit a run the backend has not accepted yet; cleared once the backend accepts it. */+export interface QueueSubmissionRetry {+ /**+ * 'server-error': a 5xx other than 502/503/504, counted toward the failure budget. 'unavailable': 408, 429, 502,+ * 503 or 504. 'unreachable': the request never got an answer (network failure or timeout). 'error': anything else,+ * such as an answer that could not be read; the batch may have been accepted, so the run is reconciled and retried.+ */+ reason: 'error' | 'server-error' | 'unavailable' | 'unreachable';+ /** Consecutive failed submissions so far, whatever their reason; at least 1. Paces the next attempt. */+ failureCount: number;+ /** Consecutive server-error answers so far; 0 when the latest failure was another reason. */+ serverErrorCount: number;+ /** Epoch ms of the first of those consecutive server errors; null when serverErrorCount is 0. */+ serverErrorSince: number | null;+ /** HTTP status of the latest failure; null without a response. */+ status: number | null;+ /** Message of the latest failure, as shown to the user. */+ message: string;+ /** Epoch ms of the latest failure. */+ failedAt: number;+}+export interface QueueItem {id: string;status: QueueHistoryItemStatus;@@ -58,6 +80,8 @@ export interface QueueItem {retriedBackendItemIds?: number[];backendBatchId?: string;error?: string;+ /** Set while the backend has not accepted the run and its latest submission failed. */+ submissionRetry?: QueueSubmissionRetry;resultImages?: QueueResultImage[];/** Videos already routed to the Gallery; a repeat routing pass must not reselect them. */resultVideoNames?: string[];diff --git a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.tsindex 6e005c186f..36eb33e301 100644--- a/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/submissionRules.ts@@ -37,3 +37,22 @@ export const isBackendSubmittableSourceId = (sourceId: QueueSourceId): boolean =*/export const shouldSubmitPendingQueueItem = (queueItem: QueueItem): boolean =>queueItem.status === 'pending' && isBackendSubmittableSourceId(queueItem.snapshot.sourceId);++/**+ * The longest failure message a submission retry keeps. A 5xx without a JSON body is the whole response (an HTML page,+ * a traceback), and the retry is written to state and recovery storage on every attempt. The final failure shows the+ * message as the run's error, so it keeps the leading text rather than one line.+ */+const MAX_SUBMISSION_RETRY_MESSAGE_LENGTH = 500;++/**+ * The message cut to MAX_SUBMISSION_RETRY_MESSAGE_LENGTH, ending with an ellipsis when cut. The cut never keeps half+ * of a surrogate pair.+ */+export const boundSubmissionRetryMessage = (message: string): string => {+ if (message.length <= MAX_SUBMISSION_RETRY_MESSAGE_LENGTH) {+ return message;+ }+ const kept = message.slice(0, MAX_SUBMISSION_RETRY_MESSAGE_LENGTH - 1);+ return `${/[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept}…`;+};diff --git a/invokeai/frontend/webv2/src/features/queue/index.ts b/invokeai/frontend/webv2/src/features/queue/index.tsindex 06a36f990b..6d899d62c3 100644--- a/invokeai/frontend/webv2/src/features/queue/index.ts+++ b/invokeai/frontend/webv2/src/features/queue/index.ts@@ -19,6 +19,7 @@ export type {QueueHistoryItemStatus,QueueItem,QueueState,+ QueueSubmissionRetry,QueueSubmissionSnapshot,RunRecord,} from './core/historyTypes';@@ -40,6 +41,7 @@ export {} from './core/historySummary';export {BACKEND_SUBMITTABLE_SOURCE_IDS,+ boundSubmissionRetryMessage,getQueueSourceResultSelection,isBackendSubmittableSourceId,shouldSubmitPendingQueueItem,diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.tsindex 4a39d85cc0..1bec99c61b 100644--- a/invokeai/frontend/webv2/src/features/queue/react.ts+++ b/invokeai/frontend/webv2/src/features/queue/react.ts@@ -1,6 +1,6 @@/** React-facing Queue read models, kept separate from widget registration. */export type { QueueItemProgress } from './core/types';-export { QueueUiProvider, type QueueUiAdapter } from './ui/QueueUiContext';+export { QueueUiProvider, type QueueLocalRun, type QueueUiAdapter } from './ui/QueueUiContext';export {useActiveProgressTarget,useActiveProgressTargets,diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 214da84eb1..b2d09addd4 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -14,7 +14,7 @@ import { activeProgressTargetStore } from '@features/queue/data/activeProgressTaimport { buildQueueItemOrigin } from '@features/queue/data/events';import { ApiError } from '@platform/transport/http';import { createInitialWorkbenchState, type WorkbenchAction, workbenchReducer } from '@workbench/workbenchState.testing';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {createQueueItemBackendSubmission,@@ -95,6 +95,7 @@ const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBackconst createTestCommands = (overrides: Partial<QueueHistoryCommands> = {}): QueueHistoryCommands => ({markBackendCancelled: vi.fn(),markBackendSubmitted: vi.fn(),+ recordSubmissionRetry: vi.fn(),setCancellationPending: vi.fn(),setLocalRecoveryState: vi.fn(),recordError: vi.fn(),@@ -117,6 +118,99 @@ const createTestJournal = (overrides: Partial<QueueRunJournalPort> = {}): QueueR...overrides,});+/** A journal kept in memory, holding what it records as storage would: serialized. */+const createMemoryJournal = (): QueueRunJournalPort => {+ const entries = new Map<string, { item: unknown; projectId: string; queueItemId: string }>();+ return {+ listForProject: (projectId) =>+ Promise.resolve({+ entries: [...entries.values()].filter((entry) => entry.projectId === projectId),+ kind: 'available',+ }),+ record: (projectId, item) => {+ entries.set(JSON.stringify([projectId, item.id]), {+ item: JSON.parse(JSON.stringify(item)) as unknown,+ projectId,+ queueItemId: item.id,+ });+ return Promise.resolve({ kind: 'stored' });+ },+ settle: (projectId, queueItemId) => {+ entries.delete(JSON.stringify([projectId, queueItemId]));+ return Promise.resolve({ kind: 'removed' });+ },+ };+};++/** Queue history over the real Workbench reducer, its active project holding one pending run. */+const createWorkbenchQueueHistory = () => {+ let state = createInitialWorkbenchState();+ const projectId = state.activeProjectId;+ const { canvas } = state.projects.find((project) => project.id === projectId)!;+ const pendingItem = createPendingQueueItem();+ const queueItem: WorkbenchQueueItem = {+ ...pendingItem,+ snapshot: {+ ...pendingItem.snapshot,+ canvas: {+ document: { bbox: { ...canvas.document.bbox }, height: canvas.document.height, width: canvas.document.width },+ documentRevision: canvas.documentRevision,+ },+ },+ };+ const setItems = (items: WorkbenchQueueItem[]): void => {+ state = {+ ...state,+ projects: state.projects.map((project) =>+ project.id === projectId ? { ...project, queue: { items } } : project+ ),+ };+ };+ setItems([queueItem]);+ const listeners = new Set<() => void>();+ const dispatch = (action: WorkbenchAction): void => {+ state = workbenchReducer(state, action);+ listeners.forEach((listener) => listener());+ };+ let connectionStatus: BackendConnectionStatus = 'connected';+ const commands = createTestCommands({+ setConnectionStatus: ({ status }) => {+ connectionStatus = status;+ },+ markBackendSubmitted: (payload) => dispatch({ ...payload, type: 'markQueueItemBackendSubmitted' }),+ setCancellationPending: (payload) => dispatch({ ...payload, type: 'setQueueItemCancellationPending' }),+ recordSubmissionRetry: (payload) => dispatch({ ...payload, type: 'recordQueueItemSubmissionRetry' }),+ restoreFromJournal: (payload) => dispatch({ ...payload, type: 'restoreQueueItemsFromJournal' }),+ setLocalRecoveryState: (payload) => dispatch({ ...payload, type: 'setQueueItemLocalRecoveryState' }),+ setStatus: vi.fn<QueueHistoryCommands['setStatus']>((payload) =>+ dispatch({ ...payload, type: 'setQueueItemStatus' })+ ),+ });+ return {+ /** The backend item a successful enqueue of the run creates. */+ acceptedItem: {+ batchId: 'backend-batch',+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, projectId),+ status: 'pending' as const,+ },+ getRun: () =>+ state.projects.find((project) => project.id === projectId)?.queue.items.find((item) => item.id === queueItem.id),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus, isHydrated: true, projects: state.projects }),+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ /** The user cancels the run, as the queue's cancel action does. */+ cancel: () => dispatch({ notice: null, projectId, queueItemId: queueItem.id, type: 'cancelQueueItem' }),+ /** A reload: the page forgets its runs, and only what the journal kept comes back. */+ reload: () => setItems([]),+ };+};+/** Run locks that no other tab holds, around the given acquire. */const createTestLocks = (acquire: QueueRunLockPort['acquire'],@@ -143,6 +237,12 @@ const runtimeServices = {},};+// A failing assertion must not leave fake timers or a stubbed Math.random to the next test.+afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});+describe('queue runtime', () => {it('turns a malformed legacy submission into a failed request instead of throwing', () => {const queueItem = createPendingQueueItem();@@ -390,6 +490,7 @@ describe('queue runtime', () => {queueItem.backendItemIds = backendItemIds;queueItem.status = 'running';},+ recordSubmissionRetry: vi.fn(),setCancellationPending: ({ pending }) => {queueItem.cancellationPending = pending || undefined;},@@ -552,7 +653,6 @@ describe('queue runtime', () => {expect(commands.refreshBoardDestinations).toHaveBeenCalledTimes(refreshes);expect(commands.refreshBackendData).not.toHaveBeenCalled();await runtime.dispose();- vi.useRealTimers();});@@ -594,7 +694,6 @@ describe('queue runtime', () => {expect(commands.setStatus).not.toHaveBeenCalled();}await runtime.dispose();- vi.useRealTimers();});it('fails a run whose queued request is invalid with a code its notice can translate, without enqueueing', async () => {@@ -627,7 +726,6 @@ describe('queue runtime', () => {status: 'failed',});await runtime.dispose();- vi.useRealTimers();});it('fails a run the server queue accepted none of with a code its notice can translate', async () => {@@ -1352,7 +1450,6 @@ describe('queue runtime', () => {expect(settle).toHaveBeenCalledTimes(2);await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));await runtime.dispose();- vi.useRealTimers();});it('restores a durable cancellation intent and retries cancellation before settling it', async () => {@@ -1740,128 +1837,105 @@ describe('queue runtime', () => {it('fails a run whose enqueue keeps returning a 500 instead of retrying forever', async () => {vi.useFakeTimers();- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const commands = createTestCommands();+ const workbench = createWorkbenchQueueHistory();const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('graph validation crashed', 500));const runtime = createQueueRuntime({...runtimeServices,backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),- },+ history: workbench.history,journal: createTestJournal(),});runtime.start();await vi.advanceTimersByTimeAsync(20_000);+ expect(workbench.getRun()).toMatchObject({ error: 'graph validation crashed', status: 'failed' });+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');// The notice words the give-up itself and quotes the server's error as the reason.- expect(commands.setStatus).toHaveBeenCalledWith(- expect.objectContaining({- error: 'graph validation crashed',- errorCode: 'server-error',- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- })+ expect(workbench.history.commands.setStatus).toHaveBeenCalledWith(+ expect.objectContaining({ error: 'graph validation crashed', errorCode: 'server-error', status: 'failed' }));- const attempts = enqueueGenerate.mock.calls.length;- expect(attempts).toBeGreaterThanOrEqual(3);+ // At 0, 1, 3, 7 and 15 s: the fifth 500 is the first one at least 10 s after the first.+ expect(enqueueGenerate).toHaveBeenCalledTimes(5);await vi.advanceTimersByTimeAsync(30_000);- expect(enqueueGenerate).toHaveBeenCalledTimes(attempts);+ expect(enqueueGenerate).toHaveBeenCalledTimes(5);await runtime.dispose();- vi.useRealTimers();});- it('forgets earlier 500s once the run settles, so a later run of the item starts fresh', async () => {+ it('continues the 500 budget of a run restored after a reload instead of starting it over', async () => {vi.useFakeTimers();- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const listeners = new Set<() => void>();- const notify = () => listeners.forEach((listener) => listener());- const commands = createTestCommands({- setStatus: vi.fn(({ status }) => {- queueItem.status = status;- notify();- }),- });+ const workbench = createWorkbenchQueueHistory();+ const journal = createMemoryJournal();const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('graph validation crashed', 500));- const runtime = createQueueRuntime({- ...runtimeServices,- backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: (listener) => {- listeners.add(listener);- return () => listeners.delete(listener);- },+ const backend = createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) });+ const createRuntime = () =>+ createQueueRuntime({ ...runtimeServices, backend, history: workbench.history, journal });+ const startedAt = Date.now();++ const beforeReload = createRuntime();+ beforeReload.start();+ while (enqueueGenerate.mock.calls.length < 2) {+ await vi.advanceTimersByTimeAsync(10);+ }+ await beforeReload.dispose();+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: {+ failureCount: 2,+ reason: 'server-error',+ serverErrorCount: 2,+ serverErrorSince: startedAt,+ status: 500,},- journal: createTestJournal(),});- runtime.start();- await vi.advanceTimersByTimeAsync(1_000);- expect(enqueueGenerate.mock.calls.length).toBeGreaterThanOrEqual(2);-- // The user cancels the run before the 500s are given up on, which settles it.- queueItem.status = 'cancelled';- notify();+ // The page is gone past the 500 window; the next load knows the run only from the journal.await vi.advanceTimersByTimeAsync(15_000);+ workbench.reload();+ const afterReload = createRuntime();+ afterReload.start();+ await vi.advanceTimersByTimeAsync(5_000);- // Running the item again must not inherit the earlier run's 500 count and window.- enqueueGenerate.mockClear();- queueItem.status = 'pending';- notify();- await vi.advanceTimersByTimeAsync(1_000);- expect(enqueueGenerate).toHaveBeenCalled();- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));- await runtime.dispose();- vi.useRealTimers();+ expect(workbench.getRun()).toMatchObject({ error: 'graph validation crashed', status: 'failed' });+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);+ await afterReload.dispose();});- it('recovers from 500s that stop within a second instead of failing the run', async () => {+ it('recovers from 500s that stop within a few seconds instead of failing the run', async () => {vi.useFakeTimers();- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const commands = createTestCommands();+ const workbench = createWorkbenchQueueHistory();const startedAt = Date.now();const enqueueGenerate = vi.fn(() =>- Date.now() - startedAt < 1_000+ Date.now() - startedAt < 2_500? Promise.reject(new ApiError('transient internal error', 500)): Promise.resolve({ batchId: 'backend-batch', enqueued: 1, itemIds: [88], requested: 1 }));const runtime = createQueueRuntime({...runtimeServices,- backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),- },+ backend: createTestBackend({+ enqueueGenerate,+ getItem: vi.fn().mockResolvedValue(workbench.acceptedItem),+ listItems: vi.fn().mockResolvedValue([]),+ }),+ history: workbench.history,journal: createTestJournal(),});runtime.start();await vi.advanceTimersByTimeAsync(10_000);- expect(enqueueGenerate.mock.calls.length).toBeGreaterThan(3);- expect(commands.markBackendSubmitted).toHaveBeenCalledWith(- expect.objectContaining({ backendItemIds: [88], projectId: project.id, queueItemId: queueItem.id })- );- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ // 500s at 0 and 1 s; accepted at 3 s.+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);+ expect(workbench.getRun()).toMatchObject({ backendItemIds: [88], status: 'running' });+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');await runtime.dispose();- vi.useRealTimers();});it('adopts a run the server accepted before its last 500 instead of failing it', async () => {vi.useFakeTimers();- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const commands = createTestCommands();+ const workbench = createWorkbenchQueueHistory();const startedAt = Date.now();let committed = false;// Once the 500s have lasted long enough to give up, the server commits the next enqueue but still answers 500.@@ -1869,21 +1943,15 @@ describe('queue runtime', () => {committed = Date.now() - startedAt >= 10_000;return Promise.reject(new ApiError('response failed after commit', 500));});- const acceptedItem = {- batchId: 'backend-batch',- id: 88,- origin: buildQueueItemOrigin(queueItem.id, project.id),- status: 'pending',- };- const listItems = vi.fn().mockImplementation(() => Promise.resolve(committed ? [acceptedItem] : []));+ const listItems = vi.fn(() => Promise.resolve(committed ? [workbench.acceptedItem] : []));const runtime = createQueueRuntime({...runtimeServices,- backend: createTestBackend({ enqueueGenerate, listItems }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),- },+ backend: createTestBackend({+ enqueueGenerate,+ getItem: vi.fn().mockResolvedValue(workbench.acceptedItem),+ listItems,+ }),+ history: workbench.history,journal: createTestJournal(),});@@ -1891,68 +1959,472 @@ describe('queue runtime', () => {await vi.advanceTimersByTimeAsync(20_000);expect(committed).toBe(true);- expect(commands.markBackendSubmitted).toHaveBeenCalledWith(- expect.objectContaining({ backendItemIds: [88], projectId: project.id, queueItemId: queueItem.id })+ expect(workbench.getRun()).toMatchObject({ backendItemIds: [88], status: 'running' });+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');+ await runtime.dispose();+ });++ it('keeps retrying an unavailable server without counting it toward the 500 budget', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const startedAt = Date.now();+ // One 500, then the server is unavailable for longer than the 500 window lasts.+ const enqueueGenerate = vi.fn(() =>+ enqueueGenerate.mock.calls.length === 1+ ? Promise.reject(new ApiError('graph validation crashed', 500))+ : Date.now() - startedAt < 20_000+ ? Promise.reject(new ApiError('unavailable', 503))+ : Promise.resolve({ batchId: 'backend-batch', enqueued: 1, itemIds: [88], requested: 1 }));- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ enqueueGenerate,+ getItem: vi.fn().mockResolvedValue(workbench.acceptedItem),+ listItems: vi.fn().mockResolvedValue([]),+ }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.advanceTimersByTimeAsync(14_000);+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: {+ failureCount: 4,+ message: 'unavailable',+ reason: 'unavailable',+ serverErrorCount: 0,+ serverErrorSince: null,+ status: 503,+ },+ });++ // 503 at 15 s, accepted at 30 s.+ await vi.advanceTimersByTimeAsync(20_000);+ expect(workbench.getRun()).toMatchObject({ backendItemIds: [88], status: 'running' });+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');await runtime.dispose();- vi.useRealTimers();});- it('keeps retrying an enqueue that returns 503 while the server is unavailable', async () => {- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const commands = createTestCommands();+ it('paces a run through a long outage by its own failures, whatever the reconciles in between find', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('unavailable', 503));+ const listItems = vi.fn().mockResolvedValue([]);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();++ // Waits of 1, 2, 4 and 8 s, then 15 s: attempts at 0, 1, 3, 7, 15, 30, 45, 60, 75, 90 and 105 s.+ await vi.advanceTimersByTimeAsync(119_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(11);+ expect(workbench.getRun()).toMatchObject({ status: 'pending', submissionRetry: { failureCount: 11 } });+ await runtime.dispose();+ });++ it.each([+ { disconnectedMs: 500, name: 'a random share of two seconds', random: 0.25, waitMs: 500 },+ { disconnectedMs: 2_000, name: 'no longer than the rest of its own wait', random: 0.99, waitMs: 1_000 },+ ])(+ 'lets a waiting run submit within $name when the connection comes back',+ async ({ disconnectedMs, random, waitMs }) => {+ vi.useFakeTimers();+ vi.spyOn(Math, 'random').mockReturnValue(random);+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('unavailable', 503));+ let setConnection: (status: BackendConnectionStatus) => void = () => undefined;+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ enqueueGenerate,+ listItems: vi.fn().mockResolvedValue([]),+ onConnectionChange: (listener) => {+ setConnection = listener;+ listener('connected');+ return vi.fn();+ },+ }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();+ // Attempts at 0, 1 and 3 s; the next waits until 7 s.+ await vi.advanceTimersByTimeAsync(4_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);++ setConnection('disconnected');+ await vi.advanceTimersByTimeAsync(disconnectedMs);+ setConnection('connected');+ await vi.advanceTimersByTimeAsync(waitMs - 10);+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(20);+ expect(enqueueGenerate).toHaveBeenCalledTimes(4);++ // The clock then steps back a minute. That attempt failed too, so the run waits 8 s from it again, and the+ // failures after it, recorded before the reconnect by the clock, keep their pace.+ vi.setSystemTime(Date.now() - 60_000);+ await vi.advanceTimersByTimeAsync(7_900);+ expect(enqueueGenerate).toHaveBeenCalledTimes(4);+ await vi.advanceTimersByTimeAsync(200);+ expect(enqueueGenerate).toHaveBeenCalledTimes(5);+ await vi.advanceTimersByTimeAsync(14_800);+ expect(enqueueGenerate).toHaveBeenCalledTimes(5);+ await vi.advanceTimersByTimeAsync(200);+ expect(enqueueGenerate).toHaveBeenCalledTimes(6);+ await runtime.dispose();+ }+ );++ it.each([+ { clockShiftMs: 0, name: 'the rest of its wait' },+ { clockShiftMs: -60_000, name: 'no longer than its delay when the clock was set back' },+ ])('waits after a reload for $name before submitting again', async ({ clockShiftMs }) => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const journal = createMemoryJournal();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('unavailable', 503));+ const backend = createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) });+ const createRuntime = () =>+ createQueueRuntime({ ...runtimeServices, backend, history: workbench.history, journal });++ const beforeReload = createRuntime();+ beforeReload.start();+ // Attempts at 0, 1 and 3 s; the next waits 4 s, until 7 s.+ await vi.advanceTimersByTimeAsync(4_000);+ await beforeReload.dispose();+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);++ vi.setSystemTime(Date.now() + clockShiftMs);+ workbench.reload();+ const afterReload = createRuntime();+ afterReload.start();+ // 3 s left at the same clock; with the clock set back, the wait is capped at the 4 s delay.+ const waitMs = clockShiftMs === 0 ? 3_000 : 4_000;+ await vi.advanceTimersByTimeAsync(waitMs - 100);+ expect(enqueueGenerate).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(200);+ expect(enqueueGenerate).toHaveBeenCalledTimes(4);+ await afterReload.dispose();+ });++ it.each([+ { error: new ApiError('request timeout', 408), reason: 'unavailable', status: 408 },+ { error: new ApiError('too many requests', 429), reason: 'unavailable', status: 429 },+ { error: new ApiError('bad gateway', 502), reason: 'unavailable', status: 502 },+ { error: new ApiError('gateway timeout', 504), reason: 'unavailable', status: 504 },+ // What `fetch` rejects with when the request gets no answer, or is aborted or times out.+ { error: new TypeError('Failed to fetch'), reason: 'unreachable', status: null },+ { error: new DOMException('The operation timed out.', 'TimeoutError'), reason: 'unreachable', status: null },+ // An answer arrived but could not be read; the batch may have been accepted, so the run is reconciled and retried.+ { error: new SyntaxError('Unexpected token < in JSON'), reason: 'error', status: null },+ { error: new Error('Invalid queue enqueue response'), reason: 'error', status: null },+ ])('keeps retrying, paced, while an enqueue fails with $error.message', async ({ error, reason, status }) => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(error);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();++ // Attempts at 0, 1, 3, 7, 15, 30 and 45 s, well past the 500 window, and the run still waits for the next.+ await vi.advanceTimersByTimeAsync(59_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(7);+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: { failureCount: 7, message: error.message, reason, serverErrorCount: 0, status },+ });+ await runtime.dispose();+ });++ it('stops retrying a run cancelled while it waits to submit again', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('unavailable', 503));+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();+ // Attempts at 0 and 1 s; the next waits until 3 s.+ await vi.advanceTimersByTimeAsync(2_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(2);++ workbench.cancel();+ await vi.advanceTimersByTimeAsync(30_000);++ expect(enqueueGenerate).toHaveBeenCalledTimes(2);+ expect(workbench.getRun()).toMatchObject({ status: 'cancelled' });+ // The cancellation settled without reaching the backend.+ expect(workbench.getRun()?.cancellationPending).toBeUndefined();+ expect(workbench.getRun()?.error).toBeUndefined();+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');+ await runtime.dispose();+ });++ it('neither revives nor fails a run cancelled while its enqueue is in flight when a late 500 answers it', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ let answer: (error: unknown) => void = () => undefined;const enqueueGenerate = vi.fn()- .mockRejectedValueOnce(new ApiError('unavailable', 503))- .mockRejectedValueOnce(new ApiError('unavailable', 503))- .mockRejectedValueOnce(new ApiError('unavailable', 503))- .mockResolvedValue({ batchId: 'backend-batch', enqueued: 1, itemIds: [88], requested: 1 });+ .mockRejectedValueOnce(new ApiError('graph validation crashed', 500))+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ answer = reject;+ })+ )+ .mockRejectedValue(new ApiError('graph validation crashed', 500));const runtime = createQueueRuntime({...runtimeServices,backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),- },+ history: workbench.history,journal: createTestJournal(),});runtime.start();+ // A 500 at 0 s; the second attempt, at 1 s, is still waiting for its answer.+ await vi.advanceTimersByTimeAsync(1_500);+ expect(enqueueGenerate).toHaveBeenCalledTimes(2);- await vi.waitFor(() => expect(commands.markBackendSubmitted).toHaveBeenCalled(), { timeout: 4_000 });- expect(enqueueGenerate).toHaveBeenCalledTimes(4);- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ workbench.cancel();+ answer(new ApiError('graph validation crashed', 500));+ await vi.advanceTimersByTimeAsync(30_000);++ expect(enqueueGenerate).toHaveBeenCalledTimes(2);+ expect(workbench.getRun()).toMatchObject({ status: 'cancelled' });+ expect(workbench.getRun()?.error).toBeUndefined();+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');+ expect(workbench.history.commands.setStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'failed' })+ );await runtime.dispose();});- it('keeps reconciling after three consecutive lost enqueue responses', async () => {- const queueItem = createPendingQueueItem();- const project = { id: 'project-1', queue: { items: [queueItem] } };- const commands = createTestCommands();+ it('needs three fresh 500s over ten seconds after an unavailable answer breaks the streak', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const startedAt = Date.now();+ // 500s at 0 and 1 s, a 503 at 3 s, then 500s from 7 s on.+ const enqueueGenerate = vi.fn(() =>+ Promise.reject(+ enqueueGenerate.mock.calls.length === 3+ ? new ApiError('unavailable', 503)+ : new ApiError('graph validation crashed', 500)+ )+ );+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();++ // Five 500s by 15 s would have spent an unbroken budget; this streak has two, since 7 s.+ await vi.advanceTimersByTimeAsync(20_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(5);+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: { reason: 'server-error', serverErrorCount: 2, serverErrorSince: startedAt + 7_000 },+ });++ // The third, at 30 s, is 23 s after the streak began.+ await vi.advanceTimersByTimeAsync(15_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(6);+ expect(workbench.getRun()).toMatchObject({ error: 'graph validation crashed', status: 'failed' });+ await runtime.dispose();+ });++ it('restarts the 500 window at now, keeping the count, when the clock is set back before the streak began', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('graph validation crashed', 500));+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();+ await vi.advanceTimersByTimeAsync(500);+ expect(enqueueGenerate).toHaveBeenCalledTimes(1);++ // The streak now began a minute ahead of the clock. The wait, due 0.5 s later, finds its due time a minute away+ // and waits its 1 s delay once more instead.+ vi.setSystemTime(Date.now() - 60_000);+ const steppedBackAt = Date.now();+ await vi.advanceTimersByTimeAsync(1_400);+ expect(enqueueGenerate).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(200);+ expect(enqueueGenerate).toHaveBeenCalledTimes(2);+ const retry = workbench.getRun()?.submissionRetry;+ expect(retry).toMatchObject({ reason: 'server-error', serverErrorCount: 2 });+ expect(retry?.serverErrorSince).toBe(retry?.failedAt);+ expect(retry!.failedAt - steppedBackAt).toBeLessThan(1_600);++ // Neither failed at once nor stalled: the third 500 fails the run once ten seconds have passed since the restart.+ await vi.advanceTimersByTimeAsync(5_000);+ expect(workbench.getRun()).toMatchObject({ status: 'pending', submissionRetry: { serverErrorCount: 3 } });+ await vi.advanceTimersByTimeAsync(20_000);+ expect(workbench.getRun()).toMatchObject({ error: 'graph validation crashed', status: 'failed' });+ await runtime.dispose();+ });++ it.each([+ { accepted: false, name: 'fails it with the server error' },+ { accepted: true, name: 'adopts what the server accepted' },+ ])('reconciles a run reloaded after its last 500 and $name, without submitting it again', async ({ accepted }) => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const journal = createMemoryJournal();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('graph validation crashed', 500));+ // The server answers the final reconcile only after the reload.+ let reloaded = false;+ const listItems = vi.fn(() => Promise.resolve(reloaded && accepted ? [workbench.acceptedItem] : []));+ const backend = createTestBackend({+ enqueueGenerate,+ getItem: vi.fn().mockResolvedValue(workbench.acceptedItem),+ listItems,+ });+ const createRuntime = () =>+ createQueueRuntime({ ...runtimeServices, backend, history: workbench.history, journal });++ const beforeReload = createRuntime();+ beforeReload.start();+ // The fifth 500, at 15 s, spends the budget; the page goes before its final reconcile.+ while (enqueueGenerate.mock.calls.length < 5) {+ await vi.advanceTimersByTimeAsync(10);+ }+ await vi.advanceTimersByTimeAsync(0);+ const reconcilesBefore = listItems.mock.calls.length;+ await beforeReload.dispose();+ expect(workbench.getRun()).toMatchObject({ status: 'pending', submissionRetry: { serverErrorCount: 5 } });++ reloaded = true;+ workbench.reload();+ const afterReload = createRuntime();+ afterReload.start();+ await vi.advanceTimersByTimeAsync(30_000);++ expect(enqueueGenerate).toHaveBeenCalledTimes(5);+ expect(listItems.mock.calls.length).toBeGreaterThan(reconcilesBefore);+ expect(workbench.getRun()).toMatchObject(+ accepted ? { backendItemIds: [88], status: 'running' } : { error: 'graph validation crashed', status: 'failed' }+ );+ expect(workbench.getRun()).not.toHaveProperty('submissionRetry');+ await afterReload.dispose();+ });++ it('starts a new 500 streak for a run last failed more than five minutes before its next attempt', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const journal = createMemoryJournal();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError('graph validation crashed', 500));+ const backend = createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) });+ const createRuntime = () =>+ createQueueRuntime({ ...runtimeServices, backend, history: workbench.history, journal });++ const beforeReload = createRuntime();+ beforeReload.start();+ while (enqueueGenerate.mock.calls.length < 2) {+ await vi.advanceTimersByTimeAsync(10);+ }+ await beforeReload.dispose();+ expect(workbench.getRun()).toMatchObject({ submissionRetry: { failureCount: 2, serverErrorCount: 2 } });++ // The page comes back a day later, and the server answers with one more 500.+ await vi.advanceTimersByTimeAsync(24 * 60 * 60_000);+ workbench.reload();+ const afterReload = createRuntime();+ const reloadedAt = Date.now();+ afterReload.start();+ while (enqueueGenerate.mock.calls.length < 3) {+ await vi.advanceTimersByTimeAsync(10);+ }++ // Without the restart, three 500s spread over a day would have failed the run at once.+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: { failureCount: 3, serverErrorCount: 1 },+ });+ expect(workbench.getRun()?.submissionRetry?.serverErrorSince).toBeGreaterThanOrEqual(reloadedAt);+ await afterReload.dispose();+ });++ it('keeps the 500 streak of a run whose answer took longer than five minutes to come', async () => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const startedAt = Date.now();+ const slowServerError = () =>+ new Promise((_resolve, reject) => {+ setTimeout(() => reject(new ApiError('graph validation crashed', 500)), 6 * 60_000);+ });const enqueueGenerate = vi.fn()- .mockRejectedValueOnce(new Error('response lost 1'))- .mockRejectedValueOnce(new Error('response lost 2'))- .mockRejectedValueOnce(new Error('response lost 3'))- .mockResolvedValue({ batchId: 'backend-batch', enqueued: 1, itemIds: [88], requested: 1 });+ .mockRejectedValueOnce(new ApiError('graph validation crashed', 500))+ .mockImplementation(slowServerError);const runtime = createQueueRuntime({...runtimeServices,backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),- history: {- commands,- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),- },+ history: workbench.history,journal: createTestJournal(),});runtime.start();+ // The second attempt starts at 1 s and its 500 arrives six minutes later.+ await vi.advanceTimersByTimeAsync(6 * 60_000 + 2_000);- await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(4), { timeout: 4_000 });- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ expect(enqueueGenerate).toHaveBeenCalledTimes(2);+ expect(workbench.getRun()).toMatchObject({+ status: 'pending',+ submissionRetry: { failureCount: 2, serverErrorCount: 2, serverErrorSince: startedAt },+ });+ await runtime.dispose();+ });++ it.each([+ {+ name: 'a long error page',+ page: `<html><body><h1>503 Service Unavailable</h1>${'<p>trace</p>\n'.repeat(1_000)}</body></html>`,+ kept: `<html><body><h1>503 Service Unavailable</h1>${'<p>trace</p>\n'.repeat(1_000)}`.slice(0, 499),+ },+ // The cut would fall inside the emoji; it drops the emoji rather than keep half of it.+ { name: 'a cut through an emoji', page: `${'x'.repeat(498)}😀${'y'.repeat(100)}`, kept: 'x'.repeat(498) },+ ])('keeps the start of $name as the message of a failed submission', async ({ kept, page }) => {+ vi.useFakeTimers();+ const workbench = createWorkbenchQueueHistory();+ const enqueueGenerate = vi.fn().mockRejectedValue(new ApiError(page, 503));+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: workbench.history,+ journal: createTestJournal(),+ });++ runtime.start();+ await vi.advanceTimersByTimeAsync(500);++ expect(workbench.getRun()?.submissionRetry?.message).toBe(`${kept}…`);await runtime.dispose();});@@ -2090,7 +2562,6 @@ describe('queue runtime', () => {expect(enqueueGenerate).toHaveBeenCalledTimes(1);expect(queueItem.cancellationPending).toBeUndefined();await runtime.dispose();- vi.useRealTimers();});it('adopts a partially accepted enqueue instead of abandoning its backend items', async () => {@@ -2657,6 +3128,7 @@ describe('queue runtime video board routing', () => {queueItem.backendItemIds = backendItemIds;queueItem.status = 'running';},+ recordSubmissionRetry: vi.fn(),setCancellationPending: ({ pending }) => {queueItem.cancellationPending = pending || undefined;},diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex 9c87a0ec59..81208bb910 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -1,4 +1,4 @@-import type { QueueItem, QueueRunErrorCode } from '@features/queue/core/historyTypes';+import type { QueueItem, QueueRunErrorCode, QueueSubmissionRetry } from '@features/queue/core/historyTypes';import type {QueueBackendPort,QueueEnqueueGenerateRequest,@@ -21,7 +21,11 @@ import {MAX_QUEUE_BATCH_ITEMS,type QueueWorkflowSeed,} from '@features/queue/core/promptBatch';-import { QUEUE_SOURCE_RESULT_NODE_IDS, shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';+import {+ boundSubmissionRetryMessage,+ QUEUE_SOURCE_RESULT_NODE_IDS,+ shouldSubmitPendingQueueItem,+} from '@features/queue/core/submissionRules';import {buildQueueItemOrigin,isTerminalBackendStatus,@@ -96,6 +100,8 @@ export interface QueueHistoryCommands {projectId: string;queueItemId: string;}): void;+ /** Record the latest failed submission of a run the backend has not accepted; acceptance or an ending clears it. */+ recordSubmissionRetry(payload: { projectId: string; queueItemId: string; retry: QueueSubmissionRetry }): void;setCancellationPending(payload: { pending: boolean; projectId: string; queueItemId: string }): void;setLocalRecoveryState(payload: {projectId: string;@@ -417,22 +423,106 @@ const getJournalSignature = (item: QueueItem): string =>item.backendItemIds,item.completedBackendItemIds,item.cancelledBackendItemIds,+ // The failure budget and the wait before the next attempt survive a reload, so every failed attempt writes the run+ // once more; the retry pace bounds those writes.+ item.submissionRetry,]);/*** A 5xx answer to an enqueue is usually caused by the request itself (e.g. a graph that* crashes server-side validation), so retrying the same submission forever never succeeds.- * Gateway and availability errors (502/503/504) stay transient and keep retrying.- * A run only gives up after at least MAX_SERVER_ERROR_SUBMISSIONS 500s spread over at least+ * Gateway and availability errors (502/503/504, and 408/429) stay transient and keep retrying.+ * A run only gives up after at least MAX_SERVER_ERROR_SUBMISSIONS consecutive 500s spread over at least* MIN_SERVER_ERROR_WINDOW_MS, so a short-lived internal error can still recover.* After the last allowed 500 the run is reconciled once more, and only fails if the- * backend queue really has nothing for it.+ * backend queue really has nothing for it. The count lives on the run (`submissionRetry`), so a reload continues it.*/const MAX_SERVER_ERROR_SUBMISSIONS = 3;const MIN_SERVER_ERROR_WINDOW_MS = 10_000;-const TRANSIENT_SERVER_STATUSES = [502, 503, 504];-const isDeterministicServerError = (error: unknown): boolean =>- error instanceof ApiError && error.status >= 500 && !TRANSIENT_SERVER_STATUSES.includes(error.status);+/**+ * An attempt starting this long after the run's previous failure begins a new 500 streak, so 500s from an earlier+ * session do not spend the budget of a later one. Minutes rather than a few retry delays: a hidden tab's timers can+ * fire only about once a minute, and that must not reset a streak.+ */+const SERVER_ERROR_STREAK_GAP_MS = 5 * 60_000;+const UNAVAILABLE_STATUSES = [408, 429, 502, 503, 504];+/**+ * A run waits before each resubmission, 1 s after its first failed submission and doubling up to 15 s, whatever the+ * reason; its 500 budget is then spent after five attempts over about 15 s. When the connection comes back, each run+ * waiting then submits within a random RECONNECT_SPREAD_MS instead (never later than its own wait), so a restarting+ * server, and every tab, does not get all of them at once.+ *+ * Clock rules, for the wall clock the recorded times use:+ * - A wait runs from the recorded failure (`failedAt`), so a reload keeps it.+ * - A wait is never longer than the run's delay: a failure recorded ahead of the clock (set back since) waits the+ * delay from now (`getSubmissionWaitMs`), and a due time the clock has since moved more than a delay away is fixed+ * again (`getRemainingSubmissionWaitMs`). A clock set back delays a run once by at most its delay.+ * - A 500 streak whose start reads after now restarts its window at now and keeps its count, so the run neither waits+ * for the clock to catch up nor fails at once; a clock set forward can only shorten the window, and the run still+ * takes MAX_SERVER_ERROR_SUBMISSIONS 500s to fail (`getSubmissionRetry`). A clock set back never starts a new streak+ * by SERVER_ERROR_STREAK_GAP_MS; one set forward past it does, which only gives the run a fresh budget.+ * - Whether the budget is spent is judged from the recorded times alone (`isSubmissionRetryExhausted`).+ */+const SUBMISSION_RETRY_BASE_MS = 1_000;+const SUBMISSION_RETRY_MAX_MS = 15_000;+const RECONNECT_SPREAD_MS = 2_000;+const getSubmissionRetryDelayMs = (failureCount: number): number =>+ Math.min(SUBMISSION_RETRY_BASE_MS * 2 ** Math.max(failureCount - 1, 0), SUBMISSION_RETRY_MAX_MS);+const getSubmissionWaitMs = (retry: QueueSubmissionRetry, now: number): number => {+ const delayMs = getSubmissionRetryDelayMs(retry.failureCount);+ return Math.min(Math.max(retry.failedAt + delayMs - now, 0), delayMs);+};+const isDeterministicServerError = (error: unknown): error is ApiError =>+ error instanceof ApiError && error.status >= 500 && !UNAVAILABLE_STATUSES.includes(error.status);+/** `fetch` rejects with a TypeError when the request gets no answer, and a DOMException when it is aborted. */+const isTransportFailure = (error: unknown): boolean =>+ error instanceof TypeError ||+ (error instanceof DOMException && ['AbortError', 'NetworkError', 'TimeoutError'].includes(error.name));++const getRetryReason = (error: unknown): Exclude<QueueSubmissionRetry['reason'], 'server-error'> => {+ if (error instanceof ApiError) {+ return UNAVAILABLE_STATUSES.includes(error.status) ? 'unavailable' : 'error';+ }+ return isTransportFailure(error) ? 'unreachable' : 'error';+};++/**+ * The retry a failed submission leaves, continuing the run's consecutive server errors unless the attempt started+ * more than SERVER_ERROR_STREAK_GAP_MS after the previous failure. The gap is measured from the attempt's start, so+ * a slow answer cannot reset its own streak.+ */+const getSubmissionRetry = (+ error: unknown,+ previous: QueueSubmissionRetry | undefined,+ { attemptStartedAt, now }: { attemptStartedAt: number; now: number }+): QueueSubmissionRetry => {+ const base = {+ failedAt: now,+ failureCount: (previous?.failureCount ?? 0) + 1,+ message: boundSubmissionRetryMessage(toErrorMessage(error)),+ status: error instanceof ApiError ? error.status : null,+ };+ if (!isDeterministicServerError(error)) {+ return { ...base, reason: getRetryReason(error), serverErrorCount: 0, serverErrorSince: null };+ }+ const streak =+ previous?.reason === 'server-error' && attemptStartedAt - previous.failedAt <= SERVER_ERROR_STREAK_GAP_MS+ ? previous+ : undefined;+ const since = streak?.serverErrorSince ?? null;+ return {+ ...base,+ reason: 'server-error',+ serverErrorCount: (streak?.serverErrorCount ?? 0) + 1,+ serverErrorSince: since !== null && since <= now ? since : now,+ };+};++const isSubmissionRetryExhausted = (retry: QueueSubmissionRetry): boolean =>+ retry.reason === 'server-error' &&+ retry.serverErrorSince !== null &&+ retry.serverErrorCount >= MAX_SERVER_ERROR_SUBMISSIONS &&+ retry.failedAt - retry.serverErrorSince >= MIN_SERVER_ERROR_WINDOW_MS;const NO_CANCEL_REQUESTS: QueueCancelRequestPort = { wasRequestedHere: () => false };@@ -513,9 +603,15 @@ export const createQueueRuntime = ({const submissionOperations = new Map<string, Promise<unknown>>();const cancelRequestedRunKeys = new Set<string>();let reconcileRetryDelayMs = 100;- const serverErrorCounts = new Map<string, { count: number; firstAt: number }>();- const exhaustedServerErrors = new Map<string, string>();let retryTimer: ReturnType<typeof setTimeout> | undefined;+ /** Wakes the runtime when the earliest waiting run may submit again. */+ let submissionTimer: { dueAt: number; timer: ReturnType<typeof setTimeout> } | undefined;+ /**+ * When each waiting run may submit again, by the failure it waits on; fixed when that failure is first seen and+ * shortened on reconnect. See the clock rules at SUBMISSION_RETRY_BASE_MS.+ */+ const submissionDueTimes = new Map<string, { dueAt: number; failedAt: number }>();+ let sawDisconnect = false;let renewTimer: ReturnType<typeof setInterval> | undefined;let hasInitialized = false;let isInitializing = false;@@ -824,8 +920,7 @@ export const createQueueRuntime = ({reconcileRetryRunKeys.delete(key);cancelRequestedRunKeys.delete(key);reportedCancelFailures.delete(key);- serverErrorCounts.delete(key);- exhaustedServerErrors.delete(key);+ submissionDueTimes.delete(key);invalidateAttempt(projectId, queueItemId);pendingJournalRecords.delete(key);const ownershipEpoch = ownershipEpochs.get(key) ?? 0;@@ -1875,6 +1970,7 @@ export const createQueueRuntime = ({return;}+ const attemptStartedAt = Date.now();const request =submission.kind === 'generate'? coordinator.submitGenerate(currentQueueItem.id, submission.request)@@ -1887,7 +1983,6 @@ export const createQueueRuntime = ({await request.then(async ({ batchId, enqueued, itemIds, requested }) => {- serverErrorCounts.delete(runKey);if (!isAttemptCurrent(attempt)) {return;}@@ -1958,21 +2053,18 @@ export const createQueueRuntime = ({});return;}- if (isDeterministicServerError(error)) {- const now = Date.now();- const previous = serverErrorCounts.get(runKey);- const failures = (previous?.count ?? 0) + 1;- const firstAt = previous?.firstAt ?? now;- if (failures >= MAX_SERVER_ERROR_SUBMISSIONS && now - firstAt >= MIN_SERVER_ERROR_WINDOW_MS) {- // The server may have accepted the batch before answering 500, so reconcile before failing the run.- serverErrorCounts.delete(runKey);- exhaustedServerErrors.set(runKey, toErrorMessage(error));- } else {- serverErrorCounts.set(runKey, { count: failures, firstAt });- }- } else {- serverErrorCounts.delete(runKey);- }+ // Even a run past its server-error budget is reconciled first: the server may have accepted the batch before+ // answering 500.+ const failedTarget = getRouteTarget(history, currentQueueItem.id);+ commands.recordSubmissionRetry({+ projectId: project.id,+ queueItemId: currentQueueItem.id,+ retry: getSubmissionRetry(+ error,+ failedTarget?.project.id === project.id ? failedTarget.queueItem?.submissionRetry : undefined,+ { attemptStartedAt, now: Date.now() }+ ),+ });startedRunKeys.delete(runKey);reconcileRetryRunKeys.add(runKey);scheduleRetry();@@ -2032,8 +2124,7 @@ export const createQueueRuntime = ({pendingReconcileRunKeys.delete(key);reconcileRetryRunKeys.delete(key);reportedCancelFailures.delete(key);- serverErrorCounts.delete(key);- exhaustedServerErrors.delete(key);+ submissionDueTimes.delete(key);pendingJournalRecords.delete(key);releaseRunOwnershipAfterJournal(tracked.projectId, tracked.queueItemId);}@@ -2112,29 +2203,89 @@ export const createQueueRuntime = ({});};+ const getRemainingSubmissionWaitMs = (key: string, retry: QueueSubmissionRetry, now: number): number => {+ let due = submissionDueTimes.get(key);+ if (!due || due.failedAt !== retry.failedAt || due.dueAt - now > getSubmissionRetryDelayMs(retry.failureCount)) {+ due = { dueAt: now + getSubmissionWaitMs(retry, now), failedAt: retry.failedAt };+ submissionDueTimes.set(key, due);+ }+ return Math.max(due.dueAt - now, 0);+ };++ /** Each waiting run's remaining wait becomes a random share of RECONNECT_SPREAD_MS, never longer than it was. */+ const spreadSubmissionWaits = (): void => {+ const now = Date.now();+ for (const project of history.getSnapshot().projects) {+ for (const item of project.queue.items) {+ const key = getRunKey(project.id, item.id);+ if (item.status !== 'pending' || !item.submissionRetry || !trackedRuns.has(key)) {+ continue;+ }+ const waitMs = Math.min(+ getRemainingSubmissionWaitMs(key, item.submissionRetry, now),+ Math.random() * RECONNECT_SPREAD_MS+ );+ submissionDueTimes.set(key, { dueAt: now + waitMs, failedAt: item.submissionRetry.failedAt });+ }+ }+ };++ const scheduleSubmissionWake = (waitMs: number): void => {+ const dueAt = Date.now() + waitMs;+ if (submissionTimer && submissionTimer.dueAt <= dueAt) {+ return;+ }+ if (submissionTimer) {+ clearTimeout(submissionTimer.timer);+ }+ submissionTimer = {+ dueAt,+ timer: setTimeout(() => {+ submissionTimer = undefined;+ if (isActive()) {+ synchronize();+ }+ }, waitMs),+ };+ };+const processQueueItems = (): void => {if (!hasInitialized || !isActive() || history.getSnapshot().connectionStatus !== 'connected' || isReconciling) {return;}+ const now = Date.now();+ let nextWaitMs: number | undefined;for (const project of history.getSnapshot().projects) {if (!loadedProjectIds.has(project.id)) {continue;}for (const queueItem of project.queue.items) {const runKey = getRunKey(project.id, queueItem.id);+ // A run waiting out its retry backoff is reconciled before it is submitted again, whatever else changes.if (shouldSubmitPendingQueueItem(queueItem) &&trackedRuns.has(runKey) &&!preparingRunKeys.has(runKey) &&!pendingReconcileRunKeys.has(runKey) &&+ !reconcileRetryRunKeys.has(runKey) &&!startedRunKeys.has(runKey)) {+ const retry = queueItem.submissionRetry;+ const waitMs = retry ? getRemainingSubmissionWaitMs(runKey, retry, now) : 0;+ if (waitMs > 0) {+ nextWaitMs = Math.min(nextWaitMs ?? waitMs, waitMs);+ continue;+ }+ submissionDueTimes.delete(runKey);startedRunKeys.add(runKey);void submitQueueItem(project, queueItem, beginAttempt(project.id, queueItem.id));}}}+ if (nextWaitMs !== undefined) {+ scheduleSubmissionWake(nextWaitMs);+ }};const reconcile = (): void => {@@ -2261,8 +2412,6 @@ export const createQueueRuntime = ({const cancelRequested = cancelRequestedRunKeys.has(runKey);reconcileRetryRunKeys.delete(runKey);const outcome = outcomes.get(queueItem.id);- const exhaustedServerError = exhaustedServerErrors.get(runKey);- exhaustedServerErrors.delete(runKey);if ((outcome?.kind === 'adopted' || outcome?.kind === 'resumed') && outcome.missingBackendItemIds?.length) {commands.recordError({@@ -2288,9 +2437,9 @@ export const createQueueRuntime = ({switch (outcome?.kind) {case 'enqueue':- if (exhaustedServerError !== undefined) {+ if (currentQueueItem.submissionRetry && isSubmissionRetryExhausted(currentQueueItem.submissionRetry)) {commands.setStatus({- error: exhaustedServerError,+ error: currentQueueItem.submissionRetry.message,errorCode: 'server-error',projectId: project.id,queueItemId: currentQueueItem.id,@@ -2537,6 +2686,13 @@ export const createQueueRuntime = ({}commands.setConnectionStatus({ error, status });+ if (status === 'disconnected') {+ sawDisconnect = true;+ } else if (status === 'connected' && sawDisconnect) {+ // The server is likely back: the runs this tab is waiting to submit go soon, spread out.+ sawDisconnect = false;+ spreadSubmissionWaits();+ }if (status === 'connected') {for (const runKey of reconcileRetryRunKeys) {reconcileRetryRunKeys.delete(runKey);@@ -2560,6 +2716,10 @@ export const createQueueRuntime = ({clearTimeout(retryTimer);retryTimer = undefined;}+ if (submissionTimer) {+ clearTimeout(submissionTimer.timer);+ submissionTimer = undefined;+ }for (const detach of detachers.splice(0)) {detach();@@ -2604,8 +2764,7 @@ export const createQueueRuntime = ({fallbackAckOperations.clear();reconcileRetryRunKeys.clear();pendingReconcileRunKeys.clear();- serverErrorCounts.clear();- exhaustedServerErrors.clear();+ submissionDueTimes.clear();trackedRuns.clear();activeAttempts.clear();ownershipEpochs.clear();diff --git a/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsxnew file mode 100644index 0000000000..46f738192d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsx@@ -0,0 +1,364 @@+/* eslint-disable react-perf/jsx-no-new-object-as-prop */+import type { QueueReadModel } from '@features/queue/core/types';++import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@features/queue/publicApi', () => ({+ getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),+ getQueueReadModelOptions: () => ({ queryFn: () => null, queryKey: ['queue'], staleTime: Number.POSITIVE_INFINITY }),+ queueCommands: {},+}));++import { createTestLocalRun, createTestQueueUiAdapter } from './queueUiAdapter.testing';+import { QueueUiProvider, type QueueLocalRun, type QueueUiAdapter } from './QueueUiContext';+import { QueueWidgetView } from './QueueWidgetView';++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackNS: 'translation',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++// The server holds one queued item and four finished ones; nothing it holds is listed, so only local rows show.+const serverModel: QueueReadModel = {+ current: null,+ items: [],+ next: null,+ scope: {},+ status: {+ processor: { isProcessing: false, isStarted: true },+ queue: {+ canceled: 1,+ completed: 2,+ failed: 1,+ inProgress: 0,+ pending: 1,+ queueId: 'default',+ total: 5,+ waiting: 0,+ },+ },+};++let host: HTMLDivElement;+let root: Root;+let client: QueryClient;++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width:360px;height:600px;';+ document.body.append(host);+ root = createRoot(host);+ client = new QueryClient();+ client.setQueryData(['queue'], serverModel);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++/** `listed` defaults to every run in scope: the test runs are old, so none waits out the reveal delay. */+const render = async (overrides: Partial<QueueUiAdapter>, listed?: number) => {+ const adapter = createTestQueueUiAdapter({ activeProjectId: 'project-1', ...overrides });++ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={client}>+ <QueueUiProvider adapter={adapter}>+ <QueueWidgetView region="right" />+ </QueueUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ // The rows load lazily with the first run; wait for the ones the widget lists.+ await expect+ .poll(() => rows().length)+ .toBe(+ listed ??+ adapter.localRuns.filter((run) => adapter.queueJobsScope === 'all' || run.projectId === adapter.activeProjectId)+ .length+ );+};++const section = () => host.querySelector<HTMLElement>('[role="list"][aria-label="Submitting"]');+const rows = () => [...(section()?.querySelectorAll<HTMLElement>(':scope > [role="listitem"]') ?? [])];+const rowFor = (title: string) => rows().find((row) => row.textContent?.includes(title))!;+const cancelFor = (title: string) =>+ rowFor(title).querySelector<HTMLButtonElement>(`button[aria-label="Cancel ${title}"]`)!;+const tab = (label: string) =>+ [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) => element.textContent?.startsWith(label))!;++describe('runs this tab is still submitting', () => {+ it('lists each run with why it still waits and which attempt comes next', async () => {+ await render({+ localRuns: [+ createTestLocalRun({ id: 'a', label: 'Fresh run' }),+ createTestLocalRun({+ id: 'b',+ label: 'Broken graph',+ retry: { failureCount: 7, message: 'Internal Server Error', reason: 'server-error' },+ }),+ createTestLocalRun({+ id: 'c',+ label: 'Busy server',+ retry: { failureCount: 1, message: 'Service Unavailable', reason: 'unavailable' },+ }),+ createTestLocalRun({+ id: 'd',+ label: 'Lost network',+ retry: { failureCount: 1234, message: 'Failed to fetch', reason: 'unreachable' },+ }),+ createTestLocalRun({+ id: 'e',+ label: 'Unreadable answer',+ retry: { failureCount: 2, message: 'Unexpected end of JSON input', reason: 'error' },+ }),+ ],+ });++ expect(rowFor('Fresh run').textContent).toContain('Sending to the server…');+ expect(rowFor('Broken graph').textContent).toContain('Server error, retrying (attempt 8)');+ expect(rowFor('Broken graph').textContent).toContain('Internal Server Error');+ expect(rowFor('Busy server').textContent).toContain('Server busy or unavailable, retrying (attempt 2)');+ expect(rowFor('Lost network').textContent).toContain("Can't reach the server, retrying (attempt 1,235)");+ expect(rowFor('Unreadable answer').textContent).toContain("Couldn't submit, retrying (attempt 3)");+ expect(rowFor('Unreadable answer').textContent).not.toContain("Can't reach the server");+ });++ it('announces why a run retries when that starts or its reason changes, not on every further attempt', async () => {+ const retrying = (failureCount: number, reason: NonNullable<QueueLocalRun['retry']>['reason']) =>+ createTestLocalRun({ label: 'Broken graph', retry: { failureCount, message: 'Bad answer', reason } });+ await render({ localRuns: [createTestLocalRun({ label: 'Broken graph' })] });+ // The region exists before there is news: one inserted along with its text is not announced.+ const region = host.querySelector<HTMLElement>('[role="status"][aria-live="polite"]')!;+ const lines = () => [...region.children].map((line) => line.textContent);+ let changeCount = 0;+ const changes = new MutationObserver((records) => {+ changeCount += records.length;+ });+ changes.observe(region, { characterData: true, childList: true, subtree: true });+ const takeChanges = () => {+ const count = changeCount + changes.takeRecords().length;+ changeCount = 0;+ return count;+ };++ expect(lines()).toEqual([]);++ await render({ localRuns: [retrying(1, 'unreachable')] });+ expect(lines()).toEqual(["Broken graph: Can't reach the server, retrying"]);+ expect(takeChanges()).toBeGreaterThan(0);++ // Another attempt failing the same way changes the row's attempt number, but leaves the region as it was.+ await render({ localRuns: [retrying(2, 'unreachable')] });+ expect(rowFor('Broken graph').textContent).toContain('(attempt 3)');+ expect(takeChanges()).toBe(0);++ await render({ localRuns: [retrying(3, 'server-error')] });+ expect(lines()).toEqual(['Broken graph: Server error, retrying']);+ expect(takeChanges()).toBeGreaterThan(0);++ // Switching to a filter that hides the section is no news either, and the region keeps announcing under it.+ await act(() => tab('Done').click());+ expect(takeChanges()).toBe(0);++ await render({ localRuns: [retrying(4, 'unavailable')] }, 0);+ expect(region.isConnected).toBe(true);+ expect(lines()).toEqual(['Broken graph: Server busy or unavailable, retrying']);+ expect(takeChanges()).toBeGreaterThan(0);++ await act(() => tab('All').click());+ expect(takeChanges()).toBe(0);+ changes.disconnect();+ });++ it('waits for the connection while offline, whatever the last failure was', async () => {+ await render({+ isConnected: false,+ localRuns: [+ createTestLocalRun({+ label: 'Queued offline',+ retry: { failureCount: 2, message: 'Failed to fetch', reason: 'unreachable' },+ }),+ ],+ });++ expect(rowFor('Queued offline').textContent).toContain('Offline, waiting for the connection…');+ expect(rowFor('Queued offline').textContent).not.toContain("Can't reach the server");+ });++ it("shows a long failure's first line, and the whole of it in a bounded area once the row is expanded", async () => {+ const message = `Internal Server Error\n${'Traceback line\n'.repeat(60)}`;+ await render({+ localRuns: [+ createTestLocalRun({ label: 'Broken graph', retry: { failureCount: 1, message, reason: 'server-error' } }),+ ],+ });+ const primary = rowFor('Broken graph').querySelector<HTMLButtonElement>('[data-list-primary]')!;++ expect(primary.getAttribute('aria-expanded')).toBe('false');+ expect(rowFor('Broken graph').textContent).not.toContain('Traceback');++ await act(() => primary.click());++ const detail = rowFor('Broken graph').querySelector<HTMLElement>('[role="region"]')!;+ expect(primary.getAttribute('aria-expanded')).toBe('true');+ expect(detail.getAttribute('aria-label')).toBe('Why Broken graph is retrying');+ expect(detail.textContent).toBe(message.trim());+ // Sixty lines would be far taller; the detail scrolls instead of pushing the queue down.+ expect(detail.getBoundingClientRect().height).toBeLessThanOrEqual(128);+ expect(detail.scrollHeight).toBeGreaterThan(detail.clientHeight);+ });++ it('holds back a run whose first enqueue may still land, and shows it once that outlasts a second', async () => {+ await render({ localRuns: [createTestLocalRun({ label: 'Just queued', submittedAt: Date.now() - 200 })] }, 0);++ expect(host.textContent).not.toContain('Submitting');+ expect(tab('All').textContent).toBe('All5');++ await expect.poll(() => rows().length, { timeout: 3000 }).toBe(1);+ expect(tab('All').textContent).toBe('All6');+ });++ it("keeps the reveal timer within setTimeout's range when the clock moved back since the run was queued", async () => {+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');+ try {+ await render(+ { localRuns: [createTestLocalRun({ label: 'From the future', submittedAt: Date.now() + 2 ** 32 })] },+ 0+ );+ await new Promise((resolve) => {+ setTimeout(resolve, 100);+ });++ // An out-of-range delay would fire at once and re-arm in a tight loop.+ const delays = setTimeoutSpy.mock.calls.map(([, delay]) => delay ?? 0);+ expect(delays.every((delay) => delay <= 2 ** 31 - 1)).toBe(true);+ expect(delays.filter((delay) => delay === 1000)).toHaveLength(1);+ } finally {+ setTimeoutSpy.mockRestore();+ }+ });++ it('shows a run at once after a failure or while offline, however recently it was queued', async () => {+ const now = Date.now();+ await render(+ {+ localRuns: [+ createTestLocalRun({+ id: 'a',+ label: 'Failed once',+ retry: { failureCount: 1, message: 'Bad Gateway', reason: 'unavailable' },+ submittedAt: now,+ }),+ createTestLocalRun({ id: 'b', label: 'Just queued', submittedAt: now }),+ ],+ },+ 1+ );+ expect(rowFor('Failed once')).toBeDefined();++ await render({ isConnected: false, localRuns: [createTestLocalRun({ label: 'Just queued', submittedAt: now })] });+ expect(rowFor('Just queued').textContent).toContain('Offline, waiting for the connection…');+ });++ it('cancels the run it belongs to without asking, and hands focus on rather than dropping it', async () => {+ let localRuns: QueueLocalRun[] = [+ createTestLocalRun({ id: 'a', label: 'First run' }),+ createTestLocalRun({ id: 'b', label: 'Second run', projectId: 'project-2' }),+ ];+ const cancelLocalRun = vi.fn((projectId: string, runId: string) => {+ localRuns = localRuns.filter((run) => run.projectId !== projectId || run.id !== runId);+ });+ const rerender = () => render({ cancelLocalRun, localRuns });+ await rerender();++ await act(() => cancelFor('First run').click());+ await rerender();++ expect(cancelLocalRun).toHaveBeenCalledExactlyOnceWith('project-1', 'a');+ expect(host.querySelector('[role="alertdialog"]')).toBeNull();+ expect(rows()).toHaveLength(1);+ expect(document.activeElement).toBe(cancelFor('Second run'));++ await act(() => cancelFor('Second run').click());+ await rerender();++ expect(cancelLocalRun).toHaveBeenLastCalledWith('project-2', 'b');+ expect(section()).toBeNull();+ expect(document.activeElement).toBe(tab('All'));+ });++ it('hands focus to the previous Cancel when the last of several rows is canceled', async () => {+ let localRuns: QueueLocalRun[] = [+ createTestLocalRun({ id: 'a', label: 'First run' }),+ createTestLocalRun({ id: 'b', label: 'Second run' }),+ createTestLocalRun({ id: 'c', label: 'Third run' }),+ ];+ const cancelLocalRun = vi.fn((_projectId: string, runId: string) => {+ localRuns = localRuns.filter((run) => run.id !== runId);+ });+ await render({ cancelLocalRun, localRuns });++ await act(() => cancelFor('Third run').click());+ await render({ cancelLocalRun, localRuns });++ expect(cancelLocalRun).toHaveBeenCalledExactlyOnceWith('project-1', 'c');+ expect(document.activeElement).toBe(cancelFor('Second run'));+ });++ it('follows the queue scope setting: the active project alone, or every open project', async () => {+ const localRuns = [+ createTestLocalRun({ id: 'a', label: 'Here', projectId: 'project-1' }),+ createTestLocalRun({ id: 'b', label: 'Elsewhere', projectId: 'project-2' }),+ ];++ await render({ localRuns, queueJobsScope: 'active-project' });+ expect(rows().map((row) => row.querySelector('[data-list-primary]')?.textContent)).toEqual([+ expect.stringContaining('Here'),+ ]);+ expect(tab('All').textContent).toBe('All6');++ await render({ localRuns, queueJobsScope: 'all' });+ expect(rows()).toHaveLength(2);+ expect(tab('All').textContent).toBe('All7');+ });++ it('counts under All and Active, where it is listed, and steps aside for the finished filters', async () => {+ await render({ localRuns: [createTestLocalRun({ label: 'Fresh run' })] });++ expect(['All', 'Active', 'Done', 'Failed', 'Canceled'].map((label) => tab(label).textContent)).toEqual([+ 'All6',+ 'Active2',+ 'Done2',+ 'Failed1',+ 'Canceled1',+ ]);++ for (const [label, listed] of [+ ['Done', false],+ ['Failed', false],+ ['Canceled', false],+ ['Active', true],+ ['All', true],+ ] as const) {+ await act(() => tab(label).click());+ expect(section() !== null, label).toBe(listed);+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.tsx b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.tsxnew file mode 100644index 0000000000..5ff75e7157--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.tsx@@ -0,0 +1,179 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop */+import type { MouseEvent as ReactMouseEvent } from 'react';++import { Box, Icon, Text } from '@chakra-ui/react';+import { IconButton } from '@platform/ui/Button';+import { ListItem } from '@platform/ui/list/ListItem';+import { ListStack } from '@platform/ui/list/ListStack';+import { Scrollable } from '@platform/ui/Scrollable';+import { segmentTabsTabId } from '@platform/ui/SegmentTabs';+import {+ ChevronRightIcon,+ CircleAlertIcon,+ CloudOffIcon,+ HourglassIcon,+ SendIcon,+ TriangleAlertIcon,+ UnplugIcon,+ XIcon,+ type LucideIcon,+} from 'lucide-react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { QueueFilterId } from './queueFilters';++import { QUEUE_FILTER_TABS_ID } from './QueueFilterTabs';+import { useQueueUi, type QueueLocalRun } from './QueueUiContext';++const CHEVRON_OPEN = { transform: 'rotate(90deg)' } as const;++type LocalRunState = NonNullable<QueueLocalRun['retry']>['reason'] | 'offline' | 'submitting';++const STATE_META: Record<LocalRunState, { color: string; icon: LucideIcon; labelKey: string }> = {+ error: { color: 'fg.warning', icon: CircleAlertIcon, labelKey: 'widgets.queue.localRuns.state.error' },+ offline: { color: 'fg.warning', icon: CloudOffIcon, labelKey: 'widgets.queue.localRuns.state.offline' },+ 'server-error': {+ color: 'fg.warning',+ icon: TriangleAlertIcon,+ labelKey: 'widgets.queue.localRuns.state.serverError',+ },+ submitting: { color: 'fg.muted', icon: SendIcon, labelKey: 'widgets.queue.localRuns.state.submitting' },+ unavailable: { color: 'fg.warning', icon: HourglassIcon, labelKey: 'widgets.queue.localRuns.state.unavailable' },+ unreachable: { color: 'fg.warning', icon: UnplugIcon, labelKey: 'widgets.queue.localRuns.state.unreachable' },+};++/** Offline, the run waits for the connection whatever its last failure was. */+const getLocalRunState = (run: QueueLocalRun, isConnected: boolean): LocalRunState =>+ !isConnected ? 'offline' : (run.retry?.reason ?? 'submitting');++/**+ * The rows of the Submitting section (`LocalRunsSection` in `QueueWidgetView`), loaded only once this tab has a run the backend has not+ * accepted. The canceled row leaves at once; focus moves to a neighbour's Cancel, else to the filter tabs above, never+ * the page.+ */+export const LocalRunList = ({ filter, runs }: { filter: QueueFilterId; runs: readonly QueueLocalRun[] }) => {+ const { t } = useTranslation();+ const { cancelLocalRun } = useQueueUi();++ const cancel = useCallback(+ (run: QueueLocalRun, button: HTMLElement) => {+ const buttons = [+ ...(button.closest('[role="list"]')?.querySelectorAll<HTMLElement>('[data-local-run-cancel]') ?? []),+ ];+ const index = buttons.indexOf(button);+ const next =+ buttons[index + 1] ??+ buttons[index - 1] ??+ document.getElementById(segmentTabsTabId(QUEUE_FILTER_TABS_ID, filter));++ cancelLocalRun(run.projectId, run.id);+ next?.focus();+ },+ [cancelLocalRun, filter]+ );++ return (+ <ListStack dividers label={t('widgets.queue.localRuns.title')}>+ {runs.map((run) => (+ <LocalRunRow key={`${run.projectId}:${run.id}`} run={run} onCancel={cancel} />+ ))}+ </ListStack>+ );+};++const LocalRunRow = memo(+ ({ onCancel, run }: { onCancel: (run: QueueLocalRun, button: HTMLElement) => void; run: QueueLocalRun }) => {+ const { t } = useTranslation();+ const { isConnected } = useQueueUi();+ const [expanded, setExpanded] = useState(false);+ const toggle = useCallback(() => setExpanded((open) => !open), []);+ const state = getLocalRunState(run, isConnected);+ const meta = STATE_META[state];+ const title = run.label || t('widgets.queue.localRuns.untitled');+ const cancelLabel = t('widgets.queue.localRuns.cancel', { name: title });+ // The failure's text can be long (a traceback's last line, a proxy's page); the row shows its first line, and+ // expanding it shows the whole in a bounded scroll area, so it never pushes the rest of the queue away.+ const message = run.retry?.message.trim() ?? '';+ const canExpand = message !== '';+ const isExpanded = canExpand && expanded;+ const firstLine = message.split('\n')[0];++ const cancel = useCallback(+ (event: ReactMouseEvent<HTMLButtonElement>) => onCancel(run, event.currentTarget),+ [onCancel, run]+ );++ return (+ <Box+ borderColor={isExpanded ? 'border' : 'transparent'}+ borderWidth={1}+ overflow="hidden"+ role="listitem"+ rounded="md"+ >+ <ListItem+ actions={+ <IconButton+ aria-label={cancelLabel}+ color="fg.muted"+ data-local-run-cancel=""+ size="sm"+ tooltip={cancelLabel}+ variant="ghost"+ onClick={cancel}+ >+ <Icon as={XIcon} boxSize="3.5" />+ </IconButton>+ }+ description={+ // Wraps rather than truncates: it is the row's one statement of why the run waits.+ <Text color={meta.color}>{t(meta.labelKey, { attempt: (run.retry?.failureCount ?? 0) + 1 })}</Text>+ }+ isExpanded={canExpand ? isExpanded : undefined}+ leading={+ <Box+ alignItems="center"+ aria-hidden+ bg="bg.subtle"+ boxSize="8"+ color={meta.color}+ display="flex"+ flexShrink={0}+ justifyContent="center"+ rounded="md"+ >+ <Icon as={meta.icon} boxSize="4" />+ </Box>+ }+ role="presentation"+ title={title}+ titleTruncate="end"+ trailing={+ canExpand ? (+ <Icon+ as={ChevronRightIcon}+ boxSize="4"+ transition="transform var(--wb-motion-duration-fast) ease"+ css={isExpanded ? CHEVRON_OPEN : undefined}+ />+ ) : undefined+ }+ onPress={canExpand ? toggle : undefined}+ />++ {isExpanded ? (+ <Scrollable label={t('widgets.queue.localRuns.errorLabel', { name: title })} maxH="8rem" mb="2" mx="2.5">+ <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere" whiteSpace="pre-wrap">+ {message}+ </Text>+ </Scrollable>+ ) : canExpand ? (+ <Text color="fg.muted" fontSize="xs" pb="2" px="2.5" truncate>+ {firstLine}+ </Text>+ ) : null}+ </Box>+ );+ }+);diff --git a/invokeai/frontend/webv2/src/features/queue/ui/LocalRunListLoad.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunListLoad.browser.test.tsxnew file mode 100644index 0000000000..ec424d8b42--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunListLoad.browser.test.tsx@@ -0,0 +1,80 @@+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++import * as LocalRunListModule from './LocalRunList';+import { createTestLocalRun, createTestQueueUiAdapter } from './queueUiAdapter.testing';+import { QueueUiProvider } from './QueueUiContext';+import { createLocalRunListLoader, LocalRunsSection, type LocalRunListLoader } from './QueueWidgetView';++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackNS: 'translation',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++const runs = [createTestLocalRun({ label: 'Waiting run' })];++const render = (rows: LocalRunListLoader) =>+ act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueueUiProvider adapter={createTestQueueUiAdapter()}>+ <button type="button">Elsewhere in the widget</button>+ <LocalRunsSection filter="all" rows={rows} runs={runs} />+ </QueueUiProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );++it('keeps a failed chunk failed until Retry, which imports it once more and shows the rows', async () => {+ // The chunk fails as it does with the server down, then loads once the server is back.+ const importer = vi+ .fn<() => Promise<typeof LocalRunListModule>>()+ .mockRejectedValueOnce(new TypeError('Failed to fetch dynamically imported module'))+ .mockResolvedValue(LocalRunListModule);+ const rows = createLocalRunListLoader(importer);++ rows.preload();+ await vi.waitFor(() => expect(importer).toHaveBeenCalledOnce());+ // Neither another preload nor rendering refetches the failed chunk.+ rows.preload();+ await render(rows);++ const alert = await vi.waitUntil(() => host.querySelector<HTMLElement>('[role="alert"]'));+ expect(alert.textContent).toContain("Couldn't load the runs waiting to be submitted.");+ expect(host.textContent).toContain('Submitting');+ expect(host.querySelector('button')?.textContent).toBe('Elsewhere in the widget');+ expect(importer).toHaveBeenCalledOnce();++ await act(() => [...alert.querySelectorAll('button')].find((button) => button.textContent === 'Retry')!.click());++ await expect+ .poll(() => host.querySelector('[role="list"][aria-label="Submitting"]')?.textContent)+ .toContain('Waiting run');+ expect(importer).toHaveBeenCalledTimes(2);+ expect(host.querySelector('[role="alert"]')).toBeNull();+});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsxindex 73febd60bc..21d45ecc6d 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.browser.test.tsx@@ -32,7 +32,7 @@ import { requestQueueAction } from './queueActionRequests';import { clearQueueConfirmation, requestQueueConfirmation } from './queueConfirmationStore';import { QueueDataRuntime } from './QueueDataRuntime';import { getQueueAction, useQueueActions, type QueueActionId } from './queueMenuActions';-import { createTestQueueUiAdapter } from './queueUiAdapter.testing';+import { createTestLocalRun, createTestQueueUiAdapter } from './queueUiAdapter.testing';import { QueueUiProvider, type QueueUiAdapter } from './QueueUiContext';let host: HTMLDivElement | null = null;@@ -87,6 +87,12 @@ it('animates a queue confirmation out with its text instead of unmounting it onawait expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();});+/** `count` unaccepted runs in each project. */+const localRuns = (counts: Record<string, number>) =>+ Object.entries(counts).flatMap(([projectId, count]) =>+ Array.from({ length: count }, (_, index) => createTestLocalRun({ id: `${projectId}-run-${index}`, projectId }))+ );+describe('a bulk cancel from a shortcut or menu', () => {const notify = { error: vi.fn(), info: vi.fn(), success: vi.fn() };// Menu-only actions have no shortcut request; trigger them through the hook the menus use.@@ -181,17 +187,17 @@ describe('a bulk cancel from a shortcut or menu', () => {});it("stops this tab's runs the backend never got while offline, and sends nothing to it", async () => {- const cancelLocalUnsubmittedRuns = vi.fn();+ const cancelLocalRuns = vi.fn();const dialog = await renderWithQueue({- cancelLocalUnsubmittedRuns,+ cancelLocalRuns,isConnected: false,- localUnsubmittedRuns: { activeProject: 2, allProjects: 5 },+ localRuns: localRuns({ 'project-1': 2, 'project-2': 3 }),});expect(dialog.textContent).toContain('"count":2');await act(() => userEvent.click(buttonIn(dialog, 'widgets.queue.cancelAllItems')));- await vi.waitFor(() => expect(cancelLocalUnsubmittedRuns).toHaveBeenCalledWith('project-1'));+ await vi.waitFor(() => expect(cancelLocalRuns).toHaveBeenCalledWith('project-1'));expect(commands.cancelScopedItems).not.toHaveBeenCalled();});@@ -209,22 +215,22 @@ describe('a bulk cancel from a shortcut or menu', () => {describe('cancel-all-except-current, from its menu item', () => {it("stops this tab's runs the backend never got while offline, and sends nothing to it", async () => {- const cancelLocalUnsubmittedRuns = vi.fn();+ const cancelLocalRuns = vi.fn();const dialog = await renderWithQueue(- { cancelLocalUnsubmittedRuns, isConnected: false, localUnsubmittedRuns: { activeProject: 2, allProjects: 5 } },+ { cancelLocalRuns, isConnected: false, localRuns: localRuns({ 'project-1': 2, 'project-2': 3 }) },'cancel-all-except-current');await act(() => userEvent.click(buttonIn(dialog, 'widgets.queue.cancelAllExceptCurrent')));- await vi.waitFor(() => expect(cancelLocalUnsubmittedRuns).toHaveBeenCalledWith('project-1'));+ await vi.waitFor(() => expect(cancelLocalRuns).toHaveBeenCalledWith('project-1'));expect(commands.cancelScopedItems).not.toHaveBeenCalled();});it('stops only local runs while connected when the server has nothing queued', async () => {- const cancelLocalUnsubmittedRuns = vi.fn();+ const cancelLocalRuns = vi.fn();const dialog = await renderWithQueue(- { cancelLocalUnsubmittedRuns, localUnsubmittedRuns: { activeProject: 1, allProjects: 1 } },+ { cancelLocalRuns, localRuns: localRuns({ 'project-1': 1 }) },'cancel-all-except-current',0);@@ -232,14 +238,14 @@ describe('a bulk cancel from a shortcut or menu', () => {await act(() => userEvent.click(buttonIn(dialog, 'widgets.queue.cancelAllExceptCurrent')));await vi.waitFor(() => expect(notify.success).toHaveBeenCalled());- expect(cancelLocalUnsubmittedRuns).toHaveBeenCalledWith('project-1');+ expect(cancelLocalRuns).toHaveBeenCalledWith('project-1');expect(commands.cancelScopedItems).not.toHaveBeenCalled();});it("stops this tab's unaccepted runs and the server's queued items, keeping the running one", async () => {- const cancelLocalUnsubmittedRuns = vi.fn();+ const cancelLocalRuns = vi.fn();const dialog = await renderWithQueue(- { cancelLocalUnsubmittedRuns, localUnsubmittedRuns: { activeProject: 1, allProjects: 1 } },+ { cancelLocalRuns, localRuns: localRuns({ 'project-1': 1 }) },'cancel-all-except-current');@@ -247,7 +253,7 @@ describe('a bulk cancel from a shortcut or menu', () => {await act(() => userEvent.click(buttonIn(dialog, 'widgets.queue.cancelAllExceptCurrent')));await vi.waitFor(() => expect(commands.cancelScopedItems).toHaveBeenCalledOnce());- expect(cancelLocalUnsubmittedRuns).toHaveBeenCalledWith('project-1');+ expect(cancelLocalRuns).toHaveBeenCalledWith('project-1');expect(commands.cancelScopedItems).toHaveBeenCalledWith(expect.anything(), { keepCurrent: true });await vi.waitFor(() =>expect(notify.success).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('"count":3'))diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsxindex ffc16ecbb7..93e8991c08 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx@@ -15,9 +15,12 @@ export const QUEUE_FILTER_TABS_ID = 'queue-filter';* while there are any (All · Active · Done · Failed · Canceled).*/export const QueueFilterTabs = ({+ localRunCount,value,onChange,}: {+ /** This tab's runs the backend has not accepted that the widget lists (`useShownLocalRuns`). */+ localRunCount: number;value: QueueFilterId;onChange: (filter: QueueFilterId) => void;}) => {@@ -27,7 +30,7 @@ export const QueueFilterTabs = ({const tabs = useMemo<SegmentTab<QueueFilterId>[]>(() =>QUEUE_FILTERS.map((filter) => {- const count = getFilterCount(counts, filter.id);+ const count = getFilterCount(counts, filter.id, localRunCount);return {id: filter.id,@@ -46,7 +49,7 @@ export const QueueFilterTabs = ({),};}),- [counts, formatCount, t]+ [counts, formatCount, localRunCount, t]);return (diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsxindex 6d820e1a19..57be4ef884 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx@@ -1,3 +1,4 @@+import type { QueueSubmissionRetry } from '@features/queue/core/historyTypes';import type { QueueItemReadModel } from '@features/queue/core/types';import { createContext, useContext, useSyncExternalStore, type ComponentType, type ReactNode } from 'react';@@ -25,12 +26,15 @@ export interface QueueUiAdapter {/** Whether `projectId` is open in this tab; a Canvas rerun is staged only into a project open here. */isProjectOpen(projectId: string): boolean;/**- * Runs this tab queued that the backend has not accepted yet (unsubmitted, or with their enqueue in flight), in the- * active project and across this tab's open projects. A backend cancel cannot reach them.+ * Runs this tab queued that the backend has not accepted yet (unsubmitted, enqueue in flight, or retried after+ * failures), across this tab's open projects. The backend has no row for them, so only this tab can show or cancel+ * them. Keep the array stable while its runs are unchanged: the queue widget and its actions re-render on a new one.*/- localUnsubmittedRuns: { activeProject: number; allProjects: number };- /** Cancels those runs, in one project or (null) every open project. */- cancelLocalUnsubmittedRuns(projectId: string | null): void;+ localRuns: readonly QueueLocalRun[];+ /** Cancels one of those runs. */+ cancelLocalRun(projectId: string, runId: string): void;+ /** Cancels those runs in one project or (null) every open project. */+ cancelLocalRuns(projectId: string | null): void;notify: QueueUiNotificationPort;openQueue(): void;/**@@ -53,6 +57,18 @@ export interface QueueUiAdapter {export type QueueViewer = 'admin' | 'member' | 'single';+/** A run this tab queued that the backend has not accepted yet, as the queue widget lists it. */+export interface QueueLocalRun {+ id: string;+ projectId: string;+ /** What it makes, in the user's words (workflow name or prompt); empty when it carries neither. */+ label: string;+ /** Epoch ms it was queued; 0 when unknown, which reads as long ago. */+ submittedAt: number;+ /** Why its latest enqueue failed while it is retried; null before any failure. */+ retry: Pick<QueueSubmissionRetry, 'failureCount' | 'message' | 'reason'> | null;+}+export interface QueueLoadingModelPort {getLabel(): string | null;subscribe(listener: () => void): () => void;diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsxindex 8d69776917..f9f6d9be78 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx@@ -1,20 +1,90 @@import type { QueueActivity } from '@features/queue/core/queueActivity';-import { Stack } from '@chakra-ui/react';+import { Stack, VisuallyHidden } from '@chakra-ui/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { ListSectionHeader } from '@platform/ui/list/ListSectionHeader';+import { RetryBoundary } from '@platform/ui/RetryBoundary';import { Scrollable } from '@platform/ui/Scrollable';import { StatusWidgetChip } from '@platform/ui/StatusWidgetChip';import { CloudOffIcon, ListOrderedIcon, PauseIcon, type LucideIcon } from 'lucide-react';-import { useState } from 'react';+import { lazy, Suspense, useState, useSyncExternalStore, type ComponentProps, type ComponentType } from 'react';import { useTranslation } from 'react-i18next';+import type * as LocalRunListExports from './LocalRunList';import type { QueueFilterId } from './queueFilters';+import type { QueueLocalRun } from './QueueUiContext';import { CurrentBatchSection } from './NowNextSection';import { QueueFilterTabs } from './QueueFilterTabs';+import { useShownLocalRuns } from './queueScope';+import { useQueueUi } from './QueueUiContext';import { usePendingQueueItemReveal } from './queueUiStore';import { RecentSection } from './RecentSection';import { useQueueWidgetActivity } from './useQueueWidgetActivity';+type LocalRunListModule = Pick<typeof LocalRunListExports, 'LocalRunList'>;++type LocalRunListRows = ComponentType<ComponentProps<typeof LocalRunListExports.LocalRunList>>;++/** An external store of the rows component, so the section renders the fresh one a Retry creates. */+export interface LocalRunListLoader {+ /** The rows, lazily; replaced on Retry after a failure, since `React.lazy` keeps its first rejection. */+ getSnapshot(): { Rows: LocalRunListRows };+ /** Starts the import without waiting; a failed one stays failed until `retry`. */+ preload(): void;+ /** Imports again after a failure (an import in flight or done is reused), for the section's Retry. */+ retry(): Promise<unknown>;+ subscribe(listener: () => void): () => void;+}++/**+ * Loads the Submitting section's rows. Runs the backend has not accepted are rare, so they load with the first one, not+ * with the widget. A failed import stays failed until Retry, so re-rendering never refetches it: the server that+ * refused the run usually serves the chunk too.+ */+export const createLocalRunListLoader = (importer: () => Promise<LocalRunListModule>): LocalRunListLoader => {+ const listeners = new Set<() => void>();+ let failed = false;+ let rows: Promise<{ default: typeof LocalRunListExports.LocalRunList }> | null = null;+ const load = () => {+ if (!rows) {+ const next = importer().then((module) => ({ default: module.LocalRunList }));+ rows = next;+ next.catch(() => {+ if (rows === next) {+ failed = true;+ }+ });+ }++ return rows;+ };+ let snapshot: { Rows: LocalRunListRows } = { Rows: lazy(load) };++ return {+ getSnapshot: () => snapshot,+ preload: () => {+ void load().catch(() => undefined);+ },+ retry: () => {+ if (failed) {+ failed = false;+ rows = null;+ snapshot = { Rows: lazy(load) };+ listeners.forEach((listener) => listener());+ }++ return load();+ },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+};++const localRunList = createLocalRunListLoader(() => import('./LocalRunList'));+export const QueueWidgetView = ({presentation,region,@@ -33,6 +103,8 @@ const QueueContent = () => {const { t } = useTranslation();const [filter, setFilter] = useState<QueueFilterId>('all');const revealRequest = usePendingQueueItemReveal();+ const { localRuns } = useQueueUi();+ const shownLocalRuns = useShownLocalRuns();const [handledRevealRequestId, setHandledRevealRequestId] = useState<number | null>(null);// Adjust the active tab during render so it cannot hide a requested item.@@ -44,11 +116,13 @@ const QueueContent = () => {// The counted filters stay put while the item lists scroll on their own.return (<Stack gap="3" h="full" minH="0" pt="3">+ {localRuns.length > 0 ? <LocalRunListPreload rows={localRunList} /> : null}<Stack flexShrink={0} gap="3" px="3">- <QueueFilterTabs value={filter} onChange={setFilter} />+ <QueueFilterTabs localRunCount={shownLocalRuns.length} value={filter} onChange={setFilter} /></Stack><Scrollable flex="1" label={t('widgets.queue.items')} minH="0" overflowX="hidden"><Stack gap="3" pb="3" px="3">+ <LocalRunsSection filter={filter} rows={localRunList} runs={shownLocalRuns} /><CurrentBatchSection filter={filter} revealRequest={revealRequest} /><RecentSection filter={filter} revealRequest={revealRequest} /></Stack>@@ -57,6 +131,87 @@ const QueueContent = () => {);};+/**+ * Fetches the rows with the first unaccepted run, shown or not, while the server that serves them likely still answers.+ * Mounted while there is one; mounting again later reuses the import, or keeps a failed one failed until Retry.+ */+const LocalRunListPreload = ({ rows }: { rows: LocalRunListLoader }) => {+ useMountEffect(rows.preload);+ return null;+};++/**+ * SUBMITTING — this tab's runs the backend has not accepted yet: being sent, or retried after failures. The backend has+ * no row for them, so this is the one place to see why they wait and to cancel them. Like the current batch, they are+ * unfinished, so they show under All and Active alone. The header shows at once, so the section does not jump when its+ * rows arrive; rows that fail to load leave the rest of the widget working.+ */+export const LocalRunsSection = ({+ filter,+ rows,+ runs,+}: {+ filter: QueueFilterId;+ rows: LocalRunListLoader;+ runs: readonly QueueLocalRun[];+}) => {+ const { t } = useTranslation();+ const current = useSyncExternalStore(rows.subscribe, rows.getSnapshot, rows.getSnapshot);+ const isListed = runs.length > 0 && (filter === 'all' || filter === 'active');++ return (+ <>+ <LocalRunAnnouncements runs={runs} />+ {isListed ? (+ // Row surfaces bleed into the widget padding so their content lines up with the controls above.+ <Stack gap="1" mx="-2">+ <ListSectionHeader count={runs.length} label={t('widgets.queue.localRuns.title')} />+ <RetryBoundary+ message={t('widgets.queue.localRuns.loadFailed')}+ retry={rows.retry}+ retryLabel={t('common.retry')}+ >+ <Suspense fallback={null}>+ <current.Rows filter={filter} runs={runs} />+ </Suspense>+ </RetryBoundary>+ </Stack>+ ) : null}+ </>+ );+};++const RETRY_ANNOUNCEMENT_KEYS = {+ error: 'widgets.queue.localRuns.announcement.error',+ 'server-error': 'widgets.queue.localRuns.announcement.serverError',+ unavailable: 'widgets.queue.localRuns.announcement.unavailable',+ unreachable: 'widgets.queue.localRuns.announcement.unreachable',+} satisfies Record<NonNullable<QueueLocalRun['retry']>['reason'], string>;++/**+ * Tells screen readers why a run retries. Each retried run has one line keyed by its reason and naming no attempt, so a+ * line is added, and spoken, only when a run starts retrying or its reason changes, never on another attempt. It+ * stays mounted, whatever the filter, because a region inserted with its text is not announced, and switching tabs is+ * no news. Being offline, and the final failure that removes the run, are left to their own notices.+ */+const LocalRunAnnouncements = ({ runs }: { runs: readonly QueueLocalRun[] }) => {+ const { t } = useTranslation();++ return (+ <VisuallyHidden aria-atomic="false" aria-live="polite" as="div" role="status">+ {runs.map((run) =>+ run.retry ? (+ <div key={`${run.projectId}:${run.id}:${run.retry.reason}`}>+ {t(RETRY_ANNOUNCEMENT_KEYS[run.retry.reason], {+ name: run.label || t('widgets.queue.localRuns.untitled'),+ })}+ </div>+ ) : null+ )}+ </VisuallyHidden>+ );+};+const chipIcons = {idle: ListOrderedIcon,'loading-model': ListOrderedIcon,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.test.tsindex 612a062e65..c869ca2773 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.test.ts@@ -19,7 +19,11 @@ const counts: QueueCounts = {describe('queue filters', () => {it('counts every tab the way its list filters: the same items, waiting ones among the active', () => {- expect(QUEUE_FILTERS.map(({ id }) => getFilterCount(counts, id))).toEqual([19, 13, 2, 3, 1]);+ expect(QUEUE_FILTERS.map(({ id }) => getFilterCount(counts, id, 0))).toEqual([19, 13, 2, 3, 1]);expect(matchesFilter('waiting', 'active')).toBe(true);});++ it("counts this tab's runs the backend has not accepted under All and Active alone, where they are listed", () => {+ expect(QUEUE_FILTERS.map(({ id }) => getFilterCount(counts, id, 2))).toEqual([21, 15, 2, 3, 1]);+ });});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.tsindex cac3798548..89e1b29303 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueFilters.ts@@ -25,14 +25,15 @@ export const matchesFilter = (status: QueueItemStatus, filter: QueueFilterId): b/*** Count for a filter, derived from the scope's status counts (not the windowed list). Every tab counts what its list- * shows, everyone's items alike, so Active is the pending, running and waiting items `matchesFilter` keeps.+ * shows, everyone's items alike, so Active is the pending, running and waiting items `matchesFilter` keeps. This tab's+ * runs the backend has not accepted (`localRuns`) are listed under All and Active, so both count them too.*/-export const getFilterCount = (counts: QueueCounts, filter: QueueFilterId): number => {+export const getFilterCount = (counts: QueueCounts, filter: QueueFilterId, localRuns: number): number => {switch (filter) {case 'all':- return counts.total;+ return counts.total + localRuns;case 'active':- return counts.pending + counts.inProgress + counts.waiting;+ return counts.pending + counts.inProgress + counts.waiting + localRuns;case 'completed':return counts.completed;case 'failed':diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsxindex 627846bfa3..59481a0b3f 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx@@ -24,7 +24,13 @@ import type { QueueUiNotificationPort, QueueViewer } from './QueueUiContext';import { requestQueueConfirmation, type QueueConfirmation } from './queueConfirmationStore';import { refreshQueue, useIsProcessorPaused, useNowNextItems, useQueueCounts } from './queueDataStore';-import { translateScoped, useQueueActionScope, useQueueQueryScope, type QueueActionScope } from './queueScope';+import {+ translateScoped,+ useQueueActionScope,+ useQueueQueryScope,+ useScopedLocalRuns,+ type QueueActionScope,+} from './queueScope';import { useQueueUi } from './QueueUiContext';export type QueueActionId =@@ -290,9 +296,8 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueueactiveProjectId,canManageItem,canManageProcessor,- cancelLocalUnsubmittedRuns,+ cancelLocalRuns,isConnected,- localUnsubmittedRuns,notify,openQueue,viewer,@@ -300,8 +305,7 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueueconst counts = useMemo(() => getQueueActionCounts(serverCounts, scope, viewer), [scope, serverCounts, viewer]);const hasRunningItem = current?.status === 'in_progress' && canManageItem(current);const localProjectId = scope.kind === 'project' ? activeProjectId : null;- const localUnsubmitted =- localProjectId === null ? localUnsubmittedRuns.allProjects : localUnsubmittedRuns.activeProject;+ const localUnsubmitted = useScopedLocalRuns().length;const runners = useMemo<Record<QueueActionId, () => Promise<void>>>(() => {// Each result repeats the counts its confirmation named: both come from the model the trigger was built with.@@ -315,7 +319,7 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueuecancelOnServer: () => Promise<void>,describeRequested: (count: number) => string): Promise<void> => {- cancelLocalUnsubmittedRuns(localProjectId);+ cancelLocalRuns(localProjectId);await (serverCount > 0 ? cancelOnServer().then(() => refreshQueue()) : Promise.resolve()).then(() =>notify.success(@@ -446,7 +450,7 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueue};}, [canManageItem,- cancelLocalUnsubmittedRuns,+ cancelLocalRuns,counts,current,hasRunningItem,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueScope.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.tsindex 02a77737b6..2272f67884 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueScope.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueScope.ts@@ -3,9 +3,9 @@ import type { QueueItemReadModel, QueueQueryScope, QueueReadModel } from '@featuimport type { TFunction } from 'i18next';import { buildProjectQueueItemOriginPrefix, parseQueueItemOrigin } from '@features/queue/data/events';-import { useMemo } from 'react';+import { useCallback, useMemo, useSyncExternalStore } from 'react';-import { useQueueUi, type QueueViewer } from './QueueUiContext';+import { useQueueUi, type QueueLocalRun, type QueueViewer } from './QueueUiContext';export type QueueJobsScope = 'active-project' | 'all';@@ -78,6 +78,94 @@ export const useQueueQueryScope = (): QueueQueryScope => {return useMemo(() => getQueueQueryScope({ projectId, queueJobsScope }), [projectId, queueJobsScope]);};+/**+ * This tab's runs the backend has not accepted, within the queue scope setting: the active project's alone, or every+ * open project's. The same reach as the query scope and the bulk actions; cancel-all counts all of them, shown or not+ * (`useShownLocalRuns`).+ */+export const useScopedLocalRuns = (): readonly QueueLocalRun[] => {+ const { activeProjectId, localRuns, queueJobsScope } = useQueueUi();+ const projectId = queueJobsScope === 'active-project' ? activeProjectId : null;++ return useMemo(+ () => (projectId === null ? localRuns : localRuns.filter((run) => run.projectId === projectId)),+ [localRuns, projectId]+ );+};++/**+ * A first enqueue usually lands well within this. Showing it sooner would flash a row, and a count, on every Invoke+ * before the backend's row replaces it.+ */+export const LOCAL_RUN_REVEAL_DELAY_MS = 1000;++const NO_LOCAL_RUNS: readonly QueueLocalRun[] = [];++/** When a run earns its row: at once after a failure or while offline, otherwise once its enqueue outlasts the delay. */+const getRevealAt = (run: QueueLocalRun, isConnected: boolean): number =>+ run.retry !== null || !isConnected ? Number.NEGATIVE_INFINITY : run.submittedAt + LOCAL_RUN_REVEAL_DELAY_MS;++/**+ * The scoped runs the queue widget lists and counts: those `getRevealAt` has reached. A run restored from storage is old,+ * so it shows at once; a hung first request shows after the delay. Its caller re-renders as each one comes due, on one+ * timer at a time, cleared when it unmounts.+ */+export const useShownLocalRuns = (): readonly QueueLocalRun[] => {+ const { isConnected } = useQueueUi();+ const runs = useScopedLocalRuns();+ const revealTimes = useMemo(+ () => runs.map((run) => getRevealAt(run, isConnected)).sort((left, right) => left - right),+ [isConnected, runs]+ );+ // How many reveal times have passed: it changes only as one comes due, so the clock is read outside render.+ const getDueCount = useCallback(() => {+ const now = Date.now();+ const next = revealTimes.findIndex((time) => time > now);++ return next === -1 ? revealTimes.length : next;+ }, [revealTimes]);+ const subscribe = useCallback(+ (notify: () => void) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const schedule = () => {+ const now = Date.now();+ const next = revealTimes.find((time) => time > now);++ if (next !== undefined) {+ // At most the delay: a reveal further off means the clock moved back since the run was queued, and a delay+ // past setTimeout's 2^31-1 ms range would fire at once, again and again.+ timer = setTimeout(+ () => {+ notify();+ schedule();+ },+ Math.min(next - now, LOCAL_RUN_REVEAL_DELAY_MS)+ );+ }+ };++ schedule();+ return () => clearTimeout(timer);+ },+ [revealTimes]+ );+ const dueCount = useSyncExternalStore(subscribe, getDueCount, getDueCount);++ return useMemo(() => {+ if (dueCount === runs.length) {+ return runs;+ }++ if (dueCount === 0) {+ return NO_LOCAL_RUNS;+ }++ const latestDue = revealTimes[dueCount - 1]!;++ return runs.filter((run) => getRevealAt(run, isConnected) <= latestDue);+ }, [dueCount, isConnected, revealTimes, runs]);+};+/*** The reach of a bulk action as the viewer meets it: one project; every project (single-user); every project and user* (an administrator, whose cancel and clear reach everyone's items); or every project of the viewer's own (a member,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.tsindex c957e4c4d4..23acc12866 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts@@ -1,4 +1,4 @@-import type { QueueUiAdapter } from './QueueUiContext';+import type { QueueLocalRun, QueueUiAdapter } from './QueueUiContext';const noLoadingModel = { getLabel: (): string | null => null, subscribe: () => () => undefined };@@ -12,11 +12,12 @@ export const createTestQueueUiAdapter = (overrides: Partial<QueueUiAdapter> = {}canManageItem: () => true,canManageProcessor: true,canViewItemDetails: () => true,- cancelLocalUnsubmittedRuns: () => undefined,+ cancelLocalRun: () => undefined,+ cancelLocalRuns: () => undefined,isConnected: true,isProjectOpen: () => true,loadingModel: noLoadingModel,- localUnsubmittedRuns: { activeProject: 0, allProjects: 0 },+ localRuns: [],notify: { error: () => undefined, info: () => undefined, success: () => undefined },openQueue: () => undefined,preloadItemActions: () => undefined,@@ -24,3 +25,13 @@ export const createTestQueueUiAdapter = (overrides: Partial<QueueUiAdapter> = {}viewer: 'single',...overrides,});++/** A run this tab queued long ago in `project-1` and is still submitting, with no failure yet. */+export const createTestLocalRun = (overrides: Partial<QueueLocalRun> = {}): QueueLocalRun => ({+ id: 'run-1',+ label: 'A castle at dusk',+ projectId: 'project-1',+ retry: null,+ submittedAt: 0,+ ...overrides,+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.tsindex 2533f6544e..8763247806 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts@@ -285,6 +285,87 @@ describe('IndexedDB queue run journal', () => {expect(restoredMalformed).not.toHaveProperty('retriedBackendItemIds');});+ it('keeps the failed submission of a run not yet accepted, and drops a malformed or stale one without losing the run', async () => {+ const { journal } = await createJournal();+ const store = createWorkbenchStore();+ const projectId = store.getState().activeProjectId;+ const retry = {+ failedAt: 12_000,+ failureCount: 3,+ message: 'graph validation crashed',+ reason: 'server-error' as const,+ serverErrorCount: 2,+ serverErrorSince: 1_000,+ status: 500,+ };+ const retrying = createItem({ submissionRetry: retry });+ // A server error must be counted, and its window cannot start after the failure it ends with.+ const miscounted = createItem({ id: 'queue-item-2', submissionRetry: { ...retry, serverErrorCount: 0 } });+ const backwards = createItem({ id: 'queue-item-3', submissionRetry: { ...retry, serverErrorSince: 13_000 } });+ // Every server error is a failed submission.+ const undercounted = createItem({ id: 'queue-item-5', submissionRetry: { ...retry, failureCount: 1 } });+ // A run the backend accepted has no submission left to retry.+ const accepted = createItem({+ backendItemIds: [11],+ id: 'queue-item-4',+ status: 'running',+ submissionRetry: retry,+ });+ // A failure that is neither a server error nor a transport failure keeps its own reason.+ const otherError = {+ ...retry,+ message: 'Invalid queue enqueue response',+ reason: 'error' as const,+ serverErrorCount: 0,+ serverErrorSince: null,+ status: null,+ };+ const unreadable = createItem({ id: 'queue-item-6', submissionRetry: otherError });+ // A reason this build does not know, as a later build might write it.+ const unknownReason = createItem({+ id: 'queue-item-7',+ submissionRetry: { ...otherError, reason: 'throttled' } as unknown as WorkbenchQueueItem['submissionRetry'],+ });+ // Written before messages were bounded: a whole HTML error page.+ const page = `<html>${'x'.repeat(5_000)}</html>`;+ const longMessage = createItem({ id: 'queue-item-8', submissionRetry: { ...retry, message: page } });+ for (const item of [+ retrying,+ miscounted,+ backwards,+ undercounted,+ accepted,+ unreadable,+ unknownReason,+ longMessage,+ ]) {+ await journal.record(projectId, item);+ }++ const loaded = await journal.listForProject(projectId);+ expect(loaded.kind).toBe('available');+ store.commands.queue.restoreFromJournal({+ items: loaded.kind === 'available' ? loaded.entries.map((entry) => entry.item) : [],+ projectId,+ });++ const restored = store.getState().projects[0]?.queue.items ?? [];+ expect(restored.find((item) => item.id === retrying.id)).toMatchObject({+ status: 'pending',+ submissionRetry: retry,+ });+ expect(restored.find((item) => item.id === unreadable.id)).toMatchObject({ submissionRetry: otherError });+ expect(restored.find((item) => item.id === longMessage.id)?.submissionRetry).toEqual({+ ...retry,+ message: `${page.slice(0, 499)}…`,+ });+ for (const item of [miscounted, backwards, undercounted, accepted, unknownReason]) {+ const restoredItem = restored.find((candidate) => candidate.id === item.id);+ expect(restoredItem).toMatchObject({ status: item.status });+ expect(restoredItem).not.toHaveProperty('submissionRetry');+ }+ });+it('restores newest-first submission order without moving a run when its status changes', async () => {const { journal } = await createJournal();await journal.record('project-1', createItem({ id: 'queue-item-1' }));diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.tsindex 8a10e3c3f1..0a62eeb742 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts@@ -1,7 +1,8 @@+import type { QueueSubmissionRetry } from '@features/queue/contracts';import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';import { cloneGenerateWidgetValues, normalizeGenerateWidgetValues } from '@features/generation/settings';-import { MAX_QUEUE_BATCH_ITEMS } from '@features/queue';+import { boundSubmissionRetryMessage, MAX_QUEUE_BATCH_ITEMS } from '@features/queue';import { cloneVideoWidgetValues, normalizeVideoWidgetValues } from '@features/video';const isRecord = (value: unknown): value is Record<string, unknown> =>@@ -14,6 +15,44 @@ const isBackendItemIdList = (value: unknown): value is number[] =>new Set(value).size === value.length &&value.every((item) => Number.isSafeInteger(item) && item > 0);+/**+ * A retry record only means something with its invariants intact; anything else, including a reason a later build+ * added, is dropped, never the run. Its message is bounded again, as records from before the bound may hold a whole+ * response body.+ */+const normalizeSubmissionRetry = (value: unknown): QueueSubmissionRetry | undefined => {+ if (!isRecord(value)) {+ return undefined;+ }+ const { failedAt, failureCount, message, reason, serverErrorCount, serverErrorSince, status } = value;+ if (+ (reason !== 'error' && reason !== 'server-error' && reason !== 'unavailable' && reason !== 'unreachable') ||+ typeof message !== 'string' ||+ !isFiniteNumber(failedAt) ||+ (status !== null && !(Number.isSafeInteger(status) && (status as number) >= 100 && (status as number) <= 599)) ||+ !Number.isSafeInteger(serverErrorCount) ||+ (serverErrorCount as number) < 0 ||+ // Server errors are among the consecutive failures, and the latest failure is one of them.+ !Number.isSafeInteger(failureCount) ||+ (failureCount as number) < Math.max(serverErrorCount as number, 1) ||+ (reason === 'server-error') !== (serverErrorCount as number) > 0 ||+ (serverErrorCount === 0+ ? serverErrorSince !== null+ : !isFiniteNumber(serverErrorSince) || serverErrorSince > failedAt)+ ) {+ return undefined;+ }+ return {+ failedAt,+ failureCount: failureCount as number,+ message: boundSubmissionRetryMessage(message),+ reason,+ serverErrorCount: serverErrorCount as number,+ serverErrorSince: serverErrorSince as number | null,+ status: status as number | null,+ };+};+export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem | null => {if (!isRecord(value) ||@@ -102,6 +141,10 @@ export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem |return null;}+ // Only a run the backend has not accepted is still being submitted.+ const submissionRetry =+ value.status === 'pending' && !backendItemIds?.length ? normalizeSubmissionRetry(value.submissionRetry) : undefined;+let recall: WorkbenchQueueItem['snapshot']['recall'];try {const rawRecall = isRecord(snapshot.recall) ? snapshot.recall : null;@@ -166,5 +209,6 @@ export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem |submittedAt: snapshot.submittedAt,},status: value.status,+ ...(submissionRetry ? { submissionRetry } : {}),};};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 2e56d2534b..bcb5daeea5 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1534,6 +1534,60 @@ describe('adopting a project from another realm', () => {expect(normalized.queue).toBe(project.queue);});+ it('keeps the failed submission of a run until the backend accepts it or the run ends', () => {+ let state = submitGenerate(primeGenerate());+ const projectId = state.activeProjectId;+ const queueItemId = getActiveProject(state).queue.items[0]!.id;+ const recordRetry = (current: WorkbenchState) =>+ workbenchReducer(current, {+ projectId,+ queueItemId,+ retry: {+ failedAt: 2_000,+ failureCount: 1,+ message: 'unavailable',+ reason: 'unavailable',+ serverErrorCount: 0,+ serverErrorSince: null,+ status: 503,+ },+ type: 'recordQueueItemSubmissionRetry',+ });++ state = recordRetry(state);+ expect(getActiveProject(state).queue.items[0]?.submissionRetry).toMatchObject({+ reason: 'unavailable',+ status: 503,+ });+ expect(recordRetry(state)).toBe(state);++ const accepted = workbenchReducer(state, {+ backendItemIds: [42],+ projectId,+ queueItemId,+ type: 'markQueueItemBackendSubmitted',+ });+ expect(getActiveProject(accepted).queue.items[0]).not.toHaveProperty('submissionRetry');+ // A late answer to an earlier attempt does not bring it back.+ expect(recordRetry(accepted)).toBe(accepted);++ const failed = workbenchReducer(state, {+ error: 'graph validation crashed',+ projectId,+ queueItemId,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ const cancelled = workbenchReducer(state, { notice: null, projectId, queueItemId, type: 'cancelQueueItem' });+ for (const [ended, status] of [+ [failed, 'failed'],+ [cancelled, 'cancelled'],+ ] as const) {+ expect(getActiveProject(ended).queue.items[0]).toMatchObject({ status });+ expect(getActiveProject(ended).queue.items[0]).not.toHaveProperty('submissionRetry');+ }+ });+it('preserves and routes live queue work when server content replaces a project', () => {let state = submitGenerate(primeGenerate());const liveProject = getActiveProject(state);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 2e401ecf83..6be32dd9c8 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1,6 +1,11 @@import type { GenerateWidgetValues, ImageWithDims } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';-import type { QueueCompiledSubmission, QueueHistoryItemStatus, QueueRunErrorCode } from '@features/queue/contracts';+import type {+ QueueCompiledSubmission,+ QueueHistoryItemStatus,+ QueueRunErrorCode,+ QueueSubmissionRetry,+} from '@features/queue/contracts';import type { ProjectGraphState, ProjectWorkflowSource } from '@features/workflow/contracts';import type { WorkflowSubmissionPlan } from '@features/workflow/graph';import type { LogNamespace } from '@platform/logging/contracts';@@ -462,6 +467,13 @@ type WorkbenchReducerAction =backendItemIds: number[];backendBatchId?: string;}+ | {+ /** The latest failed submission of a pending run the backend has not accepted; ignored for any other run. */+ type: 'recordQueueItemSubmissionRetry';+ projectId: string;+ queueItemId: string;+ retry: QueueSubmissionRetry;+ }| {type: 'setQueueItemStatus';projectId: string;@@ -3689,6 +3701,25 @@ const reopenQueueItemForRetry = (});};+const isSameSubmissionRetry = (left: QueueSubmissionRetry | undefined, right: QueueSubmissionRetry): boolean =>+ left !== undefined &&+ left.reason === right.reason &&+ left.failureCount === right.failureCount &&+ left.serverErrorCount === right.serverErrorCount &&+ left.serverErrorSince === right.serverErrorSince &&+ left.status === right.status &&+ left.message === right.message &&+ left.failedAt === right.failedAt;++/** A run the backend accepted, or one that ended, has no submission left to retry. */+const withoutSubmissionRetry = (item: QueueItem): QueueItem => {+ if (item.submissionRetry === undefined) {+ return item;+ }+ const { submissionRetry: _, ...rest } = item;+ return rest;+};+const mergeBackendItemId = (ids: number[] | undefined, backendItemId: number): number[] =>ids?.includes(backendItemId) ? ids : [...(ids ?? []), backendItemId];@@ -5577,14 +5608,33 @@ const reduceWorkbenchAction = (item.backendItemIds?.length === action.backendItemIds.length &&item.backendItemIds.every((id, index) => id === action.backendItemIds[index]);- return item.backendBatchId === action.backendBatchId && hasSameBackendItemIds && item.status === status+ return item.backendBatchId === action.backendBatchId &&+ hasSameBackendItemIds &&+ item.status === status &&+ item.submissionRetry === undefined? item- : { ...item, backendBatchId: action.backendBatchId, backendItemIds: action.backendItemIds, status };+ : {+ ...withoutSubmissionRetry(item),+ backendBatchId: action.backendBatchId,+ backendItemIds: action.backendItemIds,+ status,+ };});return clampCanvasStagingSelection(nextProject, previousSelectedSlot);});}+ case 'recordQueueItemSubmissionRetry': {+ return updateProjectById(state, action.projectId, (project) =>+ updateQueueItem(project, action.queueItemId, (item) =>+ item.status !== 'pending' ||+ item.backendItemIds?.length ||+ isSameSubmissionRetry(item.submissionRetry, action.retry)+ ? item+ : { ...item, submissionRetry: { ...action.retry } }+ )+ );+ }case 'setQueueItemStatus': {const project = state.projects.find((project) => project.id === action.projectId);const queueItem = project?.queue.items.find((item) => item.id === action.queueItemId);@@ -5593,6 +5643,7 @@ const reduceWorkbenchAction = (return state;}+ // Only a pending run holds a submission retry, so an unchanged status has none to clear.if (queueItem?.status === action.status && queueItem.error === action.error) {return state;}@@ -5600,7 +5651,7 @@ const reduceWorkbenchAction = (const nextState = updateProjectById(state, action.projectId, (project) => {const previousSelectedSlot = getSelectedCanvasStagingSlot(project);const nextProject = updateQueueItem(project, action.queueItemId, (item) => ({- ...item,+ ...(action.status === 'pending' ? item : withoutSubmissionRetry(item)),error: action.error,status: action.status,}));@@ -6195,7 +6246,7 @@ const reduceWorkbenchAction = (return item;}- return { ...item, cancellationPending: true, status: 'cancelled' };+ return { ...withoutSubmissionRetry(item), cancellationPending: true, status: 'cancelled' };}),},};@@ -6247,7 +6298,9 @@ const reduceWorkbenchAction = (...project,queue: {items: project.queue.items.map((item) =>- isUnsubmittedQueueItem(item) ? { ...item, cancellationPending: true, status: 'cancelled' } : item+ isUnsubmittedQueueItem(item)+ ? { ...withoutSubmissionRetry(item), cancellationPending: true, status: 'cancelled' }+ : item),},};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 3b0943c711..9f4dcc64c2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -493,6 +493,7 @@ const createCommands = (clearCompleted: command('clearCompletedQueueItems'),markBackendCancelled: command('markQueueItemBackendCancelled'),markBackendSubmitted: command('markQueueItemBackendSubmitted'),+ recordSubmissionRetry: command('recordQueueItemSubmissionRetry'),setCancellationPending: command('setQueueItemCancellationPending'),setLocalRecoveryState: command('setQueueItemLocalRecoveryState'),routePartialResults: command('routeQueueItemPartialResults'),diff --git a/tests/test_node_graph.py b/tests/test_node_graph.pyindex e33727f03d..5fdf76645f 100644--- a/tests/test_node_graph.py+++ b/tests/test_node_graph.py@@ -61,6 +61,7 @@ from tests.test_nodes import (PromptTestInvocation,PromptTestInvocationOutput,TextToImageTestInvocation,+ TypeFormCollectionTestInvocation,UnionCollectionTestInvocation,UnionItemCollectionTestInvocation,get_single_output_from_session,@@ -1237,6 +1238,149 @@ def test_batch_with_literal_collector_items_is_validated_without_type_error():Batch.model_validate({"graph": graph})+def _collect_type_form_items(graph: Graph, type_form_field: str, other_item: BaseInvocation) -> None:+ graph.add_node(TypeFormCollectionTestInvocation(id="type_forms"))+ graph.add_node(other_item)+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("type_forms", type_form_field, "collect", "item"))+ graph.add_edge(create_edge(other_item.id, "value", "collect", "item"))+++def test_graph_collector_accepts_union_items_with_a_member_item_for_a_union_collection():+ # Union items next to another typed item used to reach issubclass() with the union, which+ # enqueue_batch returned as a 500.+ graph = Graph()+ _collect_type_form_items(graph, "union_items", IntegerInvocation(id="other"))+ graph.add_node(TypeFormCollectionTestInvocation(id="consumer"))+ graph.add_edge(create_edge("collect", "collection", "consumer", "union_items"))+ assert graph.is_valid()+++def test_graph_collector_rejects_union_items_for_a_collection_of_one_member():+ graph = Graph()+ _collect_type_form_items(graph, "union_items", IntegerInvocation(id="other"))+ graph.add_node(IntegerCollectionInvocation(id="ints"))+ with pytest.raises(InvalidEdgeError, match="matching type"):+ graph.add_edge(create_edge("collect", "collection", "ints", "collection"))+++def test_graph_collector_accepts_union_items_whose_members_subclass_the_collection_members():+ graph = Graph()+ _collect_type_form_items(graph, "derived_union_items", DerivedFieldTestInvocation(id="other"))+ graph.add_node(UnionItemCollectionTestInvocation(id="consumer"))+ graph.add_edge(create_edge("collect", "collection", "consumer", "value"))+ assert graph.is_valid()+++ ("type_form_field", "other_item"),+ [+ pytest.param("union_items", FloatInvocation(id="other"), id="union-and-non-member"),+ pytest.param("nested_items", IntegerInvocation(id="other"), id="generic-and-class"),+ pytest.param("optional_nested_items", IntegerInvocation(id="other"), id="optional-generic-and-class"),+ ],+)+def test_graph_collector_rejects_unrelated_type_form_items_as_mixed_types(+ type_form_field: str, other_item: BaseInvocation+):+ graph = Graph()+ with pytest.raises(InvalidEdgeError, match="single type"):+ _collect_type_form_items(graph, type_form_field, other_item)+++def _collect_type_form_collection(graph: Graph, type_form_field: str = "literal_items") -> None:+ graph.add_node(TypeFormCollectionTestInvocation(id="type_forms"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("type_forms", type_form_field, "collect", "collection"))+++ ("type_form_field", "consumer", "field"),+ [+ pytest.param(+ "literal_items",+ TypeFormCollectionTestInvocation(id="consumer"),+ "wider_literal_items",+ id="literal-superset",+ ),+ pytest.param(+ "literal_items", StringCollectionInvocation(id="consumer"), "collection", id="class-of-every-value"+ ),+ # Each value of `Literal["a", 1]` fits a different member of `int | str`.+ pytest.param(+ "mixed_literal_items",+ TypeFormCollectionTestInvocation(id="consumer"),+ "union_items",+ id="literal-values-across-union-members",+ ),+ # bool subclasses int, and pydantic accepts `True` for `int`.+ pytest.param(+ "true_literal_items", IntegerCollectionInvocation(id="consumer"), "collection", id="bool-into-int"+ ),+ pytest.param(+ "nested_items",+ TypeFormCollectionTestInvocation(id="consumer"),+ "nested_items",+ id="same-parameterized-generic",+ ),+ ],+)+def test_graph_collector_accepts_collection_items_for_a_collection_holding_every_value(+ type_form_field: str, consumer: BaseInvocation, field: str+):+ graph = Graph()+ _collect_type_form_collection(graph, type_form_field)+ graph.add_node(consumer)+ graph.add_edge(create_edge("collect", "collection", "consumer", field))+ assert graph.is_valid()+++def test_graph_collector_rejects_literal_collection_items_for_a_collection_missing_a_value():+ graph = Graph()+ _collect_type_form_collection(graph)+ graph.add_node(TypeFormCollectionTestInvocation(id="consumer"))+ with pytest.raises(InvalidEdgeError, match="matching type"):+ graph.add_edge(create_edge("collect", "collection", "consumer", "narrower_literal_items"))+++def test_graph_collector_accepts_literal_collection_items_with_an_item_of_their_values_type():+ graph = Graph()+ _collect_type_form_collection(graph)+ graph.add_node(StringInvocation(id="string"))+ graph.add_node(StringCollectionInvocation(id="strings"))+ graph.add_edge(create_edge("string", "value", "collect", "item"))+ graph.add_edge(create_edge("collect", "collection", "strings", "collection"))+ assert graph.is_valid()+++def test_batch_with_union_collector_items_is_validated_without_type_error():+ graph = {+ "id": "g",+ "nodes": {+ "type_forms": {"id": "type_forms", "type": "test_type_form_collection"},+ "int": {"id": "int", "type": "integer"},+ "collect": {"id": "collect", "type": "collect"},+ "ints": {"id": "ints", "type": "integer_collection"},+ },+ "edges": [+ {+ "source": {"node_id": "type_forms", "field": "union_items"},+ "destination": {"node_id": "collect", "field": "item"},+ },+ {+ "source": {"node_id": "int", "field": "value"},+ "destination": {"node_id": "collect", "field": "item"},+ },+ {+ "source": {"node_id": "collect", "field": "collection"},+ "destination": {"node_id": "ints", "field": "collection"},+ },+ ],+ }+ with pytest.raises(ValidationError, match="matching type"):+ Batch.model_validate({"graph": graph})++def test_graph_rejects_mixed_if_branch_types_for_collector_items():graph = Graph()string_value = StringInvocation(id="string", value="text")diff --git a/tests/test_nodes.py b/tests/test_nodes.pyindex d826041ed1..1738537ee5 100644--- a/tests/test_nodes.py+++ b/tests/test_nodes.py@@ -193,6 +193,30 @@ class UnionItemCollectionTestInvocation(BaseInvocation):return PromptCollectionTestInvocationOutput(collection=[])+@invocation_output("test_type_form_collection_output")+class TypeFormCollectionTestInvocationOutput(BaseInvocationOutput):+ """Collections whose item annotations are unions or parameterized generics, as custom nodes may declare."""++ union_items: list[int | str] = OutputField(default=[])+ derived_union_items: list[Union[DerivedTestField, str]] = OutputField(default=[])+ nested_items: list[list[int]] = OutputField(default=[])+ optional_nested_items: list[Optional[list[int]]] = OutputField(default=[])+ literal_items: list[Literal["a", "b"]] = OutputField(default=[])+ mixed_literal_items: list[Literal["a", 1]] = OutputField(default=[])+ true_literal_items: list[Literal[True]] = OutputField(default=[])+++@invocation("test_type_form_collection", version="1.0.0")+class TypeFormCollectionTestInvocation(BaseInvocation):+ union_items: list[int | str] = InputField(default=[])+ nested_items: list[list[int]] = InputField(default=[])+ wider_literal_items: list[Literal["a", "b", "c"]] = InputField(default=[])+ narrower_literal_items: list[Literal["a"]] = InputField(default=[])++ def invoke(self, context: InvocationContext) -> TypeFormCollectionTestInvocationOutput:+ return TypeFormCollectionTestInvocationOutput()++@invocation("test_pep604_union_item_collection", version="1.0.0")class Pep604UnionItemCollectionTestInvocation(BaseInvocation):value: list[BaseTestField | str] = InputField(default=[])