Skip to content

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

refactor(webv2): record diagnostics through platform logging

Josh Corbett742bf6030ecb
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 2a71877ec4..a171d6e303 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -20,6 +20,7 @@ Ownership is based on invariants, not the first caller:
| `platform/state` | React-free listener/store/selector cores and separate React hook adapters | Domain stores or aggregate state |
| `platform/query` | Query client construction and defaults | Feature query keys, DTOs, invalidation policy |
| `platform/i18n` | i18next bootstrap and supported-language metadata | Persisted preference ownership |
+| `platform/logging` | Event contracts, recording filters, safe normalization, bounded in-memory history, subscriptions, console output, export envelope | Preference persistence, diagnostic presentation, event policy |
| `platform/ui` | Chakra system/theme, reusable controls, toaster, brand mark | Workbench widgets or feature-specific views |
| `platform/runtime` | Domain-neutral build/runtime metadata | Route or feature policy |
| `workbench/backend` | Queue/node/model progress interpretation and transient domain stores pending their feature migrations | HTTP, sockets, connection mechanics, generic stores |
@@ -31,6 +32,8 @@ Platform transport receives authentication through `app/main.tsx`, before React
Platform State also owns reusable projections of broad external stores into referentially stable read-only stores. App may construct those projections for a feature port, but the listener, caching, and equality mechanics remain domain-neutral Platform code.
+Platform Logging is the one recorder for application and project events. `createLogger` binds a source (namespace, area, optional project, widget and operation identity); a runtime passes the account scope it captured so writes after that lifetime are discarded, while module-level loggers stay unbound. Entries are normalized once at ingestion into immutable JSON-safe snapshots: errors keep name, message, stack, cause and status/code, credential-like keys are redacted, URL queries and fragments are stripped, and depth, collection, string and 8 KiB entry ceilings are marked explicitly. History is account-wide and memory-only in three bounded buffers (warn and above, lower severities, timings) so verbose traffic cannot evict problems; closed projects keep their entries until eviction or account cleanup. Publication is coalesced per microtask; clears and account transitions publish synchronously and restore default capture settings. Workbench owns the preference-to-config mapping and the diagnostics panel; App applies saved preferences before React mounts, installs uncaught-error and router catch reporting, and keeps configuration in step with the active account. Each handled terminal failure has one reporting owner: the Workbench store records reported errors, widget failures, autosave outcomes and queue item transitions; transport and coordinator events are debug breadcrumbs.
+
`pnpm architecture:check` is the executable source of truth for these dependency directions. It uses the TypeScript parser to classify static imports, type imports, dynamic imports, re-exports, and inline imported types after resolving aliases and relative paths. Temporary violations must be recorded in `src/architecture/migrationExceptions.ts` with an owner and a removal ticket; architecture completion requires that registry to be empty.
The queue pilot is the first migrated feature. Its private `QueueBackendPort` is the adapter seam; public callers use domain reads, commands, and production runtime factories from `@features/queue`. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns the global backend queue read model, and non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history remains in the Workbench aggregate.
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index b7e70b79ff..7ce6345fb7 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -127,6 +127,7 @@
"source:src/app/SocketHubRuntime.tsx",
"source:src/app/ThemeController.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/assets/SplashImage.webp",
@@ -184,6 +185,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -255,6 +259,7 @@
"source:src/workbench/canvasSchemaVersion.ts",
"source:src/workbench/components/WorkbenchSplashScreen.tsx",
"source:src/workbench/deferredResource.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/hotkeys/catalog.ts",
"source:src/workbench/hotkeys/keys.ts",
"source:src/workbench/hotkeys/modalLayer.ts",
@@ -462,6 +467,7 @@
"source:src/app/WorkbenchApp.tsx",
"source:src/app/WorkflowUiAdapter.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/app/workbenchPorts.tsx",
@@ -684,6 +690,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -808,7 +817,7 @@
"source:src/workbench/controlAdapters.ts",
"source:src/workbench/controlLayerChecks.ts",
"source:src/workbench/deferredResource.ts",
- "source:src/workbench/diagnostics/logger.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/extensions/contributionSource.ts",
"source:src/workbench/extensions/extensionRegistry.ts",
"source:src/workbench/floatingWindows.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 7b22b372ad..be9412af85 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -504,6 +504,7 @@
"source:src/app/SocketHubRuntime.tsx",
"source:src/app/ThemeController.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/assets/SplashImage.webp",
@@ -595,6 +596,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -666,6 +670,7 @@
"source:src/workbench/canvasSchemaVersion.ts",
"source:src/workbench/components/WorkbenchSplashScreen.tsx",
"source:src/workbench/deferredResource.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/hotkeys/catalog.ts",
"source:src/workbench/hotkeys/keys.ts",
"source:src/workbench/hotkeys/modalLayer.ts",
@@ -857,6 +862,7 @@
"source:src/app/WorkbenchApp.tsx",
"source:src/app/WorkflowUiAdapter.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/app/workbenchPorts.tsx",
@@ -1214,6 +1220,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -1488,7 +1497,7 @@
"source:src/workbench/controlAdapters.ts",
"source:src/workbench/controlLayerChecks.ts",
"source:src/workbench/deferredResource.ts",
- "source:src/workbench/diagnostics/logger.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/extensions/contributionSource.ts",
"source:src/workbench/extensions/extensionRegistry.ts",
"source:src/workbench/floatingWindows.ts",
@@ -1892,6 +1901,7 @@
"source:src/app/WorkbenchApp.tsx",
"source:src/app/WorkflowUiAdapter.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/app/workbenchPorts.tsx",
@@ -2257,6 +2267,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -2540,7 +2553,7 @@
"source:src/workbench/controlAdapters.ts",
"source:src/workbench/controlLayerChecks.ts",
"source:src/workbench/deferredResource.ts",
- "source:src/workbench/diagnostics/logger.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/extensions/contributionSource.ts",
"source:src/workbench/extensions/extensionRegistry.ts",
"source:src/workbench/floatingWindows.ts",
@@ -3097,6 +3110,7 @@
"source:src/app/WorkbenchApp.tsx",
"source:src/app/WorkflowUiAdapter.tsx",
"source:src/app/accountLifecycle.ts",
+ "source:src/app/loggingRuntime.ts",
"source:src/app/main.tsx",
"source:src/app/router.tsx",
"source:src/app/workbenchPorts.tsx",
@@ -3521,6 +3535,9 @@
"source:src/platform/core/seed.ts",
"source:src/platform/i18n/client.ts",
"source:src/platform/i18n/languages.ts",
+ "source:src/platform/logging/contracts.ts",
+ "source:src/platform/logging/logger.ts",
+ "source:src/platform/logging/normalize.ts",
"source:src/platform/performance/semanticReady.ts",
"source:src/platform/pwa/registerServiceWorker.ts",
"source:src/platform/query/client.ts",
@@ -3796,7 +3813,7 @@
"source:src/workbench/controlAdapters.ts",
"source:src/workbench/controlLayerChecks.ts",
"source:src/workbench/deferredResource.ts",
- "source:src/workbench/diagnostics/logger.ts",
+ "source:src/workbench/diagnostics/loggingPreferences.ts",
"source:src/workbench/extensions/contributionSource.ts",
"source:src/workbench/extensions/extensionRegistry.ts",
"source:src/workbench/floatingWindows.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 1f3d858163..fb6edef99b 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1726,7 +1726,7 @@
},
"developerLogEnabled": {
"label": "Record diagnostic logs",
- "description": "Record selected diagnostic events in the Diagnostics widget."
+ "description": "Record selected diagnostic events in the Diagnostics widget. Warnings and errors from every namespace are recorded by default."
},
"developerPerformanceTimingsEnabled": {
"label": "Collect performance timings",
@@ -1734,7 +1734,7 @@
},
"developerLogNamespaces": {
"label": "Log namespaces",
- "description": "Choose which diagnostic sources to record."
+ "description": "Choose which diagnostic sources to record. New namespaces are not added to a saved selection; use Reset logging defaults."
},
"generationDevices": {
"label": "Generation devices",
@@ -1788,7 +1788,17 @@
"server": "Server",
"workspace": "Data & workspace",
"about": "About"
- }
+ },
+ "developerConsoleOutputEnabled": {
+ "label": "Mirror logs to the browser console",
+ "description": "Write recorded events to the developer console as well. The same level and namespace filters apply."
+ },
+ "developerLoggingReset": {
+ "label": "Reset logging defaults",
+ "description": "Restore the default level, namespaces, console and timing settings, including namespaces added in newer versions."
+ },
+ "resetLoggingDefaults": "Reset to defaults",
+ "loggingDefaultsActive": "Default logging settings are active."
}
},
"shell": {
diff --git a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
index 4a4688cb5a..27d994f9fc 100644
--- a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
+++ b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
@@ -54,9 +54,9 @@ const hubs = [
'features/workflow/widget.ts',
'features/upscale/index.ts',
'features/upscale/widget.ts',
+ 'platform/logging/contracts.ts',
'workbench/canvas-engine/contracts.ts',
'workbench/canvas-engine/types.ts',
- 'workbench/diagnostics/contracts.ts',
'workbench/graphContracts.ts',
'workbench/invocationContracts.ts',
'workbench/layoutContracts.ts',
diff --git a/invokeai/frontend/webv2/src/app/loggingRuntime.test.ts b/invokeai/frontend/webv2/src/app/loggingRuntime.test.ts
new file mode 100644
index 0000000000..b6a3254595
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/loggingRuntime.test.ts
@@ -0,0 +1,106 @@
+import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';
+import {
+ configureLogging,
+ getLoggingConfig,
+ getLogSnapshot,
+ resetLogging,
+ subscribeLogs,
+} from '@platform/logging/logger';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { normalizeWorkbenchPreferences } from '@workbench/settings/store';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { applyLoggingPreferences, installGlobalErrorLogging } from './loggingRuntime';
+
+type Listener = (event: never) => void;
+
+const createTarget = () => {
+ const listeners = new Map<string, Listener[]>();
+
+ return {
+ addEventListener: (type: string, listener: Listener) => {
+ listeners.set(type, [...(listeners.get(type) ?? []), listener]);
+ },
+ dispatch: (type: string, event: unknown) => {
+ for (const listener of listeners.get(type) ?? []) {
+ listener(event as never);
+ }
+ },
+ };
+};
+
+beforeEach(() => {
+ resetLogging();
+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, level: 'debug' });
+});
+
+describe('applyLoggingPreferences', () => {
+ it('applies every preference field and publishes only on effective changes', () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeLogs(listener);
+ const preferences = normalizeWorkbenchPreferences({
+ developerConsoleOutputEnabled: true,
+ developerLogEnabled: false,
+ developerLogLevel: 'info',
+ developerLogNamespaces: ['queue', 'canvas'],
+ developerPerformanceTimingsEnabled: true,
+ });
+
+ applyLoggingPreferences(preferences);
+ applyLoggingPreferences({ ...preferences, developerLogNamespaces: ['canvas', 'queue'] });
+
+ expect(getLoggingConfig()).toEqual({
+ consoleOutputEnabled: true,
+ enabled: false,
+ level: 'info',
+ namespaces: ['canvas', 'queue'],
+ performanceTimingsEnabled: true,
+ });
+ expect(listener).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
+ it('ends in the hydrated account preferences whichever order cleanup runs', () => {
+ accountLifecycle.activate('user-a');
+ applyLoggingPreferences(normalizeWorkbenchPreferences({ developerLogLevel: 'trace' }));
+
+ accountLifecycle.activate('user-b');
+ expect(getLoggingConfig().level).toBe('warn');
+
+ applyLoggingPreferences(normalizeWorkbenchPreferences({ developerLogLevel: 'error' }));
+ expect(getLoggingConfig().level).toBe('error');
+ });
+});
+
+describe('installGlobalErrorLogging', () => {
+ it('records uncaught errors and rejections as unattributed application events', () => {
+ const target = createTarget();
+
+ installGlobalErrorLogging(target);
+ target.dispatch('error', {
+ colno: 7,
+ error: new RangeError('boom'),
+ filename: 'https://host.example/assets/app.js?v=1',
+ lineno: 12,
+ message: 'Uncaught RangeError: boom',
+ });
+ target.dispatch('unhandledrejection', { reason: 'rejected value' });
+
+ expect(getLogSnapshot().entries).toMatchObject([
+ {
+ error: { message: 'rejected value', name: 'NonError' },
+ level: 'error',
+ name: 'app.unhandled-rejection',
+ source: { area: 'browser', namespace: 'app' },
+ },
+ {
+ context: { column: 7, file: 'https://host.example/assets/app.js', line: 12 },
+ error: { message: 'boom', name: 'RangeError' },
+ level: 'error',
+ message: 'Uncaught RangeError: boom',
+ name: 'app.uncaught-error',
+ },
+ ]);
+ expect(getLogSnapshot().entries[1]?.source).not.toHaveProperty('projectId');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/loggingRuntime.ts b/invokeai/frontend/webv2/src/app/loggingRuntime.ts
new file mode 100644
index 0000000000..6f056e8530
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/loggingRuntime.ts
@@ -0,0 +1,73 @@
+import type { LoggingConfig } from '@platform/logging/contracts';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+
+import { configureLogging, createLogger, getLoggingConfig } from '@platform/logging/logger';
+import { APP_VERSION } from '@platform/runtime/appMetadata';
+import { toLoggingConfig } from '@workbench/diagnostics/loggingPreferences';
+import { subscribeWorkbenchPreferences } from '@workbench/settings/store';
+
+const appLogger = createLogger({ area: 'browser', namespace: 'app' });
+
+interface GlobalErrorTarget {
+ addEventListener(type: 'error', listener: (event: ErrorEvent) => void): void;
+ addEventListener(type: 'unhandledrejection', listener: (event: PromiseRejectionEvent) => void): void;
+}
+
+/**
+ * Record uncaught errors and rejections as application events without suppressing the browser's own reporting.
+ * They are not attributed to whichever project happens to be active.
+ */
+export const installGlobalErrorLogging = (target: GlobalErrorTarget): void => {
+ target.addEventListener('error', (event) => {
+ appLogger.error({
+ context: { column: event.colno, file: event.filename, line: event.lineno },
+ error: event.error ?? event.message,
+ message: event.message || 'Uncaught error',
+ name: 'app.uncaught-error',
+ });
+ });
+ target.addEventListener('unhandledrejection', (event) => {
+ appLogger.error({
+ error: event.reason,
+ message: 'Unhandled promise rejection',
+ name: 'app.unhandled-rejection',
+ });
+ });
+};
+
+const isSameConfig = (left: LoggingConfig, right: LoggingConfig): boolean =>
+ (Object.keys(left) as (keyof LoggingConfig)[]).every((key) => {
+ const a = left[key];
+ const b = right[key];
+
+ return Array.isArray(a) && Array.isArray(b)
+ ? a.length === b.length && a.every((item, index) => item === b[index])
+ : a === b;
+ });
+
+/** Apply saved preferences to the recorder; publishes only when the effective configuration changes. */
+export const applyLoggingPreferences = (preferences: WorkbenchPreferences): void => {
+ const next = toLoggingConfig(preferences);
+
+ if (!isSameConfig(getLoggingConfig(), next)) {
+ configureLogging(next);
+ }
+};
+
+let isConfigured = false;
+
+/** App keeps capture settings in step with saved preferences for whichever account is active. */
+export const configureAppLogging = (): void => {
+ if (isConfigured) {
+ return;
+ }
+ isConfigured = true;
+
+ subscribeWorkbenchPreferences(applyLoggingPreferences);
+ installGlobalErrorLogging(window);
+ createLogger({ area: 'boot', namespace: 'app' }).info({
+ context: { version: APP_VERSION },
+ message: 'Application starting',
+ name: 'app.boot',
+ });
+};
diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsx
index 6f1bd5317e..ed71011d19 100644
--- a/invokeai/frontend/webv2/src/app/main.tsx
+++ b/invokeai/frontend/webv2/src/app/main.tsx
@@ -8,9 +8,11 @@ import { createRoot } from 'react-dom/client';
import { configureAppAccountLifecycle } from './accountLifecycle';
import { App } from './App';
+import { configureAppLogging } from './loggingRuntime';
-// Identity and HTTP ownership must be configured before any route starts work.
+// Identity, logging and HTTP ownership must be configured before any route starts work.
configureAppAccountLifecycle();
+configureAppLogging();
configureHttpAuth(identityTransportAuthAdapter);
registerServiceWorker();
diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsx
index 2c100debc6..f5f274d2c3 100644
--- a/invokeai/frontend/webv2/src/app/router.tsx
+++ b/invokeai/frontend/webv2/src/app/router.tsx
@@ -10,6 +10,7 @@ import {
type Capabilities,
} from '@features/identity';
import { ModelInstallRuntime } from '@features/models';
+import { createLogger } from '@platform/logging/logger';
import {
createHashHistory,
createRootRoute,
@@ -38,6 +39,9 @@ import { SocketHubRuntime } from './SocketHubRuntime';
* supports the relative base without server deep-path fallback.
*/
+/** Route render and loader failures reach the router's catch boundary; record them once there. */
+const routerLogger = createLogger({ area: 'router', namespace: 'app' });
+
const RouterError = ({ error }: ErrorComponentProps) => {
'use no memo';
// Skip compiler memoization on this cold path; retry tests and build budgets guard it.
@@ -215,6 +219,13 @@ const RouterPending = () => <WorkbenchSplashScreen messageKey="splash.loadingApp
export const router = createRouter({
defaultNotFoundComponent: () => <Navigate to="/" />,
+ defaultOnCatch: (error, errorInfo) =>
+ routerLogger.error({
+ context: errorInfo?.componentStack ? { componentStack: errorInfo.componentStack } : undefined,
+ error,
+ message: 'Route rendering failed',
+ name: 'app.route-failed',
+ }),
defaultPendingComponent: RouterPending,
defaultPreload: 'intent',
history: createHashHistory(),
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
index 6a4aad4b0b..64279198dc 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
@@ -1,6 +1,7 @@
import type { ProjectGraphAction } from '@features/workflow/core/document';
import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';
import type { ProjectGraphState, XYPosition } from '@features/workflow/core/types';
+import type { LogSource } from '@platform/logging/contracts';
export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';
@@ -113,10 +114,5 @@ export interface GraphPreviewSourceState {
getProvenance?: (nodeId: string, fieldName: string) => GraphPreviewProvenance | null;
}
-export interface WorkflowPerfSource {
- instanceId: string;
- kind: 'widget';
- projectId: string;
- region: WorkflowRegion;
- typeId: string;
-}
+/** Attribution for editor timings. */
+export type WorkflowPerfSource = LogSource;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
index 517e917614..a27b3ffe67 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx
@@ -279,11 +279,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {
);
const perfSource = useMemo<WorkflowPerfSource>(
() => ({
- instanceId: runtime.instanceId,
- kind: 'widget',
+ area: 'editor',
+ namespace: 'workflows',
projectId,
- region: runtime.region,
- typeId: runtime.typeId,
+ widget: { instanceId: runtime.instanceId, region: runtime.region, typeId: runtime.typeId },
}),
[projectId, runtime.instanceId, runtime.region, runtime.typeId]
);
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
index a758b8f6eb..5910b5fda5 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
@@ -1,30 +1,16 @@
import { useMountEffect } from '@platform/react/useMountEffect';
import { createCanvasDimsSync } from './canvasDimsSync';
-import { configureDiagnostics } from './diagnostics/logger';
-import { subscribeWorkbenchPreferences } from './settings/store';
import { useWorkbenchInternalStore } from './WorkbenchContext';
-/**
- * Workbench-owned lifecycle adapter for aggregate-local synchronization and
- * diagnostics. Cross-module adapters are constructed by App.
- */
+/** Workbench-owned lifecycle adapter for aggregate-local synchronization. Cross-module adapters are constructed by App. */
export const WorkbenchRuntime = () => {
const store = useWorkbenchInternalStore();
useMountEffect(() => {
const canvasDimsSync = createCanvasDimsSync(store);
- const unsubscribeDiagnostics = subscribeWorkbenchPreferences((preferences) => {
- configureDiagnostics({
- enabled: preferences.developerLogEnabled,
- level: preferences.developerLogLevel,
- namespaces: preferences.developerLogNamespaces,
- performanceTimingsEnabled: preferences.developerPerformanceTimingsEnabled,
- });
- });
return () => {
- unsubscribeDiagnostics();
canvasDimsSync.dispose();
};
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index df365306e8..d4b4a6000e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -5035,7 +5035,10 @@ describe('requestLayerThumbnail', () => {
expect(reportError).toHaveBeenCalledWith(
expect.objectContaining({
area: 'canvas-engine',
- context: expect.objectContaining({ error: 'decode failed', layerId: 'a' }),
+ context: expect.objectContaining({
+ error: expect.objectContaining({ message: 'decode failed' }),
+ layerId: 'a',
+ }),
message: 'Layer thumbnail rasterization failed',
namespace: 'canvas',
projectId: 'p1',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 8e9493d410..b0c739b443 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -219,7 +219,8 @@ const createCleanupAccumulator = (): { run: (step: () => void) => void; throwIfF
export interface CanvasEngineErrorReport {
area: 'canvas-engine';
- context: { error: string; layerId: string };
+ /** The raw failure; notifications show its message and diagnostics keep its stack. */
+ context: { error: unknown; layerId: string };
message:
| 'Layer thumbnail rasterization failed'
| 'Bitmap persistence failed'
@@ -333,7 +334,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const reportError = (message: CanvasEngineErrorReport['message'], layerId: string, error: unknown): void =>
opts.reportError({
area: 'canvas-engine',
- context: { error: error instanceof Error ? error.message : String(error), layerId },
+ context: { error, layerId },
message,
namespace: 'canvas',
projectId,
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts
deleted file mode 100644
index 2cfd8b3976..0000000000
--- a/invokeai/frontend/webv2/src/workbench/diagnostics/contracts.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/** Theme ids select palettes through html data-theme and the semantic-token conditions. */
-export type DeveloperLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
-
-export type DeveloperLogNamespace =
- | 'canvas'
- | 'canvas-workflow-integration'
- | 'config'
- | 'dnd'
- | 'events'
- | 'gallery'
- | 'generation'
- | 'metadata'
- | 'models'
- | 'system'
- | 'queue'
- | 'workflows';
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts
deleted file mode 100644
index bd50a5df31..0000000000
--- a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { accountLifecycle } from '@platform/state/accountLifecycle';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- clearProjectDiagnostics,
- configureDiagnostics,
- createProjectLogger,
- getProjectDiagnostics,
- recordDiagnosticTiming,
-} from './logger';
-
-beforeEach(() => {
- clearProjectDiagnostics('project-a');
- clearProjectDiagnostics('project-b');
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: ['workflows', 'system', 'queue'],
- performanceTimingsEnabled: true,
- });
- vi.setSystemTime(new Date('2026-06-29T00:00:00.000Z'));
-});
-
-describe('diagnostics logger', () => {
- it('records entries scoped to the source project', () => {
- const logger = createProjectLogger('workflows', {
- instanceId: 'workflow:center',
- kind: 'widget',
- projectId: 'project-a',
- region: 'center',
- typeId: 'workflow',
- });
-
- logger.info({ nodes: 120 }, 'Workflow loaded');
-
- expect(getProjectDiagnostics('project-a')).toMatchObject([
- {
- context: { nodes: 120 },
- createdAt: '2026-06-29T00:00:00.000Z',
- level: 'info',
- message: 'Workflow loaded',
- namespace: 'workflows',
- source: {
- instanceId: 'workflow:center',
- kind: 'widget',
- projectId: 'project-a',
- region: 'center',
- typeId: 'workflow',
- },
- },
- ]);
- expect(getProjectDiagnostics('project-b')).toEqual([]);
- });
-
- it('records timing entries as normal diagnostics', () => {
- recordDiagnosticTiming({ area: 'persistence', kind: 'workbench', projectId: 'project-a' }, 'workbench:save', 12.34);
-
- expect(getProjectDiagnostics('project-a')).toMatchObject([
- {
- durationMs: 12.34,
- level: 'debug',
- message: 'workbench:save completed in 12.3ms',
- namespace: 'performance',
- source: { area: 'persistence', kind: 'workbench', projectId: 'project-a' },
- },
- ]);
- });
-
- it('clears a single project without clearing other projects', () => {
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).error('A failed');
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-b' }).warn('B warned');
-
- clearProjectDiagnostics('project-a');
-
- expect(getProjectDiagnostics('project-a')).toEqual([]);
- expect(getProjectDiagnostics('project-b')).toHaveLength(1);
- });
-
- it('clears every project synchronously when its account lifetime expires', () => {
- accountLifecycle.activate('user-a');
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).error('A failed');
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-b' }).warn('B warned');
-
- accountLifecycle.invalidate();
-
- expect(getProjectDiagnostics('project-a')).toEqual([]);
- expect(getProjectDiagnostics('project-b')).toEqual([]);
- });
-
- it('filters entries by project logging settings', () => {
- configureDiagnostics({
- enabled: true,
- level: 'warn',
- namespaces: ['system'],
- performanceTimingsEnabled: true,
- });
-
- createProjectLogger('workflows', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).error(
- 'Wrong namespace'
- );
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).debug('Too quiet');
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).warn('Recorded');
-
- expect(getProjectDiagnostics('project-a')).toMatchObject([{ level: 'warn', message: 'Recorded' }]);
- });
-
- it('can disable project diagnostics and performance timings independently', () => {
- configureDiagnostics({
- enabled: false,
- level: 'trace',
- namespaces: ['system'],
- performanceTimingsEnabled: true,
- });
-
- createProjectLogger('system', { area: 'runtime', kind: 'workbench', projectId: 'project-a' }).error('Skipped');
-
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: ['system'],
- performanceTimingsEnabled: false,
- });
-
- recordDiagnosticTiming({ area: 'runtime', kind: 'workbench', projectId: 'project-a' }, 'workbench:test', 1.2);
-
- expect(getProjectDiagnostics('project-a')).toEqual([]);
- });
-
- it('applies the current diagnostics config to every project', () => {
- configureDiagnostics({
- enabled: true,
- level: 'warn',
- namespaces: ['queue'],
- performanceTimingsEnabled: true,
- });
-
- createProjectLogger('queue', { area: 'autosave', kind: 'workbench', projectId: 'project-b' }).error('Recorded');
-
- expect(getProjectDiagnostics('project-b')).toMatchObject([{ level: 'error', message: 'Recorded' }]);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts
deleted file mode 100644
index 07018b8320..0000000000
--- a/invokeai/frontend/webv2/src/workbench/diagnostics/logger.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
-import type { WidgetContributionSource } from '@workbench/widgetContracts';
-
-import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
-import { useSyncExternalStore } from 'react';
-
-const MAX_PROJECT_DIAGNOSTIC_ENTRIES = 500;
-const EMPTY_DIAGNOSTIC_ENTRIES: DiagnosticEntry[] = [];
-
-const LOG_LEVEL_ORDER: Record<DeveloperLogLevel, number> = {
- debug: 20,
- error: 50,
- fatal: 60,
- info: 30,
- trace: 10,
- warn: 40,
-};
-
-export type DiagnosticSource =
- | ({ kind: 'widget' } & WidgetContributionSource)
- | { area: string; kind: 'workbench'; projectId?: string };
-
-export interface DiagnosticEntry {
- context?: Record<string, unknown>;
- createdAt: string;
- durationMs?: number;
- id: string;
- level: DeveloperLogLevel;
- message: string;
- namespace: DeveloperLogNamespace | 'performance';
- source: DiagnosticSource;
-}
-
-export interface DiagnosticsConfig {
- enabled: boolean;
- level: DeveloperLogLevel;
- namespaces: DeveloperLogNamespace[];
- performanceTimingsEnabled: boolean;
-}
-
-type DiagnosticListener = () => void;
-
-type LogArgument = string | Record<string, unknown>;
-
-const entriesByProjectId = new Map<string, DiagnosticEntry[]>();
-const listenersByProjectId = new Map<string, Set<DiagnosticListener>>();
-
-let diagnosticsConfig: DiagnosticsConfig = {
- enabled: true,
- level: 'warn',
- namespaces: ['system', 'queue', 'workflows'],
- performanceTimingsEnabled: false,
-};
-
-let nextDiagnosticEntryId = 0;
-
-const getProjectIdFromSource = (source: DiagnosticSource): string | null => source.projectId ?? null;
-
-const shouldRecordEntry = (entry: Omit<DiagnosticEntry, 'createdAt' | 'id'>): boolean => {
- if (entry.namespace === 'performance') {
- return diagnosticsConfig.performanceTimingsEnabled;
- }
-
- return (
- diagnosticsConfig.enabled &&
- LOG_LEVEL_ORDER[entry.level] >= LOG_LEVEL_ORDER[diagnosticsConfig.level] &&
- diagnosticsConfig.namespaces.includes(entry.namespace)
- );
-};
-
-const getProjectEntries = (projectId: string): DiagnosticEntry[] => {
- const entries = entriesByProjectId.get(projectId) ?? [];
-
- if (!entriesByProjectId.has(projectId)) {
- entriesByProjectId.set(projectId, entries);
- }
-
- return entries;
-};
-
-const getProjectEntriesSnapshot = (projectId: string): DiagnosticEntry[] =>
- entriesByProjectId.get(projectId) ?? EMPTY_DIAGNOSTIC_ENTRIES;
-
-const notifyProjectDiagnostics = (projectId: string): void => {
- for (const listener of listenersByProjectId.get(projectId) ?? []) {
- listener();
- }
-};
-
-const normalizeLogArgs = (
- first: LogArgument,
- second?: string
-): { context?: Record<string, unknown>; message: string } => {
- if (typeof first === 'string') {
- return { message: first };
- }
-
- return { context: first, message: second ?? '' };
-};
-
-export const recordDiagnosticEntry = (entry: Omit<DiagnosticEntry, 'createdAt' | 'id'>): DiagnosticEntry | null => {
- const projectId = getProjectIdFromSource(entry.source);
-
- if (!projectId) {
- return null;
- }
-
- if (!shouldRecordEntry(entry)) {
- return null;
- }
-
- const nextEntry: DiagnosticEntry = {
- ...entry,
- createdAt: new Date().toISOString(),
- id: `diagnostic-${nextDiagnosticEntryId++}`,
- };
- const entries = [nextEntry, ...getProjectEntries(projectId)].slice(0, MAX_PROJECT_DIAGNOSTIC_ENTRIES);
-
- entriesByProjectId.set(projectId, entries);
-
- notifyProjectDiagnostics(projectId);
-
- return nextEntry;
-};
-
-export const createProjectLogger = (namespace: DeveloperLogNamespace, source: DiagnosticSource) => {
- const log = (level: DeveloperLogLevel, first: LogArgument, second?: string): void => {
- const { context, message } = normalizeLogArgs(first, second);
-
- recordDiagnosticEntry({ context, level, message, namespace, source });
- };
-
- return {
- debug: (first: LogArgument, second?: string) => log('debug', first, second),
- error: (first: LogArgument, second?: string) => log('error', first, second),
- fatal: (first: LogArgument, second?: string) => log('fatal', first, second),
- info: (first: LogArgument, second?: string) => log('info', first, second),
- trace: (first: LogArgument, second?: string) => log('trace', first, second),
- warn: (first: LogArgument, second?: string) => log('warn', first, second),
- };
-};
-
-export const configureDiagnostics = (config: DiagnosticsConfig): void => {
- diagnosticsConfig = { ...config, namespaces: [...config.namespaces] };
-};
-
-export const canRecordDiagnosticTiming = (source?: DiagnosticSource): source is DiagnosticSource => {
- if (!source?.projectId) {
- return false;
- }
-
- return diagnosticsConfig.performanceTimingsEnabled;
-};
-
-export const recordDiagnosticTiming = (
- source: DiagnosticSource,
- name: string,
- durationMs: number
-): DiagnosticEntry | null =>
- recordDiagnosticEntry({
- durationMs,
- level: 'debug',
- message: `${name} completed in ${durationMs.toFixed(1)}ms`,
- namespace: 'performance',
- source,
- });
-
-export const getProjectDiagnostics = (projectId: string): DiagnosticEntry[] => [...getProjectEntries(projectId)];
-
-export const useProjectDiagnostics = (projectId: string): DiagnosticEntry[] =>
- useSyncExternalStore(
- (listener) => subscribeProjectDiagnostics(projectId, listener),
- () => getProjectEntriesSnapshot(projectId),
- () => EMPTY_DIAGNOSTIC_ENTRIES
- );
-
-export const clearProjectDiagnostics = (projectId: string): void => {
- entriesByProjectId.delete(projectId);
- notifyProjectDiagnostics(projectId);
-};
-
-export const clearAllProjectDiagnostics = (): void => {
- const projectIds = [...entriesByProjectId.keys()];
-
- entriesByProjectId.clear();
- for (const projectId of projectIds) {
- notifyProjectDiagnostics(projectId);
- }
-};
-
-registerAccountOwnedResource({
- clear: clearAllProjectDiagnostics,
- name: 'project-diagnostics',
-});
-
-export const subscribeProjectDiagnostics = (projectId: string, listener: DiagnosticListener): (() => void) => {
- const listeners = listenersByProjectId.get(projectId) ?? new Set<DiagnosticListener>();
-
- listeners.add(listener);
- listenersByProjectId.set(projectId, listeners);
-
- return () => {
- listeners.delete(listener);
-
- if (listeners.size === 0) {
- listenersByProjectId.delete(projectId);
- }
- };
-};
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.test.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.test.ts
new file mode 100644
index 0000000000..ca57d295dc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.test.ts
@@ -0,0 +1,32 @@
+import { DEFAULT_LOGGING_CONFIG, LOG_NAMESPACES } from '@platform/logging/contracts';
+import { DEFAULT_PREFERENCES, normalizeWorkbenchPreferences } from '@workbench/settings/store';
+import { describe, expect, it } from 'vitest';
+
+import { areLoggingPreferencesDefault, toLoggingConfig } from './loggingPreferences';
+
+describe('loggingPreferences', () => {
+ it('maps default preferences onto the default capture settings', () => {
+ expect(toLoggingConfig(DEFAULT_PREFERENCES)).toEqual({
+ ...DEFAULT_LOGGING_CONFIG,
+ namespaces: [...LOG_NAMESPACES],
+ });
+ expect(areLoggingPreferencesDefault(DEFAULT_PREFERENCES)).toBe(true);
+ });
+
+ it('keeps a saved narrowed selection and console opt-in and reports them as non-default', () => {
+ const preferences = normalizeWorkbenchPreferences({
+ developerConsoleOutputEnabled: true,
+ developerLogLevel: 'debug',
+ developerLogNamespaces: ['queue'],
+ });
+
+ expect(toLoggingConfig(preferences)).toEqual({
+ consoleOutputEnabled: true,
+ enabled: true,
+ level: 'debug',
+ namespaces: ['queue'],
+ performanceTimingsEnabled: false,
+ });
+ expect(areLoggingPreferencesDefault(preferences)).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.ts b/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.ts
new file mode 100644
index 0000000000..ceb48e07ed
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/loggingPreferences.ts
@@ -0,0 +1,40 @@
+import type { LoggingConfig } from '@platform/logging/contracts';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+
+import { DEFAULT_PREFERENCES, patchWorkbenchPreferences } from '@workbench/settings/store';
+
+export const LOGGING_PREFERENCE_KEYS = [
+ 'developerConsoleOutputEnabled',
+ 'developerLogEnabled',
+ 'developerLogLevel',
+ 'developerLogNamespaces',
+ 'developerPerformanceTimingsEnabled',
+] as const satisfies readonly (keyof WorkbenchPreferences)[];
+
+export const toLoggingConfig = (preferences: WorkbenchPreferences): LoggingConfig => ({
+ consoleOutputEnabled: preferences.developerConsoleOutputEnabled,
+ enabled: preferences.developerLogEnabled,
+ level: preferences.developerLogLevel,
+ namespaces: preferences.developerLogNamespaces,
+ performanceTimingsEnabled: preferences.developerPerformanceTimingsEnabled,
+});
+
+export const areLoggingPreferencesDefault = (preferences: WorkbenchPreferences): boolean =>
+ LOGGING_PREFERENCE_KEYS.every((key) => {
+ const value = preferences[key];
+ const fallback = DEFAULT_PREFERENCES[key];
+
+ return Array.isArray(value) && Array.isArray(fallback)
+ ? value.length === fallback.length && value.every((item, index) => item === fallback[index])
+ : value === fallback;
+ });
+
+/** Restores default capture settings, including namespaces saved before newer namespaces existed. */
+export const resetLoggingPreferences = (): Promise<void> =>
+ patchWorkbenchPreferences({
+ developerConsoleOutputEnabled: DEFAULT_PREFERENCES.developerConsoleOutputEnabled,
+ developerLogEnabled: DEFAULT_PREFERENCES.developerLogEnabled,
+ developerLogLevel: DEFAULT_PREFERENCES.developerLogLevel,
+ developerLogNamespaces: [...DEFAULT_PREFERENCES.developerLogNamespaces],
+ developerPerformanceTimingsEnabled: DEFAULT_PREFERENCES.developerPerformanceTimingsEnabled,
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts
index e9ec506a91..c51869af43 100644
--- a/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts
@@ -1,16 +1,14 @@
+import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';
+import { configureLogging, getLogSnapshot, resetLogging } from '@platform/logging/logger';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from './diagnostics/logger';
import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from './performanceMarks';
+const source = { area: 'editor', namespace: 'workflows' as const, projectId: 'project-a' };
+
beforeEach(() => {
- clearProjectDiagnostics('project-a');
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: [],
- performanceTimingsEnabled: true,
- });
+ resetLogging();
+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, namespaces: [], performanceTimingsEnabled: true });
vi.spyOn(performance, 'mark').mockImplementation((name: string) => ({ name }) as PerformanceMark);
vi.spyOn(performance, 'measure').mockImplementation(
(name: string) => ({ duration: 12.34, name }) as PerformanceMeasure
@@ -19,42 +17,40 @@ beforeEach(() => {
});
describe('performanceMarks', () => {
- it('does nothing when no diagnostic source is provided', () => {
+ it('does nothing when no source is provided', () => {
markWorkbenchPerf('workflow:test');
measureWorkbenchPerf('workflow:measure', 'workflow:test');
expect(performance.mark).not.toHaveBeenCalled();
expect(performance.measure).not.toHaveBeenCalled();
- expect(getProjectDiagnostics('project-a')).toEqual([]);
+ expect(getLogSnapshot().entries).toEqual([]);
});
- it('marks, measures and records timings for the provided diagnostic source', () => {
- const source = { area: 'test', kind: 'workbench' as const, projectId: 'project-a' };
+ it('marks, measures and records timings for the provided source', () => {
const result = timeWorkbenchPerf('workflow:build', source, () => 42);
expect(result).toBe(42);
expect(performance.mark).toHaveBeenCalledWith('workflow:build:start');
expect(performance.mark).toHaveBeenCalledWith('workflow:build:end');
expect(performance.measure).toHaveBeenCalledWith('workflow:build', 'workflow:build:start', 'workflow:build:end');
- expect(getProjectDiagnostics('project-a')).toMatchObject([
- { durationMs: 12.34, message: 'workflow:build completed in 12.3ms', namespace: 'performance', source },
+ expect(getLogSnapshot().entries).toMatchObject([
+ {
+ durationMs: 12.34,
+ message: 'workflow:build completed in 12.3ms',
+ name: 'workflow:build',
+ namespace: 'performance',
+ source,
+ },
]);
});
it('does not call the Performance API when timing collection is disabled', () => {
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: [],
- performanceTimingsEnabled: false,
- });
-
- const source = { area: 'test', kind: 'workbench' as const, projectId: 'project-a' };
+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, performanceTimingsEnabled: false });
timeWorkbenchPerf('workflow:build', source, () => 42);
expect(performance.mark).not.toHaveBeenCalled();
expect(performance.measure).not.toHaveBeenCalled();
- expect(getProjectDiagnostics('project-a')).toEqual([]);
+ expect(getLogSnapshot().entries).toEqual([]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.ts
index 5cd9d59a6f..b36f1d3a07 100644
--- a/invokeai/frontend/webv2/src/workbench/performanceMarks.ts
+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.ts
@@ -1,11 +1,13 @@
-import { canRecordDiagnosticTiming, recordDiagnosticTiming, type DiagnosticSource } from './diagnostics/logger';
+import type { LogSource } from '@platform/logging/contracts';
+
+import { canRecordTiming, recordTiming } from '@platform/logging/logger';
const hasPerformanceApi = (): boolean => typeof performance !== 'undefined' && typeof performance.mark === 'function';
-const canMeasurePerf = (source?: DiagnosticSource): source is DiagnosticSource =>
- hasPerformanceApi() && canRecordDiagnosticTiming(source);
+const canMeasurePerf = (source?: LogSource): source is LogSource =>
+ source !== undefined && hasPerformanceApi() && canRecordTiming();
-export const markWorkbenchPerf = (name: string, source?: DiagnosticSource): void => {
+export const markWorkbenchPerf = (name: string, source?: LogSource): void => {
if (!canMeasurePerf(source)) {
return;
}
@@ -13,12 +15,7 @@ export const markWorkbenchPerf = (name: string, source?: DiagnosticSource): void
performance.mark(name);
};
-export const measureWorkbenchPerf = (
- name: string,
- startMark: string,
- source?: DiagnosticSource,
- endMark?: string
-): void => {
+export const measureWorkbenchPerf = (name: string, startMark: string, source?: LogSource, endMark?: string): void => {
if (!canMeasurePerf(source)) {
return;
}
@@ -26,7 +23,7 @@ export const measureWorkbenchPerf = (
try {
const measure = endMark ? performance.measure(name, startMark, endMark) : performance.measure(name, startMark);
- recordDiagnosticTiming(source, measure.name, measure.duration);
+ recordTiming(source, measure.name, measure.duration);
performance.clearMeasures?.(name);
performance.clearMarks?.(startMark);
@@ -38,7 +35,7 @@ export const measureWorkbenchPerf = (
}
};
-export const timeWorkbenchPerf = <T>(name: string, source: DiagnosticSource | undefined, callback: () => T): T => {
+export const timeWorkbenchPerf = <T>(name: string, source: LogSource | undefined, callback: () => T): T => {
if (!canMeasurePerf(source)) {
return callback();
}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
index 6303410270..f58c30ee5c 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
@@ -1,6 +1,6 @@
+import type { LogNamespace } from '@platform/logging/contracts';
import type { SettingFieldProps } from '@platform/ui/settings/contracts';
import type { WorkbenchThemeId } from '@theme/themes';
-import type { DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
import { Box, chakra, Checkbox, Flex, HStack, Icon, SimpleGrid, Stack, Text, useSlotRecipe } from '@chakra-ui/react';
import { Button, ConfirmDialog } from '@platform/ui';
@@ -8,6 +8,7 @@ import { resolveSettingsText } from '@platform/ui/settings/contracts';
import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';
import { themeCardRecipe } from '@theme/recipes';
import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';
+import { areLoggingPreferencesDefault, resetLoggingPreferences } from '@workbench/diagnostics/loggingPreferences';
import { clearAllWorkbenchData } from '@workbench/projects/syncedPersistence';
import { useOptionalWorkbenchCommands, useOptionalWorkbenchPersistenceService } from '@workbench/WorkbenchContext';
import { CheckIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';
@@ -86,7 +87,7 @@ export const DeveloperNamespacesSettings = () => {
const developerLogNamespaces = useWorkbenchPreferenceSelector((preferences) => preferences.developerLogNamespaces);
const enabledNamespaces = useMemo(() => new Set(developerLogNamespaces), [developerLogNamespaces]);
const toggleNamespace = useCallback(
- (namespace: DeveloperLogNamespace, checked: boolean) => {
+ (namespace: LogNamespace, checked: boolean) => {
const next = checked
? [...developerLogNamespaces, namespace]
: developerLogNamespaces.filter((candidate) => candidate !== namespace);
@@ -118,8 +119,8 @@ const DeveloperNamespaceCheckbox = ({
toggleNamespace,
}: {
checked: boolean;
- namespace: DeveloperLogNamespace;
- toggleNamespace: (namespace: DeveloperLogNamespace, checked: boolean) => void;
+ namespace: LogNamespace;
+ toggleNamespace: (namespace: LogNamespace, checked: boolean) => void;
}) => {
const handleCheckedChange = useCallback(
(event: { checked: boolean | 'indeterminate' }) => toggleNamespace(namespace, event.checked === true),
@@ -137,6 +138,26 @@ const DeveloperNamespaceCheckbox = ({
);
};
+export const LoggingResetSettings = () => {
+ const { t } = useTranslation();
+ const isDefault = useWorkbenchPreferenceSelector(areLoggingPreferencesDefault);
+ const reset = useCallback(() => void resetLoggingPreferences(), []);
+
+ return (
+ <HStack gap="3">
+ <Button disabled={isDefault} size="sm" variant="outline" onClick={reset}>
+ <RotateCcwIcon />
+ {t('settings.catalog.resetLoggingDefaults')}
+ </Button>
+ {isDefault ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('settings.catalog.loggingDefaultsActive')}
+ </Text>
+ ) : null}
+ </HStack>
+ );
+};
+
export const WorkspaceSettings = () => {
const commands = useOptionalWorkbenchCommands();
const mountedPersistence = useOptionalWorkbenchPersistenceService();
@@ -230,6 +251,9 @@ const CustomSettingField = ({ field }: SettingFieldProps) => {
case 'developerLogNamespaces':
editor = <DeveloperNamespacesSettings />;
break;
+ case 'developerLoggingReset':
+ editor = <LoggingResetSettings />;
+ break;
case 'workspaceActions':
editor = <WorkspaceSettings />;
break;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
index 6c88cd5db7..0d70b84c0d 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
@@ -122,8 +122,10 @@ export const developerSettings = section('developer', 'Developer', [
label: text(`options.${value}`, value.charAt(0).toUpperCase() + value.slice(1)),
})),
},
+ preference('developerConsoleOutputEnabled', 'Mirror logs to the browser console', 'console devtools'),
preference('developerPerformanceTimingsEnabled', 'Collect performance timings', 'diagnostics'),
custom('developerLogNamespaces', 'Log namespaces'),
+ custom('developerLoggingReset', 'Reset logging defaults', 'preference'),
]);
export const serverSettings = section('server', 'Server', [
custom('generationDevices', 'Generation devices', 'server'),
diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
index 6496144fc5..5e0fd6637d 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
@@ -1,7 +1,7 @@
import type { WorkbenchLanguage } from '@platform/i18n/languages';
+import type { LogLevel, LogNamespace } from '@platform/logging/contracts';
import type { SettingsTarget } from '@platform/ui/settings/contracts';
import type { WorkbenchThemeId } from '@theme/themes';
-import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
import type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';
export type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';
@@ -62,8 +62,10 @@ export interface WorkbenchPreferences {
/** Color prompt syntax in prompt fields; changes rendering only. */
showPromptSyntaxHighlighting: boolean;
developerLogEnabled: boolean;
- developerLogLevel: DeveloperLogLevel;
- developerLogNamespaces: DeveloperLogNamespace[];
+ developerLogLevel: LogLevel;
+ developerLogNamespaces: LogNamespace[];
+ /** Mirror recorded entries to the browser console; obeys the same recording filters. */
+ developerConsoleOutputEnabled: boolean;
developerPerformanceTimingsEnabled: boolean;
/** Always snap workflow nodes to the grid (Ctrl snaps temporarily when off). */
workflowSnapToGrid: boolean;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
index 2a34b4c719..8d6e54249a 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts
@@ -1,5 +1,6 @@
import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+import { LOG_NAMESPACES } from '@platform/logging/contracts';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProjectSettings } from './contracts';
@@ -406,12 +407,28 @@ describe('normalizeWorkbenchPreferences diagnostics', () => {
developerPerformanceTimingsEnabled: true,
})
).toMatchObject({
+ developerConsoleOutputEnabled: false,
developerLogEnabled: true,
developerLogLevel: 'warn',
developerLogNamespaces: ['system'],
developerPerformanceTimingsEnabled: true,
});
});
+
+ it('records warnings from every namespace by default and keeps a saved narrower selection', () => {
+ expect(store.normalizeWorkbenchPreferences({}).developerLogNamespaces).toEqual(LOG_NAMESPACES);
+ // The previous default was persisted by any settings write; it is not a user's narrowed choice.
+ expect(
+ store.normalizeWorkbenchPreferences({ developerLogNamespaces: ['workflows', 'queue', 'system'] })
+ .developerLogNamespaces
+ ).toEqual(LOG_NAMESPACES);
+ expect(
+ store.normalizeWorkbenchPreferences({ developerLogNamespaces: ['workflows', 'queue'] }).developerLogNamespaces
+ ).toEqual(['queue', 'workflows']);
+ expect(
+ store.normalizeWorkbenchPreferences({ developerConsoleOutputEnabled: true }).developerConsoleOutputEnabled
+ ).toBe(true);
+ });
});
describe('normalizeWorkbenchPreferences auto-switch invoke route', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.ts
index 54c90dcc36..1e7e693a49 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts
@@ -1,4 +1,4 @@
-import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
+import type { LogLevel, LogNamespace } from '@platform/logging/contracts';
import type {
ProjectSettings,
ProjectSortId,
@@ -10,6 +10,7 @@ import type {
import { getUserStorageScope } from '@features/identity';
import { normalizeWorkbenchLanguage } from '@platform/i18n/languages';
+import { isLogLevel, isLogNamespace, LOG_LEVELS, LOG_NAMESPACES } from '@platform/logging/contracts';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -29,22 +30,9 @@ const SETTINGS_BASE_STORAGE_KEY = 'invokeai:v7:webv2:settings';
const LEGACY_WORKBENCH_BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';
const SETTINGS_CLIENT_STATE_KEY = 'webv2:workbench-settings';
-export const DEVELOPER_LOG_LEVELS: DeveloperLogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
-
-export const DEVELOPER_LOG_NAMESPACES: DeveloperLogNamespace[] = [
- 'canvas',
- 'canvas-workflow-integration',
- 'config',
- 'dnd',
- 'events',
- 'gallery',
- 'generation',
- 'metadata',
- 'models',
- 'system',
- 'queue',
- 'workflows',
-];
+export const DEVELOPER_LOG_LEVELS: readonly LogLevel[] = LOG_LEVELS;
+
+export const DEVELOPER_LOG_NAMESPACES: readonly LogNamespace[] = LOG_NAMESPACES;
export const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {
antialiasProgressImages: false,
@@ -57,9 +45,10 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {
autoSwitchInvocationRoute: true,
confirmImageDeletion: true,
customHotkeys: {},
+ developerConsoleOutputEnabled: false,
developerLogEnabled: true,
developerLogLevel: 'warn',
- developerLogNamespaces: ['system', 'queue', 'workflows'],
+ developerLogNamespaces: [...LOG_NAMESPACES],
developerPerformanceTimingsEnabled: false,
enableInformationalPopovers: true,
enableModelDescriptions: true,
@@ -129,22 +118,22 @@ const getLegacyWorkbenchStorageKey = (storageSuffix = getUserStorageScope()): st
const getSettingsScope = (storageSuffix = getUserStorageScope()): WorkbenchSettingsSnapshot['scope'] =>
storageSuffix ? 'user' : 'global';
-const isDeveloperLogLevel = (value: unknown): value is DeveloperLogLevel =>
- typeof value === 'string' && DEVELOPER_LOG_LEVELS.includes(value as DeveloperLogLevel);
+/** The pre-2026-09 default; installs that merely persisted it never chose a narrowed selection. */
+const LEGACY_DEFAULT_LOG_NAMESPACES: readonly LogNamespace[] = ['queue', 'system', 'workflows'];
-const normalizeDeveloperLogNamespaces = (values: unknown): DeveloperLogNamespace[] => {
+/** A user-narrowed selection stays narrowed, including namespaces added after it was saved; reset restores defaults. */
+const normalizeDeveloperLogNamespaces = (values: unknown): LogNamespace[] => {
if (!Array.isArray(values)) {
return [...DEFAULT_PREFERENCES.developerLogNamespaces];
}
- const enabled = new Set(
- values.filter(
- (value): value is DeveloperLogNamespace =>
- typeof value === 'string' && DEVELOPER_LOG_NAMESPACES.includes(value as DeveloperLogNamespace)
- )
- );
+ const enabled = new Set(values.filter(isLogNamespace));
+ const selected = LOG_NAMESPACES.filter((namespace) => enabled.has(namespace));
+ const isLegacyDefault =
+ selected.length === LEGACY_DEFAULT_LOG_NAMESPACES.length &&
+ selected.every((namespace, index) => namespace === LEGACY_DEFAULT_LOG_NAMESPACES[index]);
- return DEVELOPER_LOG_NAMESPACES.filter((namespace) => enabled.has(namespace));
+ return isLegacyDefault ? [...DEFAULT_PREFERENCES.developerLogNamespaces] : selected;
};
/** Keep view guards local so shared settings do not pull Launchpad code into the editor bundle. */
@@ -296,7 +285,11 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferences
typeof preferences?.developerLogEnabled === 'boolean'
? preferences.developerLogEnabled
: DEFAULT_PREFERENCES.developerLogEnabled,
- developerLogLevel: isDeveloperLogLevel(preferences?.developerLogLevel)
+ developerConsoleOutputEnabled:
+ typeof preferences?.developerConsoleOutputEnabled === 'boolean'
+ ? preferences.developerConsoleOutputEnabled
+ : DEFAULT_PREFERENCES.developerConsoleOutputEnabled,
+ developerLogLevel: isLogLevel(preferences?.developerLogLevel)
? preferences.developerLogLevel
: DEFAULT_PREFERENCES.developerLogLevel,
developerLogNamespaces: normalizeDeveloperLogNamespaces(preferences?.developerLogNamespaces),
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
index 9dae9f664c..522cb1d55c 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
@@ -9,7 +9,8 @@ import type {
import type { WorkbenchAction } from '@workbench/workbenchState.testing';
import type { WorkbenchWidgetCommands } from '@workbench/workbenchStore';
-import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from '@workbench/diagnostics/logger';
+import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';
+import { configureLogging, getLogSnapshot, resetLogging } from '@platform/logging/logger';
import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';
import { createWidgetImplementationResource } from '@workbench/widgetImplementationResource';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -109,13 +110,8 @@ const createPlacementProject = (
describe('createWidgetRuntime', () => {
beforeEach(() => {
- clearProjectDiagnostics('project-1');
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: ['workflows'],
- performanceTimingsEnabled: false,
- });
+ resetLogging();
+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, level: 'trace', namespaces: ['workflows'] });
});
it('deep clones runtime state snapshots', () => {
@@ -170,17 +166,16 @@ describe('createWidgetRuntime', () => {
runtime.diagnostics.logger('workflows').info('Widget rendered');
- expect(getProjectDiagnostics('project-1')).toMatchObject([
+ expect(getLogSnapshot().entries).toMatchObject([
{
level: 'info',
message: 'Widget rendered',
namespace: 'workflows',
source: {
- instanceId: 'workflow:center',
- kind: 'widget',
+ area: 'workflow',
+ namespace: 'workflows',
projectId: 'project-1',
- region: 'center',
- typeId: 'workflow',
+ widget: { instanceId: 'workflow:center', region: 'center', typeId: 'workflow' },
},
},
]);
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts
index 2a61ef6a7c..3f4ee96c13 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts
@@ -15,7 +15,7 @@ import type {
import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';
import type { WorkbenchWidgetCommands } from '@workbench/workbenchStore';
-import { createProjectLogger } from '@workbench/diagnostics/logger';
+import { createLogger } from '@platform/logging/logger';
import { isWidgetRegion as isKnownWidgetRegion } from '@workbench/layoutContracts';
import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';
import { useWorkbenchExtensions, useWorkbenchInternalStore } from '@workbench/WorkbenchContext';
@@ -105,7 +105,13 @@ export const createWidgetRuntime = ({
register: (menu) => extensions.menus.register({ ...menu, source }),
} satisfies WidgetRuntimeApi['menus'];
const diagnostics = {
- logger: (namespace) => createProjectLogger(namespace, { ...source, kind: 'widget' }),
+ logger: (namespace) =>
+ createLogger({
+ area: instance.typeId,
+ namespace,
+ projectId: sourceProjectId,
+ widget: { instanceId: instance.id, region, typeId: instance.typeId },
+ }),
} satisfies WidgetRuntimeApi['diagnostics'];
return {
diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
index 9268070a0f..261ea689db 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
@@ -1,9 +1,9 @@
+import type { Logger, LogNamespace } from '@platform/logging/contracts';
import type { SettingsContribution } from '@platform/ui/settings/contracts';
import type { TFunction } from 'i18next';
import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';
import type { DeferredResource, DeferredResourceStatus } from './deferredResource';
-import type { DeveloperLogNamespace } from './diagnostics/contracts';
import type { GraphId } from './graphContracts';
import type { InvocationSourceId } from './invocationContracts';
import type { WidgetRegion } from './layoutContracts';
@@ -142,14 +142,8 @@ export interface WidgetRuntimeApi<State extends Record<string, unknown> = Record
}
export interface WidgetDiagnosticsApi {
- logger: (namespace: DeveloperLogNamespace) => {
- debug: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- error: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- fatal: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- info: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- trace: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- warn: (messageOrContext: string | Record<string, unknown>, message?: string) => void;
- };
+ /** A logger attributed to this widget instance and its project. */
+ logger: (namespace: LogNamespace) => Logger;
}
export interface WidgetRuntimeStateApi<State extends Record<string, unknown> = Record<string, unknown>> {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 0737a97373..ec5620842d 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -3,13 +3,13 @@ import type { ModelConfig } from '@features/models';
import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';
import type { ProjectGraphState } from '@features/workflow/contracts';
import type { WorkflowSubmissionPlan } from '@features/workflow/graph';
+import type { LogNamespace } from '@platform/logging/contracts';
import type {
CanvasDocumentContractV3,
CanvasPlacementContract,
CanvasStateContractV3,
CanvasStagingCandidateContract,
} from '@workbench/canvas-engine/api';
-import type { DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
import type { GraphContract } from '@workbench/graphContracts';
import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';
import type {
@@ -74,6 +74,7 @@ import {
type GeneratedImageContract,
} from '@features/gallery/contracts';
import { planSeedSubmission } from '@platform/core/seed';
+import { describeError } from '@platform/logging/normalize';
import { WIDGET_REGIONS } from '@workbench/layoutContracts';
import { prependProjectEvent, PROJECT_EVENT_LIMIT } from '@workbench/projectEvents';
@@ -446,8 +447,9 @@ type WorkbenchReducerAction =
type: 'recordError';
message: string;
area?: string;
- context?: { error?: string; layerId?: string };
- namespace?: DeveloperLogNamespace;
+ /** `error` may be a raw Error; notifications show its message and diagnostics keep its stack. */
+ context?: { error?: unknown; [key: string]: unknown };
+ namespace?: LogNamespace;
projectId?: string;
}
| { type: 'setBackendConnectionStatus'; status: WorkbenchState['backendConnection']['status']; error?: string }
@@ -5019,7 +5021,7 @@ export const __workbenchReducerInternal = (
);
}
case 'recordError': {
- const detail = action.context?.error;
+ const detail = describeError(action.context?.error);
return addNotification(
state,
createNotification({
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index def0669086..126faca5ea 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -1,3 +1,5 @@
+import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';
+import { configureLogging, getLogSnapshot, resetLogging } from '@platform/logging/logger';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -5,7 +7,6 @@ import type { CanvasLayerContract } from './canvas-engine/contracts';
import type { LayoutPreset, LayoutPresetRoute } from './layoutContracts';
import type { WorkbenchInternalStore, WorkbenchSnapshot } from './workbenchStore';
-import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from './diagnostics/logger';
import { publishLayerPanelSelection, readLayerPanelState, toggleLayerStackCollapsed } from './layerPanelState';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from './widgetPlacementMeta';
import { getProjectWidgetValues } from './widgetState';
@@ -57,12 +58,8 @@ const watchSelector = <Selected>(
describe('createWorkbenchStore', () => {
beforeEach(() => {
- configureDiagnostics({
- enabled: true,
- level: 'trace',
- namespaces: ['system', 'queue'],
- performanceTimingsEnabled: false,
- });
+ resetLogging();
+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, level: 'trace' });
});
it('exposes stable capability interfaces and initializes snapshot metadata', () => {
@@ -459,22 +456,58 @@ describe('createWorkbenchStore', () => {
const store = createWorkbenchStore();
const projectId = store.getSnapshot().activeProject.id;
- clearProjectDiagnostics(projectId);
+ const error = new Error('socket closed');
+
store.commands.notifications.reportError({
area: 'queue-runtime',
+ context: { error, itemId: 'item-1' },
message: 'Queue failed',
namespace: 'queue',
});
- expect(getProjectDiagnostics(projectId)).toMatchObject([
+ expect(getLogSnapshot().entries).toMatchObject([
{
+ context: { itemId: 'item-1' },
+ error: { message: 'socket closed', name: 'Error' },
level: 'error',
message: 'Queue failed',
+ name: 'queue.queue-runtime',
namespace: 'queue',
- source: { area: 'queue-runtime', kind: 'workbench', projectId },
+ source: { area: 'queue-runtime', namespace: 'queue', projectId },
+ },
+ ]);
+ expect(store.getSnapshot().notifications[0]).toMatchObject({
+ message: 'Queue failed: socket closed',
+ title: 'Error',
+ });
+ });
+
+ it('records autosave outcomes and queue item transitions with the history owner as the only reporter', () => {
+ const store = createWorkbenchStore();
+ const projectId = store.getSnapshot().activeProject.id;
+
+ store.internal.persistence.saveStarted();
+ store.internal.persistence.savePending('Autosave requires your attention.');
+ store.internal.persistence.saveFailed('Backend rejected the revision');
+ store.commands.queue.setStatus({ error: 'Out of memory', projectId, queueItemId: 'missing', status: 'failed' });
+
+ expect(getLogSnapshot().entries).toMatchObject([
+ {
+ context: { queueItemId: 'missing', reason: 'Out of memory', status: 'failed' },
+ level: 'error',
+ message: 'Queue item failed: Out of memory',
+ name: 'queue.item-failed',
+ source: { area: 'history', namespace: 'queue', projectId },
+ },
+ {
+ context: { reason: 'Backend rejected the revision' },
+ level: 'error',
+ name: 'persistence.autosave-failed',
+ source: { area: 'autosave', namespace: 'persistence', projectId },
},
+ { level: 'warn', name: 'persistence.autosave-pending' },
+ { level: 'debug', name: 'persistence.autosave-started' },
]);
- expect(store.getSnapshot().notifications[0]?.title).toBe('Error');
});
it('records accepted widget failures into diagnostics once', () => {
@@ -487,17 +520,17 @@ describe('createWorkbenchStore', () => {
widgetId: 'workflow' as const,
};
- clearProjectDiagnostics(projectId);
store.commands.notifications.recordWidgetFailure(failure);
store.commands.notifications.recordWidgetFailure(failure);
- expect(getProjectDiagnostics(projectId)).toMatchObject([
+ expect(getLogSnapshot().entries).toMatchObject([
{
- context: { widgetId: 'workflow' },
+ context: { details: 'Widget stack', widgetId: 'workflow' },
level: 'error',
- message: 'Widget stack',
+ message: 'Widget failed',
+ name: 'widget.registration-failed',
namespace: 'system',
- source: { area: 'widget-failure', kind: 'workbench', projectId },
+ source: { area: 'widget-failure', namespace: 'system', projectId },
},
]);
});
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index a3da47fd72..269dc757e2 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -7,6 +7,7 @@ import {
type GalleryImage,
type GeneratedImageContract,
} from '@features/gallery/contracts';
+import { recordLogEvent } from '@platform/logging/logger';
import { createExternalStore } from '@platform/state/externalStore';
import { closeWidgetOverlays } from '@platform/ui/widgetOverlayRegistry';
import { hasActiveQueueRuns, hasInFlightQueueRuns } from '@workbench/queue-integration/activeQueueRuns';
@@ -14,7 +15,6 @@ import { hasActiveQueueRuns, hasInFlightQueueRuns } from '@workbench/queue-integ
import type { CanvasEditIntent } from './autoRoutePolicy';
import type { CanvasProjectMutation } from './canvasProjectMutations';
-import { recordDiagnosticEntry } from './diagnostics/logger';
import { clearLayerPanelStates, reconcileLayerPanelStates } from './layerPanelState';
import { createLayoutPresetActivator, loadLayoutPresetWidgets } from './layoutPresetActivation';
import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';
@@ -601,6 +601,7 @@ const hasPersistedStateChanged = (previous: WorkbenchState, next: WorkbenchState
const getDiagnosticProjectId = (state: WorkbenchState, projectId?: string): string | undefined =>
projectId ?? getActiveProject(state)?.id;
+/** The store is the one diagnostic owner for reported errors, widget failures and autosave outcomes. */
const recordDiagnosticForAction = (
action: WorkbenchAction,
previousState: WorkbenchState,
@@ -608,19 +609,22 @@ const recordDiagnosticForAction = (
): void => {
switch (action.type) {
case 'recordError': {
- const projectId = getDiagnosticProjectId(nextState, action.projectId);
-
- if (!projectId) {
- return;
- }
-
- recordDiagnosticEntry({
- context: action.context,
- level: 'error',
- message: action.message,
- namespace: action.namespace ?? 'system',
- source: { area: action.area ?? 'runtime', kind: 'workbench', projectId },
- });
+ const { error, ...context } = action.context ?? {};
+
+ recordLogEvent(
+ 'error',
+ {
+ area: action.area ?? 'runtime',
+ namespace: action.namespace ?? 'system',
+ projectId: getDiagnosticProjectId(nextState, action.projectId),
+ },
+ {
+ context: Object.keys(context).length > 0 ? context : undefined,
+ error,
+ message: action.message,
+ name: `${action.namespace ?? 'system'}.${action.area ?? 'runtime'}`,
+ }
+ );
break;
}
case 'recordWidgetFailure': {
@@ -628,19 +632,15 @@ const recordDiagnosticForAction = (
return;
}
- const projectId = getDiagnosticProjectId(nextState);
-
- if (!projectId) {
- return;
- }
-
- recordDiagnosticEntry({
- context: { widgetId: action.failure.widgetId },
- level: 'error',
- message: action.failure.details,
- namespace: 'system',
- source: { area: 'widget-failure', kind: 'workbench', projectId },
- });
+ recordLogEvent(
+ 'error',
+ { area: 'widget-failure', namespace: 'system', projectId: getDiagnosticProjectId(nextState) },
+ {
+ context: { details: action.failure.details, widgetId: action.failure.widgetId },
+ message: action.failure.message,
+ name: 'widget.registration-failed',
+ }
+ );
break;
}
case 'closeProject': {
@@ -648,18 +648,96 @@ const recordDiagnosticForAction = (
return;
}
- const projectId = getDiagnosticProjectId(nextState, action.projectId);
-
- if (!projectId) {
+ recordLogEvent(
+ 'error',
+ {
+ area: 'project-lifecycle',
+ namespace: 'system',
+ projectId: getDiagnosticProjectId(nextState, action.projectId),
+ },
+ { message: 'At least one project must remain open.', name: 'project.close-refused' }
+ );
+ break;
+ }
+ case 'markQueueItemBackendSubmitted': {
+ recordLogEvent(
+ 'info',
+ { area: 'submission', namespace: 'queue', projectId: action.projectId },
+ {
+ context: {
+ backendBatchId: action.backendBatchId,
+ backendItemIds: action.backendItemIds,
+ queueItemId: action.queueItemId,
+ },
+ message: 'Queue item accepted by the backend',
+ name: 'queue.submitted',
+ }
+ );
+ break;
+ }
+ case 'setQueueItemStatus': {
+ if (Object.is(previousState, nextState)) {
return;
}
- recordDiagnosticEntry({
- level: 'error',
- message: 'At least one project must remain open.',
- namespace: 'system',
- source: { area: 'project-lifecycle', kind: 'workbench', projectId },
- });
+ const level = action.status === 'failed' ? 'error' : 'debug';
+
+ recordLogEvent(
+ level,
+ { area: 'history', namespace: 'queue', projectId: action.projectId },
+ {
+ context: { queueItemId: action.queueItemId, reason: action.error, status: action.status },
+ message:
+ action.status === 'failed'
+ ? `Queue item failed${action.error ? `: ${action.error}` : ''}`
+ : `Queue item ${action.status}`,
+ name: action.status === 'failed' ? 'queue.item-failed' : 'queue.item-status',
+ }
+ );
+ break;
+ }
+ case 'hydrateWorkbench': {
+ recordLogEvent(
+ 'info',
+ { area: 'hydration', namespace: 'persistence' },
+ {
+ context: { activeProjectId: nextState.activeProjectId, projectCount: nextState.projects.length },
+ message: 'Workbench hydrated',
+ name: 'persistence.hydrated',
+ }
+ );
+ break;
+ }
+ case 'autosaveStarted': {
+ recordLogEvent(
+ 'debug',
+ { area: 'autosave', namespace: 'persistence', projectId: nextState.activeProjectId },
+ { message: 'Autosave started', name: 'persistence.autosave-started' }
+ );
+ break;
+ }
+ case 'autosaveSucceeded': {
+ recordLogEvent(
+ 'debug',
+ { area: 'autosave', namespace: 'persistence', projectId: nextState.activeProjectId },
+ { context: { savedAt: action.savedAt }, message: 'Autosave succeeded', name: 'persistence.autosave-succeeded' }
+ );
+ break;
+ }
+ case 'autosavePending': {
+ recordLogEvent(
+ 'warn',
+ { area: 'autosave', namespace: 'persistence', projectId: nextState.activeProjectId },
+ { context: { reason: action.error }, message: 'Autosave needs attention', name: 'persistence.autosave-pending' }
+ );
+ break;
+ }
+ case 'autosaveFailed': {
+ recordLogEvent(
+ 'error',
+ { area: 'autosave', namespace: 'persistence', projectId: nextState.activeProjectId },
+ { context: { reason: action.error }, message: 'Autosave failed', name: 'persistence.autosave-failed' }
+ );
break;
}
}