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
feat(webv2): expand workbench state for runtime features
joshistoastda5dd80cc722
diff --git a/invokeai/frontend/webv2/src/theme/themes.ts b/invokeai/frontend/webv2/src/theme/themes.tsnew file mode 100644index 0000000000..96f2dce493--- /dev/null+++ b/invokeai/frontend/webv2/src/theme/themes.ts@@ -0,0 +1,234 @@+import type { WorkbenchThemeId } from '../workbench/types';++/**+ * A single, mode-agnostic set of concrete color values that fully describes one+ * workbench theme. Every theme provides the same slots so the semantic-token+ * builder in `system.ts` can generate a uniform token contract across themes.+ *+ * Components never read these slots directly — they consume the semantic tokens+ * (`bg.surface`, `fg.muted`, `accent.invoke`, …) that map onto them. Adding a new+ * theme is therefore a matter of adding one entry here; no component changes.+ */+export interface ThemeColors {+ /** App backdrop behind every panel. */+ shell: string;+ /** Default raised panel / rail surface. */+ surface: string;+ /** Slightly lifted surface (top bar, headers, popovers). */+ surfaceRaised: string;+ /** Center work-area background. */+ center: string;+ /** Canvas viewport background. */+ canvas: string;+ /** Inset / control surface inside panels. */+ panel: string;+ /** Stroke around the panel surface. */+ panelStroke: string;+ /** Hairline divider color. */+ line: string;+ /** Stronger divider / emphasized border. */+ lineStrong: string;+ /** Canvas dot-grid color. */+ dot: string;+ /** Primary text. */+ fg: string;+ /** Secondary text. */+ fgMuted: string;+ /** Tertiary / disabled text. */+ fgSubtle: string;+ /** Primary action (Invoke) color. */+ accent: string;+ /** Foreground used on top of `accent`. */+ accentFg: string;+ /** Muted accent surface (active widget chip background). */+ accentMuted: string;+ /** Foreground used on top of `accentMuted`. */+ accentMutedFg: string;+ /** Secondary / selection accent (queue, active rail). */+ active: string;+ /** Foreground used on top of `active`. */+ activeFg: string;+ /** Destructive / error foreground. */+ danger: string;+}++export interface ThemeDefinition {+ id: WorkbenchThemeId;+ label: string;+ description: string;+ /** Native color-scheme hint for form controls, scrollbars, and `<select>` popups. */+ colorScheme: 'dark' | 'light';+ colors: ThemeColors;+}++/** The default theme. Its palette is emitted as the semantic-token `base` value. */+export const DEFAULT_THEME_ID: WorkbenchThemeId = 'dark';++const dark: ThemeColors = {+ shell: '#141514',+ surface: '#161716',+ surfaceRaised: '#181918',+ center: '#1a1b1a',+ canvas: '#1c1d1c',+ panel: '#282928',+ panelStroke: '#303330',+ line: '#2e312d',+ lineStrong: '#343832',+ dot: '#343734',+ fg: '#d7dec7',+ fgMuted: '#a9afa1',+ fgSubtle: '#6f756a',+ accent: '#cbff63',+ accentFg: '#10160b',+ accentMuted: '#33372a',+ accentMutedFg: '#dfff8c',+ active: '#59cfff',+ activeFg: '#081218',+ danger: '#ff6b6b',+};++const light: ThemeColors = {+ shell: '#eef0eb',+ surface: '#ffffff',+ surfaceRaised: '#f8faf5',+ center: '#e7eae3',+ canvas: '#dfe3da',+ panel: '#f3f5ef',+ panelStroke: '#d2d7c9',+ line: '#e0e4da',+ lineStrong: '#c7cdbb',+ dot: '#cdd2c4',+ fg: '#1a1d16',+ fgMuted: '#565c4d',+ fgSubtle: '#8b9182',+ accent: '#69a417',+ accentFg: '#0d1604',+ accentMuted: '#dcecbf',+ accentMutedFg: '#39520f',+ active: '#2563eb',+ activeFg: '#ffffff',+ danger: '#c33d3d',+};++const forest: ThemeColors = {+ shell: '#0c120c',+ surface: '#0f160f',+ surfaceRaised: '#121b12',+ center: '#101810',+ canvas: '#0d150d',+ panel: '#1a271a',+ panelStroke: '#28401f',+ line: '#1d2c1c',+ lineStrong: '#2c4528',+ dot: '#2a4127',+ fg: '#d2e8c6',+ fgMuted: '#94ac88',+ fgSubtle: '#5f7556',+ accent: '#84d65a',+ accentFg: '#08160a',+ accentMuted: '#213520',+ accentMutedFg: '#bdeaa3',+ active: '#3fb6a0',+ activeFg: '#04140f',+ danger: '#e8775a',+};++const mono: ThemeColors = {+ shell: '#121212',+ surface: '#161616',+ surfaceRaised: '#1b1b1b',+ center: '#181818',+ canvas: '#1c1c1c',+ panel: '#272727',+ panelStroke: '#343434',+ line: '#2b2b2b',+ lineStrong: '#3a3a3a',+ dot: '#353535',+ fg: '#e8e8e8',+ fgMuted: '#a3a3a3',+ fgSubtle: '#6e6e6e',+ accent: '#e8e8e8',+ accentFg: '#121212',+ accentMuted: '#2e2e2e',+ accentMutedFg: '#d6d6d6',+ active: '#9a9a9a',+ activeFg: '#121212',+ danger: '#d68a8a',+};++const ultradark: ThemeColors = {+ shell: '#000000',+ surface: '#050505',+ surfaceRaised: '#0a0a0a',+ center: '#070707',+ canvas: '#0b0b0b',+ panel: '#141414',+ panelStroke: '#202020',+ line: '#181818',+ lineStrong: '#262626',+ dot: '#1f1f1f',+ fg: '#d7dec7',+ fgMuted: '#8f968a',+ fgSubtle: '#585d52',+ accent: '#cbff63',+ accentFg: '#0a0f05',+ accentMuted: '#1f2614',+ accentMutedFg: '#cdf08a',+ active: '#59cfff',+ activeFg: '#05121a',+ danger: '#ff6b6b',+};++/**+ * Theme registry. Order here is the display order in the Settings picker.+ * `THEMES` is the single source of truth consumed by both the token builder+ * and the settings UI.+ */+export const THEMES: ThemeDefinition[] = [+ {+ id: 'dark',+ label: 'Dark',+ description: 'The default lime-on-charcoal workbench.',+ colorScheme: 'dark',+ colors: dark,+ },+ {+ id: 'light',+ label: 'Light',+ description: 'Bright, high-contrast surfaces for daylight work.',+ colorScheme: 'light',+ colors: light,+ },+ {+ id: 'forest',+ label: 'Forest',+ description: 'Deep greens with a leafy accent.',+ colorScheme: 'dark',+ colors: forest,+ },+ {+ id: 'mono',+ label: 'Mono',+ description: 'Neutral grayscale with no color cast.',+ colorScheme: 'dark',+ colors: mono,+ },+ {+ id: 'ultradark',+ label: 'Ultra Dark',+ description: 'Pure-black OLED surfaces for low-light rooms.',+ colorScheme: 'dark',+ colors: ultradark,+ },+];++export const THEMES_BY_ID: Record<WorkbenchThemeId, ThemeDefinition> = THEMES.reduce(+ (accumulator, theme) => {+ accumulator[theme.id] = theme;+ return accumulator;+ },+ {} as Record<WorkbenchThemeId, ThemeDefinition>+);++export const isWorkbenchThemeId = (value: unknown): value is WorkbenchThemeId =>+ typeof value === 'string' && Object.prototype.hasOwnProperty.call(THEMES_BY_ID, value);diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.ts b/invokeai/frontend/webv2/src/workbench/generation/api.tsnew file mode 100644index 0000000000..75293502cf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/api.ts@@ -0,0 +1,150 @@+import type { BackendGraphContract } from '../types';+import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, MainModelConfig, QueueItemDTO } from './types';++const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';+const POLL_INTERVAL_MS = 1500;+const POLL_TIMEOUT_MS = 15 * 60 * 1000;++const buildUrl = (path: string): string => `${API_BASE_URL}${path}`;++const sleep = (ms: number): Promise<void> =>+ new Promise((resolve) => {+ window.setTimeout(resolve, ms);+ });++const assertOk = async (response: Response): Promise<Response> => {+ if (response.ok) {+ return response;+ }++ const text = await response.text();+ throw new Error(text || `${response.status} ${response.statusText}`);+};++const absolutizeImageUrl = (url: string): string => {+ if (!API_BASE_URL || url.startsWith('http://') || url.startsWith('https://')) {+ return url;+ }++ return new URL(url, API_BASE_URL).toString();+};++export const listMainModels = async (): Promise<MainModelConfig[]> => {+ const response = await assertOk(await fetch(buildUrl('/api/v2/models/?model_type=main')));+ const body = (await response.json()) as { models?: MainModelConfig[] };++ return body.models ?? [];+};++export const enqueueGenerateGraph = async (request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult> => {+ const body = {+ batch: {+ data: [+ [+ { field_name: 'value', items: [request.seed], node_path: request.seedNodeId },+ { field_name: 'value', items: [request.positivePrompt], node_path: request.positivePromptNodeId },+ { field_name: 'value', items: [request.negativePrompt], node_path: request.negativePromptNodeId },+ ],+ ],+ destination: request.destination,+ graph: request.graph satisfies BackendGraphContract,+ origin: `webv2:${request.sourceQueueItemId}`,+ runs: request.batchCount,+ },+ prepend: false,+ };++ const response = await assertOk(+ await fetch(buildUrl('/api/v1/queue/default/enqueue_batch'), {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ })+ );+ const result = (await response.json()) as { item_ids?: number[] };++ return { itemIds: result.item_ids ?? [] };+};++const getQueueItem = async (itemId: number): Promise<QueueItemDTO> => {+ const response = await assertOk(await fetch(buildUrl(`/api/v1/queue/default/i/${itemId}`)));++ return (await response.json()) as QueueItemDTO;+};++const getImageDTO = async (imageName: string, queuedAt: string, sourceQueueItemId: string): Promise<ImageDTO> => {+ const response = await assertOk(await fetch(buildUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}`)));+ const body = (await response.json()) as {+ image_name: string;+ image_url: string;+ thumbnail_url: string;+ width: number;+ height: number;+ is_intermediate: boolean;+ };++ return {+ height: body.height,+ imageName: body.image_name,+ imageUrl: absolutizeImageUrl(body.image_url),+ isIntermediate: body.is_intermediate,+ queuedAt,+ sourceQueueItemId,+ thumbnailUrl: absolutizeImageUrl(body.thumbnail_url),+ width: body.width,+ };+};++const getResultImageNames = (queueItem: QueueItemDTO): string[] => {+ const imageNames = new Set<string>();++ for (const result of Object.values(queueItem.session.results)) {+ if (!result || typeof result !== 'object') {+ continue;+ }++ const image = (result as { image?: { image_name?: unknown } }).image;+ if (typeof image?.image_name === 'string') {+ imageNames.add(image.image_name);+ }+ }++ return [...imageNames];+};++export const waitForQueueItemImages = async (+ itemId: number,+ sourceQueueItemId: string,+ queuedAt: string+): Promise<ImageDTO[]> => {+ const startedAt = Date.now();++ while (Date.now() - startedAt < POLL_TIMEOUT_MS) {+ const queueItem = await getQueueItem(itemId);++ if (queueItem.status === 'completed') {+ const imageNames = getResultImageNames(queueItem);+ return Promise.all(imageNames.map((imageName) => getImageDTO(imageName, queuedAt, sourceQueueItemId)));+ }++ if (queueItem.status === 'failed' || queueItem.status === 'canceled') {+ throw new Error(queueItem.error_message ?? queueItem.error_type ?? `Queue item ${itemId} ${queueItem.status}.`);+ }++ await sleep(POLL_INTERVAL_MS);+ }++ throw new Error(`Timed out waiting for queue item ${itemId}.`);+};++export const cancelQueueItems = async (itemIds: number[]): Promise<void> => {+ await Promise.all(+ itemIds.map(async (itemId) => {+ await assertOk(+ await fetch(buildUrl(`/api/v1/queue/default/i/${itemId}/cancel`), {+ method: 'PUT',+ })+ );+ })+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.tsnew file mode 100644index 0000000000..4e6bada09f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts@@ -0,0 +1,223 @@+import type {+ BackendGraphContract,+ BackendGraphEdgeContract,+ BackendInvocationContract,+ ResultDestination,+} from '../types';+import type { CompiledGenerateGraph, GenerateSettings, MainModelConfig, SupportedGenerateBase } from './types';++const now = (): string => new Date().toISOString();++const createId = (prefix: string): string =>+ `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;++const getNumber = (value: number | null | undefined, fallback: number): number =>+ Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;++const clampDimension = (value: number): number => Math.max(64, Math.round(value / 8) * 8);++export const isSupportedGenerateModel = (+ model: MainModelConfig+): model is MainModelConfig & { base: SupportedGenerateBase } =>+ model.type === 'main' && (model.base === 'sdxl' || model.base === 'sd-1' || model.base === 'sd-2');++export const getDefaultGenerateSettings = (model?: MainModelConfig): GenerateSettings => {+ const defaults = model?.default_settings;++ return {+ batchCount: 1,+ cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),+ cfgScale: getNumber(defaults?.cfg_scale, 7),+ height: clampDimension(getNumber(defaults?.height, 1024)),+ modelKey: model?.key ?? '',+ negativePrompt: '',+ positivePrompt: '',+ scheduler: defaults?.scheduler ?? 'euler_a',+ seed: Math.floor(Math.random() * 4_294_967_295),+ shouldRandomizeSeed: true,+ steps: Math.max(1, Math.round(getNumber(defaults?.steps, 30))),+ width: clampDimension(getNumber(defaults?.width, 1024)),+ };+};++export const getSettingsWithModelDefaults = (settings: GenerateSettings, model: MainModelConfig): GenerateSettings => {+ const modelDefaults = getDefaultGenerateSettings(model);++ return {+ ...settings,+ cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier,+ cfgScale: modelDefaults.cfgScale,+ height: modelDefaults.height,+ modelKey: model.key,+ scheduler: modelDefaults.scheduler,+ steps: modelDefaults.steps,+ width: modelDefaults.width,+ };+};++const addNode = <T extends BackendInvocationContract>(graph: BackendGraphContract, node: T): T => {+ graph.nodes[node.id] = {+ is_intermediate: true,+ use_cache: true,+ ...node,+ };++ return graph.nodes[node.id] as T;+};++const addEdge = (+ graph: BackendGraphContract,+ source: BackendInvocationContract,+ sourceField: string,+ destination: BackendInvocationContract,+ destinationField: string+): BackendGraphEdgeContract => {+ const edge = {+ destination: { field: destinationField, node_id: destination.id },+ source: { field: sourceField, node_id: source.id },+ };+ graph.edges.push(edge);++ return edge;+};++const addMetadata = (+ graph: BackendGraphContract,+ outputNode: BackendInvocationContract,+ settings: GenerateSettings,+ model: MainModelConfig,+ generationMode: string+) => {+ const metadata = addNode(graph, {+ cfg_scale: settings.cfgScale,+ cfg_rescale_multiplier: settings.cfgRescaleMultiplier,+ generation_mode: generationMode,+ height: settings.height,+ id: createId('core_metadata'),+ model,+ rand_device: 'cuda',+ scheduler: settings.scheduler,+ steps: settings.steps,+ type: 'core_metadata',+ width: settings.width,+ });++ addEdge(graph, graph.nodes.seed, 'value', metadata, 'seed');+ addEdge(graph, graph.nodes.positive_prompt, 'value', metadata, 'positive_prompt');+ addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');+ addEdge(graph, metadata, 'metadata', outputNode, 'metadata');+};++const buildSDGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };+ const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';+ const compelType = model.base === 'sdxl' ? 'sdxl_compel_prompt' : 'compel';++ const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });+ const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });+ const seed = addNode(graph, { id: 'seed', type: 'integer' });+ const modelLoader = addNode(graph, { id: 'model_loader', model, type: modelLoaderType });+ const posCond = addNode(graph, { id: 'pos_cond', type: compelType });+ const negCond = addNode(graph, { id: 'neg_cond', type: compelType });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCondCollect = addNode(graph, { id: 'neg_cond_collect', type: 'collect' });+ const noise = addNode(graph, {+ height: settings.height,+ id: 'noise',+ type: 'noise',+ use_cpu: false,+ width: settings.width,+ });+ const denoise = addNode(graph, {+ cfg_rescale_multiplier: settings.cfgRescaleMultiplier,+ cfg_scale: settings.cfgScale,+ denoising_end: 1,+ denoising_start: 0,+ id: 'denoise_latents',+ scheduler: settings.scheduler,+ steps: settings.steps,+ type: 'denoise_latents',+ });+ const output = addNode(graph, {+ fp32: false,+ id: 'canvas_output',+ is_intermediate: outputIsIntermediate,+ type: 'l2i',+ use_cache: false,+ });++ if (model.base === 'sdxl') {+ addEdge(graph, modelLoader, 'clip', posCond, 'clip');+ addEdge(graph, modelLoader, 'clip2', posCond, 'clip2');+ addEdge(graph, modelLoader, 'clip', negCond, 'clip');+ addEdge(graph, modelLoader, 'clip2', negCond, 'clip2');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, positivePrompt, 'value', posCond, 'style');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'style');+ } else {+ const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: 0, type: 'clip_skip' });++ addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');+ addEdge(graph, clipSkip, 'clip', posCond, 'clip');+ addEdge(graph, clipSkip, 'clip', negCond, 'clip');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ }++ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', noise, 'seed');+ addEdge(graph, modelLoader, 'unet', denoise, 'unet');+ addEdge(graph, noise, 'noise', denoise, 'noise');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img');++ return graph;+};++const toGraphContract = (backendGraph: BackendGraphContract, label: string) => ({+ backendGraph,+ edges: backendGraph.edges.map((edge, index) => ({+ id: `edge-${index}`,+ sourceField: edge.source.field,+ sourceNodeId: edge.source.node_id,+ targetField: edge.destination.field,+ targetNodeId: edge.destination.node_id,+ })),+ id: backendGraph.id,+ label,+ nodes: Object.values(backendGraph.nodes).map(({ id, type, ...inputs }) => ({ id, inputs, type })),+ updatedAt: now(),+ version: 1 as const,+});++export const compileGenerateGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ destination: ResultDestination+): CompiledGenerateGraph => {+ if (!isSupportedGenerateModel(model)) {+ throw new Error(`${model.base} generation is not wired into the V7 Generate widget yet.`);+ }++ const backendGraph = buildSDGraph(settings, model, destination === 'canvas');++ return {+ backendGraph,+ graph: toGraphContract(backendGraph, `${model.name} txt2img`),+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ };+};++export const resolveGenerateSeed = (settings: GenerateSettings): number =>+ settings.shouldRandomizeSeed ? Math.floor(Math.random() * 4_294_967_295) : settings.seed;diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.tsnew file mode 100644index 0000000000..638c9ba273--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts@@ -0,0 +1,79 @@+import type { BackendGraphContract, GeneratedImageContract, GraphContract, ResultDestination } from '../types';++export type SupportedGenerateBase = 'sd-1' | 'sd-2' | 'sdxl';++export type MainModelConfig = {+ key: string;+ name: string;+ base: string;+ type: 'main';+ format?: string;+ default_settings?: {+ scheduler?: string | null;+ steps?: number | null;+ cfg_scale?: number | null;+ cfg_rescale_multiplier?: number | null;+ width?: number | null;+ height?: number | null;+ vae_precision?: string | null;+ } | null;+ [key: string]: unknown;+};++export interface GenerateSettings {+ batchCount: number;+ modelKey: string;+ positivePrompt: string;+ negativePrompt: string;+ width: number;+ height: number;+ steps: number;+ cfgScale: number;+ cfgRescaleMultiplier: number;+ scheduler: string;+ seed: number;+ shouldRandomizeSeed: boolean;+}++export interface GenerateWidgetValues extends GenerateSettings {+ model: MainModelConfig;+}++export interface CompiledGenerateGraph {+ backendGraph: BackendGraphContract;+ graph: GraphContract;+ negativePromptNodeId: string;+ positivePromptNodeId: string;+ seedNodeId: string;+}++export interface EnqueueGenerateResult {+ itemIds: number[];+}++export interface QueueItemDTO {+ item_id: number;+ status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';+ error_type?: string | null;+ error_message?: string | null;+ session: {+ results: Record<string, unknown>;+ };+}++export interface EnqueueGenerateRequest {+ batchCount: number;+ destination: ResultDestination;+ graph: BackendGraphContract;+ negativePrompt: string;+ negativePromptNodeId: string;+ positivePrompt: string;+ positivePromptNodeId: string;+ seed: number;+ seedNodeId: string;+ sourceQueueItemId: string;+}++export interface ImageDTO extends GeneratedImageContract {+ isIntermediate: boolean;+}diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex ce317bcdcc..7e8d0332bf 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -30,7 +30,7 @@ export interface ResultDestinationMeta {export const invocationSources: InvocationSourceMeta[] = [{ id: 'generate', label: 'Generate', available: true },- { id: 'project-graph', label: 'Workflow', available: true },+ { id: 'project-graph', label: 'Workflow', available: false },{ id: 'upscale', label: 'Upscale', available: false },{ id: 'canvas-fill', label: 'Canvas Fill', available: false },];@@ -71,6 +71,27 @@ const sourceWidgetIds: Partial<Record<InvocationSourceId, WidgetId>> = {const isWidgetMounted = (project: Project, widgetId: WidgetId): boolean =>Object.values(project.widgetRegions).some((region) => region.enabledWidgetIds.includes(widgetId));+const hasGenerateSnapshotInputs = (project: Project): boolean => {+ const values = project.widgetStates.generate.values;+ const model = values.model;+ const hasFiniteNumber = (key: string) => typeof values[key] === 'number' && Number.isFinite(values[key]);++ return (+ typeof values.modelKey === 'string' &&+ typeof values.positivePrompt === 'string' &&+ typeof values.negativePrompt === 'string' &&+ hasFiniteNumber('width') &&+ hasFiniteNumber('height') &&+ hasFiniteNumber('steps') &&+ hasFiniteNumber('cfgScale') &&+ hasFiniteNumber('cfgRescaleMultiplier') &&+ typeof values.scheduler === 'string' &&+ hasFiniteNumber('seed') &&+ typeof values.shouldRandomizeSeed === 'boolean' &&+ Boolean(model && typeof model === 'object' && (model as Record<string, unknown>).type === 'main')+ );+};+export const isResultDestinationAvailable = (destination: ResultDestination): boolean =>validDestinationIds.has(destination);@@ -83,10 +104,14 @@ export const resolveInvocationRoute = (const destination = route.destination;const sourceWidgetId = sourceWidgetIds[sourceId];const sourceValid =- isInvocationSourceAvailable(sourceId) && (!sourceWidgetId || isWidgetMounted(project, sourceWidgetId));+ isInvocationSourceAvailable(sourceId) &&+ (!sourceWidgetId || isWidgetMounted(project, sourceWidgetId)) &&+ (sourceId !== 'generate' || hasGenerateSnapshotInputs(project));const destinationValid = isResultDestinationAvailable(destination);const validationMessage = !sourceValid- ? `${getSourceLabel(sourceId)} is not an available invocation source.`+ ? sourceId === 'generate'+ ? 'Generate needs a supported model before it can be invoked.'+ : `${getSourceLabel(sourceId)} is not an available invocation source.`: !destinationValid? `${getDestinationLabel(destination)} is not an available result destination.`: undefined;diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.tsindex 1b22ac49a0..37c60722da 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts@@ -1,6 +1,7 @@-import type { WorkbenchPersistenceSnapshot, WorkbenchState } from './types';+import type { Project, WorkbenchPersistenceSnapshot, WorkbenchState } from './types';const STORAGE_KEY = 'invokeai:v7:webv2:workbench';+const WORKBENCH_SCHEMA_VERSION = 1;export interface WorkbenchPersistenceService {loadWorkbench(): Promise<WorkbenchPersistenceSnapshot | null>;@@ -8,14 +9,49 @@ export interface WorkbenchPersistenceService {clearWorkbench(): Promise<void>;}+export interface ProjectPersistenceService {+ loadProjects(): Promise<Project[]>;+ saveProjects(projects: Project[]): Promise<Project[]>;+ clearProjects(): Promise<void>;+}+const isBrowser = (): boolean => typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';const createSnapshot = (state: WorkbenchState): WorkbenchPersistenceSnapshot => ({savedAt: new Date().toISOString(),state,- version: 1,+ version: WORKBENCH_SCHEMA_VERSION,});+const isWorkbenchState = (value: unknown): value is WorkbenchState => {+ if (!value || typeof value !== 'object') {+ return false;+ }++ const record = value as Record<string, unknown>;++ return Array.isArray(record.projects) && typeof record.activeProjectId === 'string';+};++export const migrateWorkbenchPersistenceSnapshot = (value: unknown): WorkbenchPersistenceSnapshot | null => {+ if (!value || typeof value !== 'object') {+ return null;+ }++ const record = value as Partial<WorkbenchPersistenceSnapshot> & { schemaVersion?: number };+ const version = record.version ?? record.schemaVersion;++ if (version !== WORKBENCH_SCHEMA_VERSION || !isWorkbenchState(record.state)) {+ return null;+ }++ return {+ savedAt: typeof record.savedAt === 'string' ? record.savedAt : new Date().toISOString(),+ state: record.state,+ version: WORKBENCH_SCHEMA_VERSION,+ };+};+export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {clearWorkbench() {if (!isBrowser()) {@@ -37,7 +73,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {return Promise.resolve(null);}- return Promise.resolve(JSON.parse(value) as WorkbenchPersistenceSnapshot);+ return Promise.resolve(migrateWorkbenchPersistenceSnapshot(JSON.parse(value)));},saveWorkbench(state) {const snapshot = createSnapshot(state);@@ -51,3 +87,25 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {return Promise.resolve(snapshot);},};++export const localStorageProjectPersistence: ProjectPersistenceService = {+ async clearProjects() {+ await localStorageWorkbenchPersistence.clearWorkbench();+ },+ async loadProjects() {+ const snapshot = await localStorageWorkbenchPersistence.loadWorkbench();++ return snapshot?.state.projects ?? [];+ },+ async saveProjects(projects) {+ const snapshot = await localStorageWorkbenchPersistence.loadWorkbench();++ if (!snapshot) {+ return projects;+ }++ await localStorageWorkbenchPersistence.saveWorkbench({ ...snapshot.state, projects });++ return projects;+ },+};diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex c9667b2b5b..52e2b15781 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -9,11 +9,14 @@ export type GraphId = string;export type WidgetId =| 'autosave-status'| 'canvas'+ | 'diagnostics'| 'gallery'| 'generate'| 'history-controls'| 'layout-actions'| 'layers'+ | 'notifications'+ | 'preview'| 'queue'| 'server-status'| 'version-status'@@ -23,7 +26,12 @@ export type WorkbenchRegion = 'left' | 'right' | 'center' | 'bottom' | 'dialog'export type QueueItemStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';-export type ProjectEventType = 'project-created' | 'layout-updated' | 'invocation-updated' | 'queue-submitted';+export type ProjectEventType =+ | 'project-created'+ | 'layout-updated'+ | 'invocation-updated'+ | 'queue-submitted'+ | 'canvas-layer-accepted';export interface GraphNodeContract {id: string;@@ -46,6 +54,30 @@ export interface GraphContract {nodes: GraphNodeContract[];edges: GraphEdgeContract[];updatedAt: string;+ backendGraph?: BackendGraphContract;+}++export interface BackendInvocationContract {+ id: string;+ type: string;+ [key: string]: unknown;+}++export interface BackendGraphEdgeContract {+ source: {+ node_id: string;+ field: string;+ };+ destination: {+ node_id: string;+ field: string;+ };+}++export interface BackendGraphContract {+ id: string;+ nodes: Record<string, BackendInvocationContract>;+ edges: BackendGraphEdgeContract[];}export interface WidgetStateContract {@@ -75,6 +107,9 @@ export interface WidgetViewProps {export type WidgetView = ComponentType<WidgetViewProps>;+export type WidgetHeaderActions = ComponentType<WidgetViewProps>;+export type WidgetFooter = ComponentType<WidgetViewProps>;+export interface WidgetLabelProps {region: WorkbenchRegion;presentation?: 'compact' | 'expanded' | 'tooltip';@@ -92,7 +127,13 @@ export interface WidgetManifest {regions: WorkbenchRegion[];icon: WidgetIconId;bottomPanel?: 'expandable' | 'tooltip';+ centerPlacement?: 'toolbar' | 'view';+ chrome?: {+ header?: 'hidden' | 'visible';+ };view?: WidgetView;+ headerActions?: WidgetHeaderActions;+ footer?: WidgetFooter;graphBearing?: {sourceId: InvocationSourceId;defaultGraphId: GraphId;@@ -117,12 +158,53 @@ export interface WidgetFailure {occurredAt: string;}+export interface GeneratedImageContract {+ imageName: string;+ imageUrl: string;+ thumbnailUrl: string;+ width: number;+ height: number;+ queuedAt: string;+ sourceQueueItemId: string;+}++export interface CanvasPlacementContract {+ x: number;+ y: number;+ width: number;+ height: number;+ opacity: number;+}++export interface CanvasStagingCandidateContract extends GeneratedImageContract {+ placement: CanvasPlacementContract;+}++export interface CanvasRasterLayerContract extends GeneratedImageContract {+ id: string;+ acceptedAt: string;+ label: string;+ placement: CanvasPlacementContract;+}++export interface CanvasDocumentContract {+ version: 1;+ width: number;+ height: number;+ layers: CanvasRasterLayerContract[];+}+export interface CanvasStateContract {version: 1;- layers: string[];+ document: CanvasDocumentContract;stagingArea: {+ sourceQueueItemId?: string;selectedLayerId?: string;pendingImageIds: string[];+ pendingImages: CanvasStagingCandidateContract[];+ selectedImageIndex: number;+ isVisible: boolean;+ areThumbnailsVisible: boolean;};}@@ -207,11 +289,24 @@ export interface WorkbenchState {projects: Project[];activeProjectId: string;errorLog: string[];+ notifications: WorkbenchNotification[];autosave: AutosaveState;account: AccountState;widgetFailures: WidgetFailure[];}+export type WorkbenchNotificationKind = 'error' | 'success' | 'info';++export interface WorkbenchNotification {+ id: string;+ kind: WorkbenchNotificationKind;+ title: string;+ message?: string;+ createdAt: string;+ projectId?: string;+ isRead: boolean;+}+export interface GraphHistorySnapshot {id: string;createdAt: string;@@ -255,6 +350,9 @@ export interface QueueItem {status: QueueItemStatus;cancellable: boolean;snapshot: QueueSubmissionSnapshot;+ backendItemIds?: number[];+ error?: string;+ resultImages?: GeneratedImageContract[];}export interface QueueState {@@ -287,8 +385,23 @@ export interface AutosaveState {error?: string;}+/**+ * Identifier for a workbench color theme. The matching palette lives in+ * `theme/themes.ts`; the active id is applied to `<html data-theme>` so the+ * semantic-token conditions in `theme/system.ts` resolve to the right colors.+ */+export type WorkbenchThemeId = 'dark' | 'light' | 'forest' | 'mono' | 'ultradark';++/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */+export interface WorkbenchPreferences {+ themeId: WorkbenchThemeId;+ reduceMotion: boolean;+ showFocusRegionHighlight: boolean;+}+export interface AccountState {activeLayoutPresetId: LayoutPresetId;+ preferences: WorkbenchPreferences;}export interface WorkbenchPersistenceSnapshot {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 22c03029f6..1adc7fbc41 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -4,10 +4,18 @@ import {isInvocationSourceAvailable,resolveInvocationRoute,} from './invocation';+import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '../theme/themes';+import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';+import type { GenerateWidgetValues, MainModelConfig } from './generation/types';import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';import type {+ CanvasDocumentContract,+ CanvasPlacementContract,CanvasStateContract,CenterViewId,+ CanvasRasterLayerContract,+ CanvasStagingCandidateContract,+ GeneratedImageContract,GraphContract,GraphHistorySnapshot,InvocationRoute,@@ -17,12 +25,16 @@ import type {ProjectLayoutState,ProjectUndoSnapshot,QueueItem,+ QueueItemStatus,ResultDestination,WidgetFailure,WidgetId,WidgetRegion,WidgetRegionState,WidgetStateContract,+ WorkbenchNotification,+ WorkbenchNotificationKind,+ WorkbenchPreferences,WorkbenchState,} from './types';@@ -42,8 +54,26 @@ type WorkbenchAction =| { type: 'toggleRegionWidget'; region: WidgetRegion; widgetId: WidgetId }| { type: 'setRegionWidgetCollapsed'; region: WidgetRegion; isCollapsed: boolean }| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }+ | { type: 'setGenerateSettings'; values: GenerateWidgetValues }+ | { type: 'setGenerateBatchCount'; batchCount: number }| { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean }| { type: 'submitResolvedInvocationSnapshot'; backendSupportsCancellation: boolean; route: InvocationRoute }+ | { type: 'markQueueItemBackendSubmitted'; projectId: string; queueItemId: string; backendItemIds: number[] }+ | { type: 'setQueueItemStatus'; projectId: string; queueItemId: string; status: QueueItemStatus; error?: string }+ | { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }+ | { type: 'setStagedImageIndex'; imageIndex: number }+ | { type: 'cycleStagedImage'; direction: -1 | 1 }+ | { type: 'discardSelectedStagedImage' }+ | { type: 'discardAllStagedImages' }+ | { type: 'toggleCanvasStagingVisibility' }+ | { type: 'toggleCanvasStagingThumbnailsVisibility' }+ | { type: 'selectGalleryImage'; image: GeneratedImageContract }+ | { type: 'selectGalleryBoard'; boardId: string }+ | { type: 'setGalleryView'; galleryView: 'images' | 'assets' }+ | { type: 'setGallerySearchTerm'; searchTerm: string }+ | { type: 'setGalleryImageDensityPercent'; imageDensityPercent: number }+ | { type: 'acceptStagedImage' }+ | { type: 'clearCanvasStaging' }| { type: 'cancelQueueItem'; queueItemId: string }| { type: 'undoProjectChange' }| { type: 'redoProjectChange' }@@ -51,34 +81,185 @@ type WorkbenchAction =| { type: 'autosaveStarted' }| { type: 'autosaveSucceeded'; savedAt: string }| { type: 'autosaveFailed'; error: string }+ | { type: 'markAllNotificationsRead' }+ | { type: 'clearNotifications' }+ | { type: 'clearErrorLog' }| { type: 'recordWidgetFailure'; failure: WidgetFailure }+ | { type: 'setPreferences'; preferences: Partial<WorkbenchPreferences> }| { type: 'recordError'; message: string };const HISTORY_LIMIT = 40;const INITIAL_PROJECT_COUNT = 3;const ERROR_LOG_LIMIT = 5;+const NOTIFICATION_LIMIT = 100;const MIN_PANEL_SIZE_PX = 180;const MAX_PANEL_SIZE_PX = 520;const MIN_STATUS_PANEL_SIZE_PX = 96;const MAX_STATUS_PANEL_SIZE_PX = 420;+const DEFAULT_CANVAS_DOCUMENT_WIDTH = 1024;+const DEFAULT_CANVAS_DOCUMENT_HEIGHT = 1024;const now = (): string => new Date().toISOString();const createId = (prefix: string): string =>`${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+const createNotification = ({+ kind,+ message,+ projectId,+ title,+}: {+ kind: WorkbenchNotificationKind;+ message?: string;+ projectId?: string;+ title: string;+}): WorkbenchNotification => ({+ createdAt: now(),+ id: createId('notification'),+ isRead: false,+ kind,+ message,+ projectId,+ title,+});++const addNotification = (state: WorkbenchState, notification: WorkbenchNotification): WorkbenchState => ({+ ...state,+ notifications: [notification, ...state.notifications].slice(0, NOTIFICATION_LIMIT),+});+const cloneGraph = (graph: GraphContract): GraphContract => ({...graph,+ backendGraph: graph.backendGraph+ ? {+ ...graph.backendGraph,+ edges: graph.backendGraph.edges.map((edge) => ({+ destination: { ...edge.destination },+ source: { ...edge.source },+ })),+ nodes: Object.fromEntries(Object.entries(graph.backendGraph.nodes).map(([id, node]) => [id, { ...node }])),+ }+ : undefined,edges: graph.edges.map((edge) => ({ ...edge })),nodes: graph.nodes.map((node) => ({ ...node, inputs: { ...node.inputs } })),});+const clonePlacement = (placement: CanvasPlacementContract): CanvasPlacementContract => ({ ...placement });++const createCenteredPlacement = (+ image: Pick<GeneratedImageContract, 'height' | 'width'>,+ document: Pick<CanvasDocumentContract, 'height' | 'width'>+): CanvasPlacementContract => {+ const imageWidth = image.width > 0 ? image.width : document.width;+ const imageHeight = image.height > 0 ? image.height : document.height;+ const scale = Math.min(document.width / imageWidth, document.height / imageHeight);+ const width = Math.round(imageWidth * scale);+ const height = Math.round(imageHeight * scale);++ return {+ height,+ opacity: 1,+ width,+ x: Math.round((document.width - width) / 2),+ y: Math.round((document.height - height) / 2),+ };+};++const createCanvasDocument = (layers: CanvasRasterLayerContract[] = []): CanvasDocumentContract => ({+ height: DEFAULT_CANVAS_DOCUMENT_HEIGHT,+ layers,+ version: 1,+ width: DEFAULT_CANVAS_DOCUMENT_WIDTH,+});++const normalizeLayer = (layer: CanvasRasterLayerContract | string): CanvasRasterLayerContract => {+ if (typeof layer !== 'string') {+ return {+ ...layer,+ placement: layer.placement+ ? clonePlacement(layer.placement)+ : createCenteredPlacement(layer, createCanvasDocument()),+ };+ }++ return {+ acceptedAt: now(),+ height: 0,+ id: layer,+ imageName: layer,+ imageUrl: '',+ label: layer,+ placement: createCenteredPlacement({ height: 0, width: 0 }, createCanvasDocument()),+ queuedAt: now(),+ sourceQueueItemId: 'legacy',+ thumbnailUrl: '',+ width: 0,+ };+};++const normalizeCanvasDocument = (canvas: CanvasStateContract): CanvasDocumentContract => {+ const legacyCanvas = canvas as CanvasStateContract & { layers?: CanvasRasterLayerContract[] };+ const rawDocument = legacyCanvas.document;+ const document = rawDocument ?? createCanvasDocument(legacyCanvas.layers ?? []);++ return {+ height: document.height || DEFAULT_CANVAS_DOCUMENT_HEIGHT,+ layers: (document.layers ?? []).map(normalizeLayer),+ version: 1,+ width: document.width || DEFAULT_CANVAS_DOCUMENT_WIDTH,+ };+};++const normalizeStagingCandidate = (+ image: CanvasStagingCandidateContract | GeneratedImageContract,+ document: CanvasDocumentContract+): CanvasStagingCandidateContract => ({+ ...image,+ placement:+ 'placement' in image && image.placement+ ? clonePlacement(image.placement)+ : createCenteredPlacement(image, document),+});++const clearStagingArea = (stagingArea: CanvasStateContract['stagingArea']): CanvasStateContract['stagingArea'] => ({+ ...stagingArea,+ isVisible: false,+ pendingImageIds: [],+ pendingImages: [],+ selectedImageIndex: 0,+ sourceQueueItemId: undefined,+});++const clampStagedImageIndex = (imageIndex: number, pendingImageCount: number): number => {+ const maxIndex = Math.max(0, pendingImageCount - 1);++ return Math.min(maxIndex, Math.max(0, imageIndex));+};++const cycleStagedImageIndex = (imageIndex: number, pendingImageCount: number, direction: -1 | 1): number => {+ if (pendingImageCount < 2) {+ return 0;+ }++ return (imageIndex + direction + pendingImageCount) % pendingImageCount;+};++const getGalleryImages = (values: Record<string, unknown>): GeneratedImageContract[] =>+ Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];+const cloneCanvas = (canvas: CanvasStateContract): CanvasStateContract => ({- ...canvas,- layers: [...canvas.layers],+ version: 1,+ document: normalizeCanvasDocument(canvas),stagingArea: {...canvas.stagingArea,- pendingImageIds: [...canvas.stagingArea.pendingImageIds],+ pendingImageIds: [...(canvas.stagingArea?.pendingImageIds ?? [])],+ pendingImages: (canvas.stagingArea?.pendingImages ?? []).map((image) =>+ normalizeStagingCandidate(image, normalizeCanvasDocument(canvas))+ ),+ areThumbnailsVisible: canvas.stagingArea?.areThumbnailsVisible ?? true,+ isVisible: canvas.stagingArea?.isVisible ?? (canvas.stagingArea?.pendingImages?.length ?? 0) > 0,+ selectedImageIndex: canvas.stagingArea?.selectedImageIndex ?? 0,},});@@ -89,19 +270,26 @@ const cloneWidgetState = (widgetState: WidgetStateContract): WidgetStateContractconst cloneWidgetStates = (widgetStates: Record<WidgetId, WidgetStateContract>-): Record<WidgetId, WidgetStateContract> => ({- 'autosave-status': cloneWidgetState(widgetStates['autosave-status']),- canvas: cloneWidgetState(widgetStates.canvas),- gallery: cloneWidgetState(widgetStates.gallery),- generate: cloneWidgetState(widgetStates.generate),- 'history-controls': cloneWidgetState(widgetStates['history-controls']),- 'layout-actions': cloneWidgetState(widgetStates['layout-actions']),- layers: cloneWidgetState(widgetStates.layers),- queue: cloneWidgetState(widgetStates.queue),- 'server-status': cloneWidgetState(widgetStates['server-status']),- 'version-status': cloneWidgetState(widgetStates['version-status']),- workflow: cloneWidgetState(widgetStates.workflow),-});+): Record<WidgetId, WidgetStateContract> => {+ const defaultWidgetStates = createWidgetStates();++ return {+ 'autosave-status': cloneWidgetState(widgetStates['autosave-status'] ?? defaultWidgetStates['autosave-status']),+ canvas: cloneWidgetState(widgetStates.canvas ?? defaultWidgetStates.canvas),+ diagnostics: cloneWidgetState(widgetStates.diagnostics ?? defaultWidgetStates.diagnostics),+ gallery: cloneWidgetState(widgetStates.gallery ?? defaultWidgetStates.gallery),+ generate: cloneWidgetState(widgetStates.generate ?? defaultWidgetStates.generate),+ 'history-controls': cloneWidgetState(widgetStates['history-controls'] ?? defaultWidgetStates['history-controls']),+ 'layout-actions': cloneWidgetState(widgetStates['layout-actions'] ?? defaultWidgetStates['layout-actions']),+ layers: cloneWidgetState(widgetStates.layers ?? defaultWidgetStates.layers),+ notifications: cloneWidgetState(widgetStates.notifications ?? defaultWidgetStates.notifications),+ preview: cloneWidgetState(widgetStates.preview ?? defaultWidgetStates.preview),+ queue: cloneWidgetState(widgetStates.queue ?? defaultWidgetStates.queue),+ 'server-status': cloneWidgetState(widgetStates['server-status'] ?? defaultWidgetStates['server-status']),+ 'version-status': cloneWidgetState(widgetStates['version-status'] ?? defaultWidgetStates['version-status']),+ workflow: cloneWidgetState(widgetStates.workflow ?? defaultWidgetStates.workflow),+ };+};const cloneWidgetRegions = (widgetRegions: Record<WidgetRegion, WidgetRegionState>@@ -139,7 +327,7 @@ const createUndoSnapshot = (project: Project): ProjectUndoSnapshot => ({const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): Project => ({...project,- canvas: cloneCanvas(snapshot.canvas),+ canvas: { ...cloneCanvas(snapshot.canvas), stagingArea: cloneCanvas(project.canvas).stagingArea },invocation: { ...snapshot.invocation },layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },projectGraph: cloneGraph(snapshot.projectGraph),@@ -183,11 +371,14 @@ const createProjectGraph = (index: number, projectId: string): GraphContract =>const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({'autosave-status': { id: 'autosave-status', label: 'Autosave', values: {}, version: 1 },canvas: { id: 'canvas', label: 'Canvas', values: {}, version: 1 },+ diagnostics: { id: 'diagnostics', label: 'Diagnostics', values: {}, version: 1 },gallery: { id: 'gallery', label: 'Gallery', values: {}, version: 1 },generate: { graphId: 'generate-graph', id: 'generate', label: 'Generate', values: {}, version: 1 },'history-controls': { id: 'history-controls', label: 'History Controls', values: {}, version: 1 },'layout-actions': { id: 'layout-actions', label: 'Layout Actions', values: {}, version: 1 },layers: { id: 'layers', label: 'Layers', values: {}, version: 1 },+ notifications: { id: 'notifications', label: 'Notifications', values: {}, version: 1 },+ preview: { id: 'preview', label: 'Preview', values: {}, version: 1 },queue: { id: 'queue', label: 'Queue', values: {}, version: 1 },'server-status': { id: 'server-status', label: 'Server Status', values: {}, version: 1 },'version-status': { id: 'version-status', label: 'Version', values: {}, version: 1 },@@ -203,7 +394,7 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({},right: {activeWidgetId: 'layers',- enabledWidgetIds: ['queue', 'gallery', 'layers'],+ enabledWidgetIds: ['queue', 'gallery', 'layers', 'diagnostics'],isCollapsed: false,sizePx: 240,},@@ -211,8 +402,10 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({activeWidgetId: 'queue',enabledWidgetIds: ['server-status',+ 'diagnostics','queue','gallery',+ 'notifications','autosave-status','history-controls','layout-actions',@@ -223,14 +416,33 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({},center: {activeWidgetId: 'canvas',- enabledWidgetIds: ['canvas', 'gallery', 'workflow'],+ enabledWidgetIds: ['canvas', 'gallery', 'preview', 'workflow'],isCollapsed: false,sizePx: 0,},});-const getCenterWidgetIdFromViewId = (centerViewId: CenterViewId): WidgetId =>- centerViewId === 'preview' ? 'gallery' : centerViewId;+const LEGACY_RIGHT_REGION_WIDGET_IDS: WidgetId[] = ['queue', 'gallery', 'layers'];++const isLegacyDefaultRightRegion = (region: WidgetRegionState): boolean =>+ region.enabledWidgetIds.length === LEGACY_RIGHT_REGION_WIDGET_IDS.length &&+ region.enabledWidgetIds.every((widgetId, index) => widgetId === LEGACY_RIGHT_REGION_WIDGET_IDS[index]);++const ensureRightRegion = (rightRegion: WidgetRegionState | undefined): WidgetRegionState => {+ const defaultRightRegion = createWidgetRegions().right;++ if (!rightRegion) {+ return defaultRightRegion;+ }++ if (isLegacyDefaultRightRegion(rightRegion)) {+ return { ...rightRegion, enabledWidgetIds: defaultRightRegion.enabledWidgetIds };+ }++ return rightRegion;+};++const getCenterWidgetIdFromViewId = (centerViewId: CenterViewId): WidgetId => centerViewId;const ensureCenterRegion = (centerRegion: WidgetRegionState | undefined,@@ -261,9 +473,10 @@ const ensureProjectWidgetContracts = (project: Project): Project => {return {...project,+ canvas: cloneCanvas(project.canvas ?? createCanvasState()),widgetRegions: {left: legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel'] ?? defaultWidgetRegions.left,- right: legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel'] ?? defaultWidgetRegions.right,+ right: ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']),bottom: legacyWidgetRegions?.bottom ?? legacyWidgetRegions?.['status-bar'] ?? defaultWidgetRegions.bottom,center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),},@@ -283,8 +496,14 @@ const clampPanelSize = (region: WidgetRegion, sizePx: number): number => {};const createCanvasState = (): CanvasStateContract => ({- layers: [],- stagingArea: { pendingImageIds: [] },+ document: createCanvasDocument(),+ stagingArea: {+ areThumbnailsVisible: true,+ isVisible: false,+ pendingImageIds: [],+ pendingImages: [],+ selectedImageIndex: 0,+ },version: 1,});@@ -355,8 +574,27 @@ const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): P},});+const normalizePreferences = (preferences?: Partial<WorkbenchPreferences>): WorkbenchPreferences => {+ const themeId = isWorkbenchThemeId(preferences?.themeId) ? preferences.themeId : DEFAULT_THEME_ID;+ const reduceMotion =+ typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion;+ const showFocusRegionHighlight =+ typeof preferences?.showFocusRegionHighlight === 'boolean'+ ? preferences.showFocusRegionHighlight+ : DEFAULT_PREFERENCES.showFocusRegionHighlight;++ return { reduceMotion, showFocusRegionHighlight, themeId };+};+const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({...state,+ // Persisted snapshots from before preferences existed (or partially written+ // ones) are healed by merging in defaults, so hydrate never reads `undefined`.+ account: {+ ...state.account,+ preferences: normalizePreferences(state.account?.preferences),+ },+ notifications: state.notifications ?? [],projects: state.projects.map(ensureProjectWidgetContracts),});@@ -404,12 +642,153 @@ const updateActiveInvocation = (};});+const isMainModelConfig = (value: unknown): value is MainModelConfig => {+ if (!value || typeof value !== 'object') {+ return false;+ }++ const record = value as Record<string, unknown>;++ return typeof record.key === 'string' && typeof record.name === 'string' && record.type === 'main';+};++const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues => {+ if (!values || typeof values !== 'object') {+ return false;+ }++ const record = values as Record<string, unknown>;+ const hasFiniteNumber = (key: string) => typeof record[key] === 'number' && Number.isFinite(record[key]);++ return (+ typeof record.modelKey === 'string' &&+ typeof record.positivePrompt === 'string' &&+ typeof record.negativePrompt === 'string' &&+ hasFiniteNumber('width') &&+ hasFiniteNumber('height') &&+ hasFiniteNumber('steps') &&+ hasFiniteNumber('cfgScale') &&+ hasFiniteNumber('cfgRescaleMultiplier') &&+ typeof record.scheduler === 'string' &&+ hasFiniteNumber('seed') &&+ typeof record.shouldRandomizeSeed === 'boolean' &&+ isMainModelConfig(record.model)+ );+};+const selectGraphForInvocation = (project: Project, invocation: InvocationRoute): GraphContract => {const widgetGraph = project.widgetGraphs[invocation.sourceId as WidgetId];return widgetGraph ? cloneGraph(widgetGraph) : cloneGraph(project.projectGraph);};+const compileInvocationSnapshot = (+ project: Project,+ route: InvocationRoute+): { graph: GraphContract; widgetStates: Record<WidgetId, WidgetStateContract> } | null => {+ const widgetStates = cloneWidgetStates(project.widgetStates);++ if (route.sourceId !== 'generate') {+ return { graph: selectGraphForInvocation(project, route), widgetStates };+ }++ const values = project.widgetStates.generate.values;++ if (!isGenerateWidgetValues(values)) {+ return null;+ }++ const resolvedSettings: GenerateWidgetValues = {+ ...values,+ seed: resolveGenerateSeed(values),+ shouldRandomizeSeed: false,+ };+ const compiledGraph = compileGenerateGraph(resolvedSettings, resolvedSettings.model, route.destination).graph;++ widgetStates.generate = {+ ...widgetStates.generate,+ graphId: compiledGraph.id,+ values: { ...resolvedSettings, model: { ...resolvedSettings.model } },+ };++ return { graph: compiledGraph, widgetStates };+};++const updateProjectById = (+ state: WorkbenchState,+ projectId: string,+ getProject: (project: Project) => Project+): WorkbenchState => ({+ ...state,+ projects: state.projects.map((project) =>+ project.id === projectId ? getProject(ensureProjectWidgetContracts(project)) : project+ ),+});++const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => ({+ ...project,+ queue: {+ items: project.queue.items.map((item) => (item.id === queueItemId ? getItem(item) : item)),+ },+});++const routeQueueItemResults = (project: Project, queueItemId: string, images: GeneratedImageContract[]): Project => {+ const queueItem = project.queue.items.find((item) => item.id === queueItemId);+ const destination = queueItem?.snapshot.destination ?? project.invocation.destination;+ const nextProject = updateQueueItem(project, queueItemId, (item) => ({+ ...item,+ resultImages: images,+ status: 'completed',+ }));++ if (destination === 'gallery') {+ const galleryValues = nextProject.widgetStates.gallery.values;+ const existingImages = getGalleryImages(galleryValues).filter(+ (image) => !images.some((incomingImage) => incomingImage.imageName === image.imageName)+ );++ return {+ ...nextProject,+ widgetStates: {+ ...nextProject.widgetStates,+ gallery: {+ ...nextProject.widgetStates.gallery,+ values: {+ ...galleryValues,+ recentImages: [...images, ...existingImages],+ selectedImage: images[0] ?? galleryValues.selectedImage,+ selectedImageName: images[0]?.imageName ?? nextProject.widgetStates.gallery.values.selectedImageName,+ },+ },+ },+ };+ }++ const incomingImages = images.map((image) => normalizeStagingCandidate(image, nextProject.canvas.document));+ const incomingImageKeys = new Set(incomingImages.map((image) => `${image.sourceQueueItemId}:${image.imageName}`));+ const existingImages = nextProject.canvas.stagingArea.pendingImages.filter(+ (image) => !incomingImageKeys.has(`${image.sourceQueueItemId}:${image.imageName}`)+ );+ const pendingImages = [...existingImages, ...incomingImages];++ return {+ ...nextProject,+ canvas: {+ ...nextProject.canvas,+ stagingArea: {+ ...nextProject.canvas.stagingArea,+ areThumbnailsVisible: true,+ isVisible: pendingImages.length > 0,+ pendingImageIds: pendingImages.map((image) => image.imageName),+ pendingImages,+ selectedImageIndex:+ incomingImages.length > 0 ? existingImages.length : nextProject.canvas.stagingArea.selectedImageIndex,+ sourceQueueItemId: queueItemId,+ },+ },+ };+};+const submitInvocationSnapshot = (project: Project,backendSupportsCancellation: boolean,@@ -421,7 +800,13 @@ const submitInvocationSnapshot = (const submittedAt = now();const queueItemId = createId('queue-item');- const graph = selectGraphForInvocation(project, route);+ const compiledSnapshot = compileInvocationSnapshot(project, route);++ if (!compiledSnapshot) {+ return project;+ }++ const { graph, widgetStates } = compiledSnapshot;const graphHistorySnapshot = createGraphHistorySnapshot(`Queue snapshot ${queueItemId}`, graph);const queueItem: QueueItem = {cancellable: backendSupportsCancellation,@@ -432,7 +817,7 @@ const submitInvocationSnapshot = (graph,sourceId: route.sourceId,submittedAt,- widgetStates: cloneWidgetStates(project.widgetStates),+ widgetStates,},status: 'pending',};@@ -457,14 +842,23 @@ const submitInvocationSnapshot = (sourceId: route.sourceId,},queue: { items: [queueItem, ...project.queue.items] },+ widgetGraphs:+ route.sourceId === 'generate' ? { ...project.widgetGraphs, generate: cloneGraph(graph) } : project.widgetGraphs,};};+export const DEFAULT_PREFERENCES: WorkbenchPreferences = {+ reduceMotion: false,+ showFocusRegionHighlight: true,+ themeId: DEFAULT_THEME_ID,+};+export const createInitialWorkbenchState = (): WorkbenchState => ({- account: { activeLayoutPresetId: 'canvas-default' },+ account: { activeLayoutPresetId: 'canvas-default', preferences: { ...DEFAULT_PREFERENCES } },activeProjectId: 'project-1',autosave: { status: 'idle' },errorLog: [],+ notifications: [],projects: Array.from({ length: INITIAL_PROJECT_COUNT }, (_value, index) => createProject(index + 1)),widgetFailures: [],});@@ -478,10 +872,15 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}case 'closeProject': {if (state.projects.length === 1) {- return {- ...state,- errorLog: ['At least one project must remain open.', ...state.errorLog],- };+ const message = 'At least one project must remain open.';++ return addNotification(+ {+ ...state,+ errorLog: [message, ...state.errorLog],+ },+ createNotification({ kind: 'error', message, title: 'Project close blocked' })+ );}const projectIndex = state.projects.findIndex((project) => project.id === action.projectId);@@ -521,7 +920,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)activeWidgetId: region.enabledWidgetIds.includes(widgetId) ? widgetId : region.activeWidgetId,isCollapsed: false,})),- account: { activeLayoutPresetId: action.presetId },+ account: { ...state.account, activeLayoutPresetId: action.presetId },};}case 'resetActiveLayout': {@@ -628,10 +1027,54 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)sizePx: clampPanelSize(action.region, action.sizePx),}));}+ case 'setGenerateSettings': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ generate: {+ ...project.widgetStates.generate,+ values: { ...action.values, model: { ...action.values.model } },+ },+ },+ }));+ }+ case 'setGenerateBatchCount': {+ const batchCount = Math.min(64, Math.max(1, Math.round(action.batchCount)));++ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ generate: {+ ...project.widgetStates.generate,+ values: { ...project.widgetStates.generate.values, batchCount },+ },+ },+ }));+ }case 'submitInvocationSnapshot': {- return updateActiveProject(state, (project) =>+ const beforeProject = state.projects.find((project) => project.id === state.activeProjectId);+ const nextState = updateActiveProject(state, (project) =>submitInvocationSnapshot(project, action.backendSupportsCancellation));+ const afterProject = nextState.projects.find((project) => project.id === nextState.activeProjectId);++ if (!beforeProject || !afterProject || beforeProject.queue.items.length === afterProject.queue.items.length) {+ return nextState;+ }++ const queueItem = afterProject.queue.items[0];++ return addNotification(+ nextState,+ createNotification({+ kind: 'info',+ message: `${afterProject.name}: ${queueItem.snapshot.sourceId} to ${queueItem.snapshot.destination}`,+ projectId: afterProject.id,+ title: 'Invocation queued',+ })+ );}case 'submitResolvedInvocationSnapshot': {return updateActiveProject(state, (project) =>@@ -642,12 +1085,310 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)));}- case 'cancelQueueItem': {+ case 'markQueueItemBackendSubmitted': {+ return updateProjectById(state, action.projectId, (project) =>+ updateQueueItem(project, action.queueItemId, (item) => ({+ ...item,+ backendItemIds: action.backendItemIds,+ status: item.status === 'cancelled' ? 'cancelled' : 'running',+ }))+ );+ }+ case 'setQueueItemStatus': {+ const project = state.projects.find((project) => project.id === action.projectId);+ const queueItem = project?.queue.items.find((item) => item.id === action.queueItemId);++ if (queueItem?.status === 'cancelled' && action.status !== 'cancelled') {+ return state;+ }++ const nextState = updateProjectById(state, action.projectId, (project) =>+ updateQueueItem(project, action.queueItemId, (item) => ({+ ...item,+ error: action.error,+ status: action.status,+ }))+ );++ if (action.status !== 'failed' && action.status !== 'cancelled') {+ return nextState;+ }++ return addNotification(+ nextState,+ createNotification({+ kind: action.status === 'failed' ? 'error' : 'info',+ message: action.error ?? `Queue item ${action.queueItemId} ${action.status}.`,+ projectId: action.projectId,+ title: action.status === 'failed' ? 'Invocation failed' : 'Invocation cancelled',+ })+ );+ }+ case 'routeQueueItemResults': {+ const project = state.projects.find((project) => project.id === action.projectId);+ const queueItem = project?.queue.items.find((item) => item.id === action.queueItemId);++ if (queueItem?.status === 'cancelled') {+ return state;+ }++ const nextState = updateProjectById(state, action.projectId, (project) =>+ routeQueueItemResults(project, action.queueItemId, action.images)+ );++ if (action.images.length === 0) {+ return nextState;+ }++ return addNotification(+ nextState,+ createNotification({+ kind: 'success',+ message: `${action.images.length} image(s) routed from ${action.queueItemId}.`,+ projectId: action.projectId,+ title: 'Invocation completed',+ })+ );+ }+ case 'setStagedImageIndex': {+ return updateActiveProject(state, (project) => {+ const selectedImageIndex = clampStagedImageIndex(+ action.imageIndex,+ project.canvas.stagingArea.pendingImages.length+ );++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: { ...project.canvas.stagingArea, selectedImageIndex },+ },+ };+ });+ }+ case 'cycleStagedImage': {+ return updateActiveProject(state, (project) => {+ const { pendingImages, selectedImageIndex } = project.canvas.stagingArea;++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ selectedImageIndex: cycleStagedImageIndex(selectedImageIndex, pendingImages.length, action.direction),+ },+ },+ };+ });+ }+ case 'discardSelectedStagedImage': {+ return updateActiveProject(state, (project) => {+ const { pendingImages, selectedImageIndex } = project.canvas.stagingArea;++ if (pendingImages.length === 0) {+ return project;+ }++ const nextPendingImages = pendingImages.filter((_image, index) => index !== selectedImageIndex);++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ isVisible: nextPendingImages.length > 0 ? project.canvas.stagingArea.isVisible : false,+ pendingImageIds: nextPendingImages.map((image) => image.imageName),+ pendingImages: nextPendingImages,+ selectedImageIndex: clampStagedImageIndex(selectedImageIndex, nextPendingImages.length),+ sourceQueueItemId:+ nextPendingImages.length > 0 ? project.canvas.stagingArea.sourceQueueItemId : undefined,+ },+ },+ };+ });+ }+ case 'discardAllStagedImages': {+ return updateActiveProject(state, (project) => ({+ ...project,+ canvas: { ...project.canvas, stagingArea: clearStagingArea(project.canvas.stagingArea) },+ }));+ }+ case 'selectGalleryImage': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: {+ ...project.widgetStates.gallery.values,+ selectedImage: action.image,+ selectedImageName: action.image.imageName,+ },+ },+ },+ }));+ }+ case 'selectGalleryBoard': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: { ...project.widgetStates.gallery.values, selectedBoardId: action.boardId },+ },+ },+ }));+ }+ case 'setGalleryView': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: { ...project.widgetStates.gallery.values, galleryView: action.galleryView },+ },+ },+ }));+ }+ case 'setGallerySearchTerm': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: { ...project.widgetStates.gallery.values, searchTerm: action.searchTerm },+ },+ },+ }));+ }+ case 'setGalleryImageDensityPercent': {+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: { ...project.widgetStates.gallery.values, imageDensityPercent: action.imageDensityPercent },+ },+ },+ }));+ }+ case 'toggleCanvasStagingVisibility': {+ return updateActiveProject(state, (project) => {+ if (project.canvas.stagingArea.pendingImages.length === 0) {+ return project;+ }++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: { ...project.canvas.stagingArea, isVisible: !project.canvas.stagingArea.isVisible },+ },+ };+ });+ }+ case 'toggleCanvasStagingThumbnailsVisibility': {+ return updateActiveProject(state, (project) => {+ if (project.canvas.stagingArea.pendingImages.length === 0) {+ return project;+ }++ return {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ areThumbnailsVisible: !project.canvas.stagingArea.areThumbnailsVisible,+ },+ },+ };+ });+ }+ case 'acceptStagedImage': {+ const activeProject = state.projects.find((project) => project.id === state.activeProjectId);+ const stagedImage =+ activeProject?.canvas.stagingArea.pendingImages[activeProject.canvas.stagingArea.selectedImageIndex];+ const nextState = updateActiveProject(state, (project) => {+ const stagedImage = project.canvas.stagingArea.pendingImages[project.canvas.stagingArea.selectedImageIndex];++ if (!stagedImage) {+ return project;+ }++ const acceptedAt = now();+ const nextProject = pushUndo(project, 'Accept staged canvas candidate');+ const layer: CanvasRasterLayerContract = {+ ...stagedImage,+ acceptedAt,+ id: createId('layer'),+ label: `Layer ${project.canvas.document.layers.length + 1}`,+ placement: clonePlacement(stagedImage.placement),+ };++ return {+ ...nextProject,+ canvas: {+ ...nextProject.canvas,+ document: {+ ...nextProject.canvas.document,+ layers: [layer, ...nextProject.canvas.document.layers],+ },+ stagingArea: clearStagingArea(nextProject.canvas.stagingArea),+ },+ events: [+ {+ createdAt: acceptedAt,+ id: createId('event'),+ summary: `Accepted ${stagedImage.imageName} into a new raster layer`,+ type: 'canvas-layer-accepted',+ },+ ...nextProject.events,+ ],+ };+ });++ if (!stagedImage || !activeProject) {+ return nextState;+ }++ return addNotification(+ nextState,+ createNotification({+ kind: 'success',+ message: `${stagedImage.imageName} added to ${activeProject.name}.`,+ projectId: activeProject.id,+ title: 'Canvas layer accepted',+ })+ );+ }+ case 'clearCanvasStaging': {return updateActiveProject(state, (project) => ({+ ...project,+ canvas: { ...project.canvas, stagingArea: clearStagingArea(project.canvas.stagingArea) },+ }));+ }+ case 'cancelQueueItem': {+ const activeProject = state.projects.find((project) => project.id === state.activeProjectId);+ const queueItem = activeProject?.queue.items.find((item) => item.id === action.queueItemId);+ const canCancelQueueItem =+ Boolean(queueItem?.cancellable) && (queueItem?.status === 'pending' || queueItem?.status === 'running');+ const nextState = updateActiveProject(state, (project) => ({...project,queue: {items: project.queue.items.map((item) => {- if (item.id !== action.queueItemId || !item.cancellable || item.status !== 'pending') {+ if (+ item.id !== action.queueItemId ||+ !item.cancellable ||+ (item.status !== 'pending' && item.status !== 'running')+ ) {return item;}@@ -655,6 +1396,20 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}),},}));++ if (!activeProject || !queueItem || !canCancelQueueItem) {+ return nextState;+ }++ return addNotification(+ nextState,+ createNotification({+ kind: 'info',+ message: `${activeProject.name}: ${action.queueItemId}`,+ projectId: activeProject.id,+ title: 'Invocation cancellation requested',+ })+ );}case 'undoProjectChange': {return updateActiveProject(state, (project) => {@@ -726,7 +1481,22 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)return { ...state, autosave: { lastSavedAt: action.savedAt, status: 'saved' } };}case 'autosaveFailed': {- return { ...state, autosave: { error: action.error, status: 'error' } };+ return addNotification(+ { ...state, autosave: { error: action.error, status: 'error' } },+ createNotification({ kind: 'error', message: action.error, title: 'Autosave failed' })+ );+ }+ case 'markAllNotificationsRead': {+ return {+ ...state,+ notifications: state.notifications.map((notification) => ({ ...notification, isRead: true })),+ };+ }+ case 'clearNotifications': {+ return { ...state, notifications: [] };+ }+ case 'clearErrorLog': {+ return { ...state, errorLog: [] };}case 'recordWidgetFailure': {const hasFailure = state.widgetFailures.some((failure) => failure.widgetId === action.failure.widgetId);@@ -735,15 +1505,36 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)return state;}+ return addNotification(+ {+ ...state,+ errorLog: [action.failure.details, ...state.errorLog].slice(0, ERROR_LOG_LIMIT),+ widgetFailures: [action.failure, ...state.widgetFailures],+ },+ createNotification({+ kind: 'error',+ message: action.failure.details,+ title: `Widget failed: ${action.failure.widgetId}`,+ })+ );+ }+ case 'recordError': {+ return addNotification(+ { ...state, errorLog: [action.message, ...state.errorLog].slice(0, ERROR_LOG_LIMIT) },+ createNotification({ kind: 'error', message: action.message, title: 'Error' })+ );+ }+ case 'setPreferences': {+ const preferences = normalizePreferences({ ...state.account.preferences, ...action.preferences });+return {...state,- errorLog: [action.failure.details, ...state.errorLog].slice(0, ERROR_LOG_LIMIT),- widgetFailures: [action.failure, ...state.widgetFailures],+ account: {+ ...state.account,+ preferences,+ },};}- case 'recordError': {- return { ...state, errorLog: [action.message, ...state.errorLog].slice(0, ERROR_LOG_LIMIT) };- }}};