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): add a platform logging service
Josh Corbett660253e9d5fe
diff --git a/invokeai/frontend/webv2/src/platform/logging/contracts.ts b/invokeai/frontend/webv2/src/platform/logging/contracts.tsnew file mode 100644index 0000000000..a583072ae9--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/contracts.ts@@ -0,0 +1,150 @@+export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';++export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];++export const LOG_LEVEL_ORDER: Record<LogLevel, number> = {+ debug: 20,+ error: 50,+ fatal: 60,+ info: 30,+ trace: 10,+ warn: 40,+};++/** Recording namespaces users can select; `performance` timings are toggled separately. */+export const LOG_NAMESPACES = [+ 'app',+ 'canvas',+ 'canvas-workflow-integration',+ 'config',+ 'dnd',+ 'events',+ 'gallery',+ 'generation',+ 'metadata',+ 'models',+ 'persistence',+ 'queue',+ 'system',+ 'transport',+ 'workflows',+] as const;++export type LogNamespace = (typeof LOG_NAMESPACES)[number];++export const isLogLevel = (value: unknown): value is LogLevel => LOG_LEVELS.includes(value as LogLevel);++export const isLogNamespace = (value: unknown): value is LogNamespace => LOG_NAMESPACES.includes(value as LogNamespace);++export interface LogWidgetSource {+ instanceId: string;+ region: string;+ typeId: string;+}++/** Who recorded an event. Namespace and area are required; the rest attributes work to a project or operation. */+export interface LogSource {+ area: string;+ namespace: LogNamespace;+ operationId?: string;+ projectId?: string;+ widget?: LogWidgetSource;+}++export type LogContext = Record<string, unknown>;++export interface LogEventInput {+ /** Stable machine name such as `queue.submission-failed`; defaults to the source area. */+ name?: string;+ message: string;+ error?: unknown;+ /** A function defers construction until the event passes recording filters. */+ context?: LogContext | (() => LogContext);+}++export type LogInput = string | LogEventInput;++export interface Logger {+ trace(input: LogInput): void;+ debug(input: LogInput): void;+ info(input: LogInput): void;+ warn(input: LogInput): void;+ error(input: LogInput): void;+ fatal(input: LogInput): void;+ /** A logger recording under this one's source merged with `source`. */+ child(source: Partial<LogSource>): Logger;+}++export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };++export interface SerializedError {+ cause?: SerializedError | JsonValue;+ code?: string | number;+ message: string;+ name: string;+ stack?: string;+ status?: number;+}++export interface LogEntry {+ readonly context?: JsonValue;+ readonly createdAt: string;+ readonly durationMs?: number;+ readonly error?: SerializedError;+ readonly id: string;+ readonly level: LogLevel;+ readonly message: string;+ readonly name: string;+ readonly namespace: LogNamespace | 'performance';+ readonly sequence: number;+ readonly source: LogSource;+ /** Present when normalization dropped or shortened part of the payload. */+ readonly truncated?: true;+}++export interface LoggingConfig {+ consoleOutputEnabled: boolean;+ enabled: boolean;+ level: LogLevel;+ namespaces: readonly LogNamespace[];+ performanceTimingsEnabled: boolean;+}++export const DEFAULT_LOGGING_CONFIG: LoggingConfig = Object.freeze({+ consoleOutputEnabled: false,+ enabled: true,+ level: 'warn',+ namespaces: LOG_NAMESPACES,+ performanceTimingsEnabled: false,+});++export interface LogRetention {+ readonly problems: { readonly count: number; readonly evicted: number; readonly limit: number };+ readonly timings: { readonly count: number; readonly evicted: number; readonly limit: number };+ readonly verbose: { readonly count: number; readonly evicted: number; readonly limit: number };+}++export interface LogSnapshot {+ /** All retained entries, newest first. */+ readonly entries: readonly LogEntry[];+ readonly retention: LogRetention;+ /** Entries accepted since the last clear whose payload was truncated. */+ readonly truncatedCount: number;+}++/** Which entries a viewer shows or clears. Application events carry no project id. */+export type LogScope =+ | { kind: 'all' }+ | { kind: 'project'; projectId: string }+ | { kind: 'project-and-application'; projectId: string };++export const matchesLogScope = (entry: LogEntry, scope: LogScope): boolean => {+ switch (scope.kind) {+ case 'all':+ return true;+ case 'project':+ return entry.source.projectId === scope.projectId;+ case 'project-and-application':+ return entry.source.projectId === undefined || entry.source.projectId === scope.projectId;+ }+};diff --git a/invokeai/frontend/webv2/src/platform/logging/export.ts b/invokeai/frontend/webv2/src/platform/logging/export.tsnew file mode 100644index 0000000000..bcf00d81c1--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/export.ts@@ -0,0 +1,32 @@+import type { LogEntry, LoggingConfig, LogRetention, LogScope } from './contracts';++export const LOG_EXPORT_FORMAT = 'invokeai-webv2-logs';+export const LOG_EXPORT_VERSION = 1;++export interface LogExportEnvelope {+ application: { version: string };+ capture: LoggingConfig;+ entries: readonly LogEntry[];+ entryCount: number;+ exportedAt: string;+ format: typeof LOG_EXPORT_FORMAT;+ retention: LogRetention;+ scope: LogScope;+ version: typeof LOG_EXPORT_VERSION;+}++/** A versioned envelope so support tooling can tell captured settings and retention from the entries. */+export const createLogExport = (+ entries: readonly LogEntry[],+ options: { appVersion: string; capture: LoggingConfig; retention: LogRetention; scope: LogScope }+): LogExportEnvelope => ({+ application: { version: options.appVersion },+ capture: options.capture,+ entries,+ entryCount: entries.length,+ exportedAt: new Date().toISOString(),+ format: LOG_EXPORT_FORMAT,+ retention: options.retention,+ scope: options.scope,+ version: LOG_EXPORT_VERSION,+});diff --git a/invokeai/frontend/webv2/src/platform/logging/logger.test.ts b/invokeai/frontend/webv2/src/platform/logging/logger.test.tsnew file mode 100644index 0000000000..5fa90a4169--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/logger.test.ts@@ -0,0 +1,411 @@+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DEFAULT_LOGGING_CONFIG, LOG_NAMESPACES, type LoggingConfig } from './contracts';+import {+ canRecordTiming,+ clearLogs,+ configureLogging,+ createLogger,+ getLoggingConfig,+ getLogSnapshot,+ LOG_RETENTION_LIMITS,+ recordLogEvent,+ recordTiming,+ resetLogging,+ subscribeLogs,+} from './logger';++const flushMicrotasks = () =>+ new Promise<void>((resolve) => {+ queueMicrotask(resolve);+ });++const configure = (overrides: Partial<LoggingConfig> = {}): void =>+ configureLogging({ ...DEFAULT_LOGGING_CONFIG, level: 'trace', ...overrides });++beforeEach(() => {+ resetLogging();+ configure();+ vi.setSystemTime(new Date('2026-09-22T00:00:00.000Z'));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('recording filters', () => {+ it('records warn and above across every namespace by default', () => {+ resetLogging();++ expect(getLoggingConfig()).toEqual(DEFAULT_LOGGING_CONFIG);+ createLogger({ area: 'boot', namespace: 'app' }).info('quiet');+ createLogger({ area: 'boot', namespace: 'app' }).warn('loud');+ createLogger({ area: 'save', namespace: 'persistence' }).error('failed');++ expect(getLogSnapshot().entries.map((entry) => entry.message)).toEqual(['failed', 'loud']);+ expect(getLoggingConfig().namespaces).toEqual(LOG_NAMESPACES);+ });++ it('applies severity and namespace selections', () => {+ configure({ level: 'warn', namespaces: ['queue'] });++ createLogger({ area: 'runtime', namespace: 'workflows' }).error('wrong namespace');+ createLogger({ area: 'runtime', namespace: 'queue' }).debug('too quiet');+ createLogger({ area: 'runtime', namespace: 'queue' }).warn('recorded');++ expect(getLogSnapshot().entries).toMatchObject([{ level: 'warn', message: 'recorded' }]);+ });++ it('disables recording independently of timings', () => {+ configure({ enabled: false, performanceTimingsEnabled: true });+ createLogger({ area: 'runtime', namespace: 'system' }).error('skipped');+ recordTiming({ area: 'runtime', namespace: 'workflows' }, 'workflow:build', 1.25);++ expect(getLogSnapshot().entries).toMatchObject([+ { durationMs: 1.25, level: 'debug', message: 'workflow:build completed in 1.3ms', namespace: 'performance' },+ ]);++ configure({ performanceTimingsEnabled: false });+ clearLogs();+ recordTiming({ area: 'runtime', namespace: 'workflows' }, 'workflow:build', 2);++ expect(canRecordTiming()).toBe(false);+ expect(getLogSnapshot().entries).toEqual([]);+ });++ it('records events before any project exists and keeps project identity on entries', () => {+ createLogger({ area: 'boot', namespace: 'app' }).info('booted');+ createLogger({ area: 'save', namespace: 'persistence', projectId: 'project-a' }).warn('slow');++ expect(getLogSnapshot().entries).toMatchObject([+ { source: { area: 'save', namespace: 'persistence', projectId: 'project-a' } },+ { source: { area: 'boot', namespace: 'app' } },+ ]);+ expect(getLogSnapshot().entries[1]?.source).not.toHaveProperty('projectId');+ });++ it('skips lazy context construction when the event is filtered out', () => {+ configure({ level: 'warn' });+ const context = vi.fn(() => ({ heavy: true }));++ createLogger({ area: 'runtime', namespace: 'queue' }).debug({ context, message: 'filtered' });+ expect(context).not.toHaveBeenCalled();++ createLogger({ area: 'runtime', namespace: 'queue' }).warn({ context, message: 'kept' });+ expect(context).toHaveBeenCalledTimes(1);+ expect(getLogSnapshot().entries[0]?.context).toEqual({ heavy: true });+ });+});++describe('entries', () => {+ it('stores immutable normalized snapshots with error detail and source metadata', () => {+ const context = { nested: { token: 'secret', value: 1 } };+ const logger = createLogger({ area: 'compile', namespace: 'workflows', projectId: 'project-a' }).child({+ operationId: 'op-1',+ widget: { instanceId: 'workflow:center', region: 'center', typeId: 'workflow' },+ });++ logger.error({ context, error: new TypeError('bad graph'), message: 'Compile failed', name: 'workflow.compile' });+ context.nested.value = 2;++ const [entry] = getLogSnapshot().entries;++ expect(entry).toMatchObject({+ context: { nested: { token: '[redacted]', value: 1 } },+ createdAt: '2026-09-22T00:00:00.000Z',+ error: { message: 'bad graph', name: 'TypeError' },+ id: expect.stringMatching(/^log-\d+$/),+ level: 'error',+ message: 'Compile failed',+ name: 'workflow.compile',+ namespace: 'workflows',+ sequence: expect.any(Number),+ source: {+ area: 'compile',+ namespace: 'workflows',+ operationId: 'op-1',+ projectId: 'project-a',+ widget: { instanceId: 'workflow:center', region: 'center', typeId: 'workflow' },+ },+ });+ expect(Object.isFrozen(entry)).toBe(true);+ expect(Object.isFrozen(entry?.context)).toBe(true);+ expect(Object.isFrozen(entry?.source)).toBe(true);+ expect(entry?.error?.stack).toContain('TypeError');+ });++ it('defaults the event name to the source area and stringifies bare messages', () => {+ recordLogEvent('warn', { area: 'autosave', namespace: 'persistence' }, 'Save is slow');++ expect(getLogSnapshot().entries[0]).toMatchObject({ message: 'Save is slow', name: 'autosave' });+ });++ it('keeps entry ids unique across a full clear', () => {+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ logger.warn('before');+ const [before] = getLogSnapshot().entries;++ clearLogs();+ logger.warn('after');++ expect(getLogSnapshot().entries[0]?.id).not.toBe(before?.id);+ expect(getLogSnapshot().entries[0]?.sequence).toBeGreaterThan(before?.sequence ?? 0);+ });++ it('bounds messages and strips bare URL queries like any other string', () => {+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ logger.warn('https://host.example/api?token=abc');+ logger.warn(`Request failed for ${'m'.repeat(1_200)}`);++ const [long, url] = getLogSnapshot().entries;++ expect(url?.message).toBe('https://host.example/api');+ expect(long?.message.length).toBeLessThan(1_100);+ expect(long?.truncated).toBe(true);+ });++ it('caps one entry at 8 KiB and marks the truncation', () => {+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ logger.error({ context: { rows: Array.from({ length: 40 }, () => 'y'.repeat(900)) }, message: 'huge' });++ const [entry] = getLogSnapshot().entries;++ expect(entry?.truncated).toBe(true);+ expect(typeof entry?.context).toBe('string');+ expect(entry?.context).toMatch(/^\[context omitted: \d+ bytes\]$/);+ expect(JSON.stringify(entry).length).toBeLessThanOrEqual(8 * 1024);+ expect(getLogSnapshot().truncatedCount).toBe(1);+ });++ it('keeps entries under the ceiling when the stack and cause chain are the bulk', () => {+ const cause = new Error('c'.repeat(3_000));+ const error = new Error('top') as Error & { cause?: unknown };++ error.stack = 'x'.repeat(3_900);+ cause.stack = 'y'.repeat(3_900);+ error.cause = cause;+ createLogger({ area: 'runtime', namespace: 'system' }).error({ error, message: 'big' });++ const [entry] = getLogSnapshot().entries;++ expect(entry?.truncated).toBe(true);+ expect(entry?.context).toBeUndefined();+ expect(entry?.error?.stack?.endsWith('…')).toBe(true);+ expect(JSON.stringify(entry).length).toBeLessThanOrEqual(8 * 1024);+ });++ it('isolates context builder failures from the caller', () => {+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ expect(() =>+ logger.error({+ context: () => {+ throw new Error('context exploded');+ },+ message: 'still recorded',+ })+ ).not.toThrow();+ expect(getLogSnapshot().entries[0]?.context).toEqual({ '[context error]': 'context exploded' });+ });+});++describe('retention', () => {+ it('keeps problems, verbose events and timings in separate bounded buffers', () => {+ configure({ performanceTimingsEnabled: true });+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ for (let index = 0; index < LOG_RETENTION_LIMITS.verbose + 5; index += 1) {+ logger.debug(`debug ${index}`);+ }+ logger.error('problem');+ for (let index = 0; index < LOG_RETENTION_LIMITS.timings + 2; index += 1) {+ recordTiming({ area: 'runtime', namespace: 'workflows' }, `timing ${index}`, index);+ }++ const { entries, retention } = getLogSnapshot();++ expect(retention).toEqual({+ problems: { count: 1, evicted: 0, limit: LOG_RETENTION_LIMITS.problems },+ timings: { count: LOG_RETENTION_LIMITS.timings, evicted: 2, limit: LOG_RETENTION_LIMITS.timings },+ verbose: { count: LOG_RETENTION_LIMITS.verbose, evicted: 5, limit: LOG_RETENTION_LIMITS.verbose },+ });+ expect(entries.find((entry) => entry.message === 'problem')).toBeDefined();+ expect(entries.find((entry) => entry.message === 'debug 0')).toBeUndefined();+ expect(entries.find((entry) => entry.message === 'debug 5')).toBeDefined();+ });++ it('merges buffers newest first and evicts the oldest problems', () => {+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ logger.warn('first problem');+ logger.info('info between');+ logger.error('second problem');++ expect(getLogSnapshot().entries.map((entry) => entry.message)).toEqual([+ 'second problem',+ 'info between',+ 'first problem',+ ]);++ for (let index = 0; index < LOG_RETENTION_LIMITS.problems; index += 1) {+ logger.error(`late ${index}`);+ }++ expect(getLogSnapshot().entries.some((entry) => entry.message === 'first problem')).toBe(false);+ expect(getLogSnapshot().retention.problems.evicted).toBe(2);+ });+});++describe('publication', () => {+ it('returns a stable snapshot until the next change and coalesces listeners per microtask', async () => {+ const listener = vi.fn();+ const unsubscribe = subscribeLogs(listener);+ const logger = createLogger({ area: 'runtime', namespace: 'system' });+ const before = getLogSnapshot();++ logger.warn('a');+ logger.warn('b');+ logger.warn('c');++ expect(listener).not.toHaveBeenCalled();+ expect(getLogSnapshot().entries).toHaveLength(3);+ expect(getLogSnapshot()).toBe(getLogSnapshot());+ expect(getLogSnapshot()).not.toBe(before);++ await flushMicrotasks();++ expect(listener).toHaveBeenCalledTimes(1);+ unsubscribe();+ });++ it('publishes clears synchronously and cancels the pending batched publication', async () => {+ const listener = vi.fn();+ const unsubscribe = subscribeLogs(listener);++ createLogger({ area: 'runtime', namespace: 'system' }).warn('a');+ clearLogs();++ expect(listener).toHaveBeenCalledTimes(1);+ expect(getLogSnapshot().entries).toEqual([]);++ await flushMicrotasks();++ expect(listener).toHaveBeenCalledTimes(1);+ unsubscribe();+ });++ it('clears one project scope without touching other projects or application events', () => {+ createLogger({ area: 'boot', namespace: 'app' }).warn('application');+ createLogger({ area: 'save', namespace: 'persistence', projectId: 'project-a' }).warn('a');+ createLogger({ area: 'save', namespace: 'persistence', projectId: 'project-b' }).warn('b');++ clearLogs({ kind: 'project', projectId: 'project-a' });+ expect(getLogSnapshot().entries.map((entry) => entry.message)).toEqual(['b', 'application']);++ clearLogs({ kind: 'project-and-application', projectId: 'project-b' });+ expect(getLogSnapshot().entries).toEqual([]);+ });++ it('keeps recording when a subscriber throws', async () => {+ const unsubscribe = subscribeLogs(() => {+ throw new Error('listener failed');+ });+ const logger = createLogger({ area: 'runtime', namespace: 'system' });++ expect(() => logger.error('recorded')).not.toThrow();+ await flushMicrotasks();+ expect(() => clearLogs()).not.toThrow();+ logger.error('still recorded');+ expect(getLogSnapshot().entries).toHaveLength(1);+ unsubscribe();+ });+});++describe('console output', () => {+ it('writes accepted entries to the console only when enabled', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ const logger = createLogger({ area: 'runtime', namespace: 'queue', projectId: 'project-a' });++ logger.warn('silent');+ expect(warn).not.toHaveBeenCalled();++ configure({ consoleOutputEnabled: true, level: 'error' });+ logger.warn('filtered');+ logger.error({ context: { itemId: 3 }, message: 'shown' });++ expect(warn).not.toHaveBeenCalled();+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ logger.error({ context: { itemId: 3 }, message: 'shown again' });+ expect(error).toHaveBeenCalledWith('[invoke:queue/runtime] shown again', {+ context: { itemId: 3 },+ projectId: 'project-a',+ });+ });++ it('isolates console failures from the originating action', () => {+ vi.spyOn(console, 'error').mockImplementation(() => {+ throw new Error('console broken');+ });+ configure({ consoleOutputEnabled: true });++ expect(() => createLogger({ area: 'runtime', namespace: 'system' }).error('recorded')).not.toThrow();+ expect(getLogSnapshot().entries).toHaveLength(1);+ });+});++describe('account lifetimes', () => {+ it('clears history and restores defaults synchronously when the account changes', () => {+ const listener = vi.fn();+ const unsubscribe = subscribeLogs(listener);++ accountLifecycle.activate('user-a');+ configure({ level: 'trace' });+ listener.mockClear();+ createLogger({ area: 'runtime', namespace: 'system' }).debug('user a');++ accountLifecycle.invalidate();++ expect(listener).toHaveBeenCalledTimes(1);+ expect(getLogSnapshot().entries).toEqual([]);+ expect(getLoggingConfig()).toEqual(DEFAULT_LOGGING_CONFIG);+ unsubscribe();+ });++ it('separates same-user reauthentication into a fresh lifetime', () => {+ accountLifecycle.activate('user-a');+ createLogger({ area: 'runtime', namespace: 'system' }).error('first session');++ accountLifecycle.activate('user-a');++ expect(getLogSnapshot().entries).toEqual([]);+ });++ it('rejects writes from loggers whose owning lifetime expired', async () => {+ accountLifecycle.activate('user-a');+ const owner = captureAccountScope();+ const logger = createLogger({ area: 'runtime', namespace: 'queue' }, { owner });+ const listener = vi.fn();+ const unsubscribe = subscribeLogs(listener);++ logger.error('accepted');+ accountLifecycle.invalidate();+ configure();+ listener.mockClear();++ logger.error('late');+ recordTiming({ area: 'runtime', namespace: 'queue' }, 'late', 1, owner);+ await flushMicrotasks();++ expect(getLogSnapshot().entries).toEqual([]);+ expect(listener).not.toHaveBeenCalled();++ createLogger({ area: 'runtime', namespace: 'queue' }, { owner: captureAccountScope() }).error('current');+ expect(getLogSnapshot().entries).toHaveLength(1);+ unsubscribe();+ });+});diff --git a/invokeai/frontend/webv2/src/platform/logging/logger.ts b/invokeai/frontend/webv2/src/platform/logging/logger.tsnew file mode 100644index 0000000000..f058d4e8a5--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/logger.ts@@ -0,0 +1,414 @@+import {+ isAccountScopeCurrent,+ registerAccountOwnedResource,+ type AccountScope,+} from '@platform/state/accountLifecycle';+import { createListenerChannel } from '@platform/state/externalStoreCore';++import type {+ JsonValue,+ LogEntry,+ LogEventInput,+ Logger,+ LoggingConfig,+ LogInput,+ LogLevel,+ LogNamespace,+ LogRetention,+ LogScope,+ LogSnapshot,+ LogSource,+ SerializedError,+} from './contracts';++import { DEFAULT_LOGGING_CONFIG, LOG_LEVEL_ORDER, matchesLogScope } from './contracts';+import { MAX_ENTRY_BYTES, measureJsonBytes, normalizeContext, normalizeError, normalizeMessage } from './normalize';++export const LOG_RETENTION_LIMITS = Object.freeze({ problems: 500, timings: 250, verbose: 1_000 });++const PROBLEM_LEVELS: ReadonlySet<LogLevel> = new Set(['warn', 'error', 'fatal']);+const CONSOLE_METHODS: Record<LogLevel, 'debug' | 'error' | 'info' | 'warn'> = {+ debug: 'debug',+ error: 'error',+ fatal: 'error',+ info: 'info',+ trace: 'debug',+ warn: 'warn',+};++interface BoundedBuffer {+ /** Oldest first. */+ entries: LogEntry[];+ evicted: number;+ readonly limit: number;+}++const createBuffer = (limit: number): BoundedBuffer => ({ entries: [], evicted: 0, limit });++const pushBounded = (buffer: BoundedBuffer, entry: LogEntry): void => {+ buffer.entries.push(entry);++ if (buffer.entries.length > buffer.limit) {+ buffer.entries.splice(0, buffer.entries.length - buffer.limit);+ buffer.evicted += 1;+ }+};++const deepFreeze = <T>(value: T): T => {+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {+ Object.freeze(value);+ for (const child of Object.values(value as Record<string, unknown>)) {+ deepFreeze(child);+ }+ }++ return value;+};++const cloneSource = (source: LogSource): LogSource => {+ const copy: LogSource = { area: source.area, namespace: source.namespace };++ if (source.projectId !== undefined) {+ copy.projectId = source.projectId;+ }+ if (source.operationId !== undefined) {+ copy.operationId = source.operationId;+ }+ if (source.widget) {+ copy.widget = { instanceId: source.widget.instanceId, region: source.widget.region, typeId: source.widget.typeId };+ }++ return copy;+};++const channel = createListenerChannel();+let config: LoggingConfig = DEFAULT_LOGGING_CONFIG;+let problems = createBuffer(LOG_RETENTION_LIMITS.problems);+let verbose = createBuffer(LOG_RETENTION_LIMITS.verbose);+let timings = createBuffer(LOG_RETENTION_LIMITS.timings);+let truncatedCount = 0;+let nextSequence = 1;+let snapshot: LogSnapshot | null = null;+let publishEpoch = 0;+let isPublishScheduled = false;++const buildRetention = (): LogRetention => ({+ problems: { count: problems.entries.length, evicted: problems.evicted, limit: problems.limit },+ timings: { count: timings.entries.length, evicted: timings.evicted, limit: timings.limit },+ verbose: { count: verbose.entries.length, evicted: verbose.evicted, limit: verbose.limit },+});++const invalidateSnapshot = (): void => {+ snapshot = null;+};++const notifyListeners = (): void => {+ try {+ channel.notify();+ } catch {+ // A failing subscriber must not break the action that produced the event.+ }+};++/** Coalesce publication once per microtask; clears and account transitions publish synchronously instead. */+const schedulePublish = (): void => {+ if (isPublishScheduled) {+ return;+ }++ isPublishScheduled = true;+ const epoch = publishEpoch;++ queueMicrotask(() => {+ if (epoch !== publishEpoch) {+ return;+ }++ isPublishScheduled = false;+ notifyListeners();+ });+};++const publishNow = (): void => {+ publishEpoch += 1;+ isPublishScheduled = false;+ notifyListeners();+};++const shouldRecord = (level: LogLevel, namespace: LogNamespace): boolean =>+ config.enabled && LOG_LEVEL_ORDER[level] >= LOG_LEVEL_ORDER[config.level] && config.namespaces.includes(namespace);++const resolveContext = (context: LogEventInput['context']): unknown => {+ if (typeof context !== 'function') {+ return context;+ }++ try {+ return context();+ } catch (error) {+ return { '[context error]': error instanceof Error ? error.message : String(error) };+ }+};++interface MutableEntry {+ context?: JsonValue;+ createdAt: string;+ durationMs?: number;+ error?: SerializedError;+ id: string;+ level: LogLevel;+ message: string;+ name: string;+ namespace: LogNamespace | 'performance';+ sequence: number;+ source: LogSource;+ truncated?: true;+}++const enforceEntryCeiling = (entry: MutableEntry): void => {+ let bytes = measureJsonBytes(entry);++ if (bytes <= MAX_ENTRY_BYTES) {+ return;+ }++ entry.truncated = true;++ if (entry.context !== undefined) {+ entry.context = `[context omitted: ${measureJsonBytes(entry.context)} bytes]`;+ bytes = measureJsonBytes(entry);+ }++ if (bytes > MAX_ENTRY_BYTES && entry.error?.stack) {+ entry.error = { ...entry.error, stack: `${entry.error.stack.slice(0, 1_024)}…` };+ bytes = measureJsonBytes(entry);+ }++ if (bytes > MAX_ENTRY_BYTES && entry.error?.cause !== undefined) {+ entry.error = { ...entry.error, cause: '[cause omitted]' };+ bytes = measureJsonBytes(entry);+ }++ if (bytes > MAX_ENTRY_BYTES) {+ entry.message = `${entry.message.slice(0, 512)}…`;+ }+};++const createEntry = (+ level: LogLevel,+ namespace: LogNamespace | 'performance',+ source: LogSource,+ input: LogInput,+ durationMs?: number+): LogEntry => {+ const event: LogEventInput = typeof input === 'string' ? { message: input } : input;+ const sequence = nextSequence;++ nextSequence += 1;++ const message = normalizeMessage(typeof event.message === 'string' ? event.message : String(event.message));+ const entry: MutableEntry = {+ createdAt: new Date().toISOString(),+ id: `log-${sequence}`,+ level,+ message: message.value,+ name: event.name ?? source.area,+ namespace,+ sequence,+ source: cloneSource(source),+ };+ let truncated = message.truncated;++ if (durationMs !== undefined) {+ entry.durationMs = durationMs;+ }++ if (event.context !== undefined) {+ const normalized = normalizeContext(resolveContext(event.context));++ entry.context = normalized.value;+ truncated ||= normalized.truncated;+ }++ if (event.error !== undefined) {+ const normalized = normalizeError(event.error);++ entry.error = normalized.error;+ truncated ||= normalized.truncated;+ }++ if (truncated) {+ entry.truncated = true;+ }++ enforceEntryCeiling(entry);++ return deepFreeze(entry) as LogEntry;+};++const writeConsole = (entry: LogEntry): void => {+ if (!config.consoleOutputEnabled) {+ return;+ }++ try {+ const label = `[invoke:${entry.namespace}/${entry.source.area}] ${entry.message}`;+ const payload: Record<string, unknown> = {};++ if (entry.context !== undefined) {+ payload.context = entry.context;+ }+ if (entry.error) {+ payload.error = entry.error;+ }+ if (entry.source.projectId) {+ payload.projectId = entry.source.projectId;+ }+ if (entry.durationMs !== undefined) {+ payload.durationMs = entry.durationMs;+ }++ // oxlint-disable-next-line no-console -- the console sink is the opt-in output destination+ console[CONSOLE_METHODS[entry.level]](label, payload);+ } catch {+ // Console failures never affect the originating action.+ }+};++const store = (entry: LogEntry): void => {+ if (entry.namespace === 'performance') {+ pushBounded(timings, entry);+ } else if (PROBLEM_LEVELS.has(entry.level)) {+ pushBounded(problems, entry);+ } else {+ pushBounded(verbose, entry);+ }++ if (entry.truncated) {+ truncatedCount += 1;+ }++ invalidateSnapshot();+ writeConsole(entry);+ schedulePublish();+};++/** Record one event when recording filters accept it. Failures inside recording never reach the caller. */+export const recordLogEvent = (level: LogLevel, source: LogSource, input: LogInput, owner?: AccountScope): void => {+ if (owner && !isAccountScopeCurrent(owner)) {+ return;+ }++ if (!shouldRecord(level, source.namespace)) {+ return;+ }++ try {+ store(createEntry(level, source.namespace, source, input));+ } catch {+ // Normalization is defensive; a failure here must still be isolated from the caller.+ }+};++export const canRecordTiming = (): boolean => config.performanceTimingsEnabled;++export const recordTiming = (source: LogSource, name: string, durationMs: number, owner?: AccountScope): void => {+ if (!config.performanceTimingsEnabled || (owner && !isAccountScopeCurrent(owner))) {+ return;+ }++ try {+ store(+ createEntry(+ 'debug',+ 'performance',+ source,+ { message: `${name} completed in ${durationMs.toFixed(1)}ms`, name },+ durationMs+ )+ );+ } catch {+ // Timings are best-effort.+ }+};++const mergeSource = (base: LogSource, override: Partial<LogSource>): LogSource => {+ const merged: LogSource = { ...base, ...override };++ return cloneSource(merged);+};++/**+ * A logger bound to `source`. Pass `owner` from a runtime or operation start so writes after that account+ * lifetime ends are discarded; module-level loggers stay unbound.+ */+export const createLogger = (source: LogSource, options: { owner?: AccountScope } = {}): Logger => {+ const bound = cloneSource(source);+ const write = (level: LogLevel, input: LogInput): void => recordLogEvent(level, bound, input, options.owner);++ return {+ child: (override) => createLogger(mergeSource(bound, override), options),+ debug: (input) => write('debug', input),+ error: (input) => write('error', input),+ fatal: (input) => write('fatal', input),+ info: (input) => write('info', input),+ trace: (input) => write('trace', input),+ warn: (input) => write('warn', input),+ };+};++export const configureLogging = (next: LoggingConfig): void => {+ config = Object.freeze({+ consoleOutputEnabled: next.consoleOutputEnabled,+ enabled: next.enabled,+ level: next.level,+ namespaces: Object.freeze([...next.namespaces]),+ performanceTimingsEnabled: next.performanceTimingsEnabled,+ });+ publishNow();+};++export const getLoggingConfig = (): LoggingConfig => config;++export const getLogSnapshot = (): LogSnapshot => {+ if (!snapshot) {+ const entries = [...problems.entries, ...verbose.entries, ...timings.entries].sort(+ (left, right) => right.sequence - left.sequence+ );++ snapshot = Object.freeze({ entries: Object.freeze(entries), retention: buildRetention(), truncatedCount });+ }++ return snapshot;+};++export const subscribeLogs = (listener: () => void): (() => void) => channel.subscribe(listener);++const removeMatching = (buffer: BoundedBuffer, scope: LogScope): void => {+ buffer.entries = buffer.entries.filter((entry) => !matchesLogScope(entry, scope));+};++/** Remove retained entries in `scope`; clearing everything also resets eviction and truncation counters. */+export const clearLogs = (scope: LogScope = { kind: 'all' }): void => {+ if (scope.kind === 'all') {+ problems = createBuffer(LOG_RETENTION_LIMITS.problems);+ verbose = createBuffer(LOG_RETENTION_LIMITS.verbose);+ timings = createBuffer(LOG_RETENTION_LIMITS.timings);+ truncatedCount = 0;+ } else {+ removeMatching(problems, scope);+ removeMatching(verbose, scope);+ removeMatching(timings, scope);+ }++ invalidateSnapshot();+ publishNow();+};++/** Drop history and pending publications and restore default capture settings. */+export const resetLogging = (): void => {+ config = DEFAULT_LOGGING_CONFIG;+ clearLogs();+};++registerAccountOwnedResource({ clear: resetLogging, name: 'logging' });diff --git a/invokeai/frontend/webv2/src/platform/logging/normalize.test.ts b/invokeai/frontend/webv2/src/platform/logging/normalize.test.tsnew file mode 100644index 0000000000..569250d62c--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/normalize.test.ts@@ -0,0 +1,193 @@+import { ApiError } from '@platform/transport/http';+import { describe, expect, it } from 'vitest';++import { describeError, normalizeContext, normalizeError, serializeError, stripUrlSecrets } from './normalize';++describe('normalizeContext', () => {+ it('produces JSON-safe values for cycles, bigints, functions, symbols and dates', () => {+ const cyclic: Record<string, unknown> = { count: 2n, when: new Date('2026-09-22T10:00:00.000Z') };++ cyclic.self = cyclic;+ cyclic.run = function run() {+ return undefined;+ };+ cyclic.tag = Symbol('tag');+ cyclic.nan = Number.NaN;++ expect(normalizeContext(cyclic)).toEqual({+ truncated: false,+ value: {+ count: '2n',+ nan: 'NaN',+ run: '[function run]',+ self: '[circular]',+ tag: 'Symbol(tag)',+ when: '2026-09-22T10:00:00.000Z',+ },+ });+ });++ it('does not execute getters or toJSON and survives throwing accessors', () => {+ let getterCalls = 0;+ const value = {+ get computedGetter() {+ getterCalls += 1;++ return 'computed';+ },+ plain: 'kept',+ toJSON: () => {+ throw new Error('toJSON must not run');+ },+ };++ Object.defineProperty(value, 'explosive', {+ enumerable: true,+ get() {+ throw new Error('boom');+ },+ });++ expect(normalizeContext(value).value).toEqual({+ computedGetter: '[accessor]',+ explosive: '[accessor]',+ plain: 'kept',+ toJSON: '[function toJSON]',+ });+ expect(getterCalls).toBe(0);+ });++ it('redacts credential-like keys and strips URL queries and fragments', () => {+ expect(+ normalizeContext({+ Authorization: 'Bearer abc',+ apiKey: 'k',+ nested: { password: 'p', refreshToken: 't', sessionCookie: 'c' },+ path: '/api/v1/images?token=abc#frag',+ url: 'https://host.example/api/v1/x?access_token=abc#x',+ username: 'visible',+ }).value+ ).toEqual({+ Authorization: '[redacted]',+ apiKey: '[redacted]',+ nested: { password: '[redacted]', refreshToken: '[redacted]', sessionCookie: '[redacted]' },+ path: '/api/v1/images',+ url: 'https://host.example/api/v1/x',+ username: 'visible',+ });+ expect(stripUrlSecrets('plain text with ? mark')).toBe('plain text with ? mark');+ });++ it('bounds depth, collection sizes and string lengths with explicit markers', () => {+ const deep = { l1: { l2: { l3: { l4: { l5: { l6: { l7: 'too deep' } } } } } } };+ const wide = Array.from({ length: 60 }, (_, index) => index);+ const long = 'x'.repeat(1_200);+ const result = normalizeContext({ deep, long, wide });++ expect(result.truncated).toBe(true);+ expect(result.value).toMatchObject({+ deep: { l1: { l2: { l3: { l4: { l5: '[depth limit]' } } } } },+ long: `${'x'.repeat(1_000)}…[+200 chars]`,+ });+ expect((result.value as { wide: unknown[] }).wide).toHaveLength(51);+ expect((result.value as { wide: unknown[] }).wide[50]).toBe('[+10 more]');+ });++ it('detects cycles that pass through an error and keeps status reads to own properties', () => {+ const error = new Error('root') as Error & { cause?: unknown };+ let getterCalls = 0;++ class StatusError extends Error {+ get status(): number {+ getterCalls += 1;++ return 500;+ }+ }++ error.cause = { via: error };++ const result = normalizeContext({ error });++ expect(result.value).toEqual({+ error: { cause: { via: '[circular]' }, message: 'root', name: 'Error', stack: expect.any(String) },+ });+ expect(normalizeError(new StatusError('boom')).error).not.toHaveProperty('status');+ expect(getterCalls).toBe(0);+ });++ it('redacts credential-like map keys', () => {+ expect(+ normalizeContext(+ new Map([+ ['authorization', 'Bearer x'],+ ['plain', 'kept'],+ ])+ ).value+ ).toEqual([+ ['authorization', '[redacted]'],+ ['plain', 'kept'],+ ]);+ });++ it('describes binary payloads and maps instead of copying them', () => {+ const result = normalizeContext({+ buffer: new Uint8Array(16),+ map: new Map([['a', 1]]),+ set: new Set(['b']),+ });++ expect(result.value).toEqual({ buffer: '[binary 16 bytes]', map: [['a', 1]], set: ['b'] });+ });+});++describe('normalizeError', () => {+ it('captures name, message, stack, cause chain and API status without retaining the instance', () => {+ const cause = new Error('root cause');+ const error = new ApiError('{"detail":"bad"}', 502, undefined);++ (error as Error & { cause?: unknown }).cause = cause;++ const { error: serialized, truncated } = normalizeError(error);++ expect(truncated).toBe(false);+ expect(serialized).toMatchObject({ message: '{"detail":"bad"}', name: 'ApiError', status: 502 });+ expect(serialized.stack).toContain('ApiError');+ expect(serialized.cause).toMatchObject({ message: 'root cause', name: 'Error' });+ expect(serialized).not.toHaveProperty('headers');+ });++ it('truncates very long stacks and cuts cause chains after three levels', () => {+ const error = new Error('top');+ let current: Error & { cause?: unknown } = error;++ for (let depth = 0; depth < 5; depth += 1) {+ const next = new Error(`cause ${depth}`);++ current.cause = next;+ current = next;+ }+ error.stack = 'x'.repeat(5_000);++ const { error: serialized, truncated } = normalizeError(error);++ expect(truncated).toBe(true);+ expect(serialized.stack).toHaveLength(4_001);+ expect(JSON.stringify(serialized)).toContain('[cause depth limit]');+ });++ it('serializes non-error throwables', () => {+ expect(serializeError('plain string')).toEqual({ message: 'plain string', name: 'NonError' });+ expect(serializeError({ code: 'E1' })).toEqual({ message: '{"code":"E1"}', name: 'NonError' });+ });+});++describe('describeError', () => {+ it('never renders [object Object]', () => {+ expect(describeError(new Error('boom'))).toBe('boom');+ expect(describeError({ message: 'from object' })).toBe('from object');+ expect(describeError({ status: 500 })).toBe('{"status":500}');+ expect(describeError(undefined)).toBe('');+ expect(describeError(42)).toBe('42');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/logging/normalize.ts b/invokeai/frontend/webv2/src/platform/logging/normalize.tsnew file mode 100644index 0000000000..c99ee0892e--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/normalize.ts@@ -0,0 +1,437 @@+import type { JsonValue, SerializedError } from './contracts';++/** Bounds keep one entry small enough that a burst cannot retain unbounded memory or block the caller. */+export const MAX_DEPTH = 6;+export const MAX_COLLECTION_ITEMS = 50;+export const MAX_STRING_LENGTH = 1_000;+export const MAX_STACK_LENGTH = 4_000;+export const MAX_ERROR_CAUSE_DEPTH = 3;+export const MAX_ENTRY_BYTES = 8 * 1024;++const SENSITIVE_KEY_PATTERN =+ /(?:^|-)(?:token|secret|password|passwd|authorization|cookie|credential|api-?key|bearer)s?(?:$|-)/;+const ABSOLUTE_URL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;++export interface NormalizedValue {+ truncated: boolean;+ value: JsonValue;+}++interface Walk {+ seen: WeakSet<object>;+ truncated: boolean;+}++/** Match whole words in camelCase, snake_case and kebab-case keys such as `refreshToken` or `api_key`. */+const isSensitiveKey = (key: string): boolean =>+ SENSITIVE_KEY_PATTERN.test(+ key+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')+ .replace(/[_.\s]+/g, '-')+ .toLowerCase()+ );++/** Keep an origin and path of a bare URL; drop query strings and fragments, which carry tokens and user input. */+export const stripUrlSecrets = (value: string): string => {+ if (/\s/.test(value)) {+ return value;+ }++ if (ABSOLUTE_URL_PATTERN.test(value)) {+ try {+ const url = new URL(value);++ return `${url.origin}${url.pathname}`;+ } catch {+ return value;+ }+ }++ if (value.startsWith('/')) {+ const cut = value.search(/[?#]/);++ return cut === -1 ? value : value.slice(0, cut);+ }++ return value;+};++const normalizeString = (value: string, walk: Walk): string => {+ const stripped = stripUrlSecrets(value);++ if (stripped.length > MAX_STRING_LENGTH) {+ walk.truncated = true;++ return `${stripped.slice(0, MAX_STRING_LENGTH)}…[+${stripped.length - MAX_STRING_LENGTH} chars]`;+ }++ return stripped;+};++const describeBinary = (value: object): string | null => {+ if (typeof ArrayBuffer !== 'undefined' && (value instanceof ArrayBuffer || ArrayBuffer.isView(value))) {+ return `[binary ${value.byteLength} bytes]`;+ }++ if (typeof Blob !== 'undefined' && value instanceof Blob) {+ return `[blob ${value.size} bytes${value.type ? ` ${value.type}` : ''}]`;+ }++ if (typeof ImageData !== 'undefined' && value instanceof ImageData) {+ return `[image-data ${value.width}x${value.height}]`;+ }++ return null;+};++const describeDom = (value: object): string | null => {+ if (typeof Node !== 'undefined' && value instanceof Node) {+ return `[dom ${value.nodeName.toLowerCase()}]`;+ }++ if (typeof Window !== 'undefined' && value instanceof Window) {+ return '[window]';+ }++ if (typeof Event !== 'undefined' && value instanceof Event) {+ return `[event ${value.type}]`;+ }++ return null;+};++const getPrototypeName = (value: object): string => {+ const prototype = Object.getPrototypeOf(value) as { constructor?: { name?: string } } | null;++ return prototype?.constructor?.name ?? 'Object';+};++const readOwnDataProperty = (value: object, key: string): { ok: true; value: unknown } | { ok: false } => {+ try {+ const descriptor = Object.getOwnPropertyDescriptor(value, key);++ if (!descriptor || !('value' in descriptor)) {+ return { ok: false };+ }++ return { ok: true, value: descriptor.value };+ } catch {+ return { ok: false };+ }+};++const normalizeValue = (value: unknown, depth: number, walk: Walk): JsonValue => {+ switch (typeof value) {+ case 'string':+ return normalizeString(value, walk);+ case 'number':+ return Number.isFinite(value) ? value : String(value);+ case 'boolean':+ return value;+ case 'bigint':+ return `${value}n`;+ case 'undefined':+ return null;+ case 'symbol':+ return value.toString();+ case 'function':+ return `[function ${value.name || 'anonymous'}]`;+ case 'object':+ break;+ }++ if (value === null) {+ return null;+ }++ const object = value as object;++ if (object instanceof Error) {+ if (walk.seen.has(object)) {+ return '[circular]';+ }++ walk.seen.add(object);+ try {+ return serializeErrorAtDepth(object, depth, walk) as unknown as JsonValue;+ } finally {+ walk.seen.delete(object);+ }+ }++ if (object instanceof Date) {+ return Number.isNaN(object.getTime()) ? '[invalid date]' : object.toISOString();+ }++ if (object instanceof RegExp) {+ return object.toString();+ }++ const binary = describeBinary(object) ?? describeDom(object);++ if (binary) {+ return binary;+ }++ if (walk.seen.has(object)) {+ return '[circular]';+ }++ if (depth >= MAX_DEPTH) {+ walk.truncated = true;++ return '[depth limit]';+ }++ walk.seen.add(object);++ try {+ if (Array.isArray(object)) {+ return normalizeArray(object, depth, walk);+ }++ if (object instanceof Map) {+ return normalizeArray(+ [...object.entries()].map(([key, entry]) => [+ key,+ typeof key === 'string' && isSensitiveKey(key) ? '[redacted]' : entry,+ ]),+ depth,+ walk+ );+ }++ if (object instanceof Set) {+ return normalizeArray([...object.values()], depth, walk);+ }++ return normalizeRecord(object, depth, walk);+ } finally {+ walk.seen.delete(object);+ }+};++const normalizeArray = (items: unknown[], depth: number, walk: Walk): JsonValue => {+ const output: JsonValue[] = [];++ for (const item of items.slice(0, MAX_COLLECTION_ITEMS)) {+ output.push(normalizeValue(item, depth + 1, walk));+ }++ if (items.length > MAX_COLLECTION_ITEMS) {+ walk.truncated = true;+ output.push(`[+${items.length - MAX_COLLECTION_ITEMS} more]`);+ }++ return output;+};++const normalizeRecord = (object: object, depth: number, walk: Walk): JsonValue => {+ const output: { [key: string]: JsonValue } = {};+ let keys: string[];++ try {+ keys = Object.keys(object);+ } catch {+ return `[unreadable ${getPrototypeName(object)}]`;+ }++ for (const key of keys.slice(0, MAX_COLLECTION_ITEMS)) {+ if (isSensitiveKey(key)) {+ output[key] = '[redacted]';+ continue;+ }++ const read = readOwnDataProperty(object, key);++ if (!read.ok) {+ output[key] = '[accessor]';+ continue;+ }++ if (read.value === undefined) {+ continue;+ }++ output[key] = normalizeValue(read.value, depth + 1, walk);+ }++ if (keys.length > MAX_COLLECTION_ITEMS) {+ walk.truncated = true;+ output['[truncated]'] = `+${keys.length - MAX_COLLECTION_ITEMS} keys`;+ }++ return output;+};++/** Convert any value into an immutable JSON-safe snapshot. Never throws. */+export const normalizeContext = (value: unknown): NormalizedValue => {+ const walk: Walk = { seen: new WeakSet(), truncated: false };++ try {+ const normalized = normalizeValue(value, 0, walk);++ return { truncated: walk.truncated, value: normalized };+ } catch (error) {+ return { truncated: true, value: `[unserializable: ${describeError(error)}]` };+ }+};++const readErrorField = (error: object, key: string): unknown => {+ const own = readOwnDataProperty(error, key);++ if (own.ok) {+ return own.value;+ }++ // Standard fields (`name`, `message`, `stack`) are inherited data properties or engine-installed accessors+ // on Error instances; reading them is safe.+ try {+ return (error as Record<string, unknown>)[key];+ } catch {+ return undefined;+ }+};++const serializeErrorAtDepth = (error: unknown, depth: number, walk: Walk): SerializedError | JsonValue => {+ if (!(error instanceof Error)) {+ return normalizeValue(error, depth, walk);+ }++ if (depth >= MAX_DEPTH) {+ walk.truncated = true;++ return '[depth limit]';+ }++ const name = readErrorField(error, 'name');+ const message = readErrorField(error, 'message');+ const stack = readErrorField(error, 'stack');+ // Domain fields are read as own data properties only, so subclass accessors never run.+ const statusRead = readOwnDataProperty(error, 'status');+ const codeRead = readOwnDataProperty(error, 'code');+ const status = statusRead.ok ? statusRead.value : undefined;+ const code = codeRead.ok ? codeRead.value : undefined;+ const serialized: SerializedError = {+ message: typeof message === 'string' ? normalizeString(message, walk) : '',+ name: typeof name === 'string' && name ? name : 'Error',+ };++ if (typeof stack === 'string' && stack) {+ if (stack.length > MAX_STACK_LENGTH) {+ walk.truncated = true;+ serialized.stack = `${stack.slice(0, MAX_STACK_LENGTH)}…`;+ } else {+ serialized.stack = stack;+ }+ }++ if (typeof status === 'number') {+ serialized.status = status;+ }++ if (typeof code === 'string' || typeof code === 'number') {+ serialized.code = code;+ }++ const causeRead = readOwnDataProperty(error, 'cause');++ if (causeRead.ok && causeRead.value !== undefined) {+ const cause = causeRead.value;++ if (depth >= MAX_ERROR_CAUSE_DEPTH) {+ walk.truncated = true;+ serialized.cause = '[cause depth limit]';+ } else if (typeof cause === 'object' && cause !== null && walk.seen.has(cause)) {+ serialized.cause = '[circular]';+ } else {+ walk.seen.add(error);+ try {+ serialized.cause = serializeErrorAtDepth(cause, depth + 1, walk);+ } finally {+ walk.seen.delete(error);+ }+ }+ }++ return serialized;+};++export interface NormalizedError {+ error: SerializedError;+ truncated: boolean;+}++/** Snapshot an error's name, message, stack, cause and status/code without retaining the instance. */+export const normalizeError = (error: unknown): NormalizedError => {+ const walk: Walk = { seen: new WeakSet(), truncated: false };++ try {+ const serialized = serializeErrorAtDepth(error, 0, walk);++ if (serialized && typeof serialized === 'object' && !Array.isArray(serialized) && 'message' in serialized) {+ return { error: serialized as SerializedError, truncated: walk.truncated };+ }++ return {+ error: { message: typeof serialized === 'string' ? serialized : JSON.stringify(serialized), name: 'NonError' },+ truncated: walk.truncated,+ };+ } catch {+ return { error: { message: '[unserializable error]', name: 'Error' }, truncated: true };+ }+};++export const serializeError = (error: unknown): SerializedError => normalizeError(error).error;++/** A readable one-line message for notifications; never `[object Object]`. */+export const describeError = (error: unknown): string => {+ if (error instanceof Error) {+ return error.message || error.name;+ }++ if (typeof error === 'string') {+ return error;+ }++ if (error === undefined || error === null) {+ return '';+ }++ if (typeof error === 'object') {+ const message = readOwnDataProperty(error, 'message');++ if (message.ok && typeof message.value === 'string') {+ return message.value;+ }++ try {+ return JSON.stringify(normalizeContext(error).value);+ } catch {+ return '[unserializable error]';+ }+ }++ return String(error);+};++const utf8 = typeof TextEncoder === 'undefined' ? null : new TextEncoder();++/** UTF-8 size of the serialized value, so the ceiling holds for non-ASCII text. */+export const measureJsonBytes = (value: unknown): number => {+ try {+ const json = JSON.stringify(value) ?? '';++ return utf8 ? utf8.encode(json).length : json.length;+ } catch {+ return Number.POSITIVE_INFINITY;+ }+};++/** Bound a message like any other string: length cap and URL secret stripping. */+export const normalizeMessage = (message: string): { truncated: boolean; value: string } => {+ const walk: Walk = { seen: new WeakSet(), truncated: false };+ const value = normalizeString(message, walk);++ return { truncated: walk.truncated, value };+};diff --git a/invokeai/frontend/webv2/src/platform/logging/react.ts b/invokeai/frontend/webv2/src/platform/logging/react.tsnew file mode 100644index 0000000000..4e09b13e01--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/logging/react.ts@@ -0,0 +1,10 @@+import { useSyncExternalStore } from 'react';++import type { LoggingConfig, LogSnapshot } from './contracts';++import { getLoggingConfig, getLogSnapshot, subscribeLogs } from './logger';++export const useLogSnapshot = (): LogSnapshot => useSyncExternalStore(subscribeLogs, getLogSnapshot, getLogSnapshot);++export const useLoggingConfig = (): LoggingConfig =>+ useSyncExternalStore(subscribeLogs, getLoggingConfig, getLoggingConfig);