Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): tailor canvas-protection workarounds to the detected browser
Josh Corbett2a4ba1095728
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex fe19f18336..4776d84857 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1485,9 +1485,11 @@"launchpad": {"browserIssues": {"canvasReadbackIntegrity": {+ "braveWorkaround": "Click the Brave Shields icon in the address bar and turn Shields off for this site, then reload Invoke.","description": "Your browser is modifying or blocking canvas pixel data. This can make later strokes noisy or pixelated.",+ "firefoxWorkaround": "Click the canvas permission icon in the address bar and allow this site to read canvas data. If no icon appears, click the shield icon and turn off Enhanced Tracking Protection for this site. Then reload Invoke.","genericWorkaround": "If you use another privacy browser or canvas-protection extension, allow unmodified canvas access for this site, then reload Invoke.",- "heliumWorkaround": "Open the setting below, disable “[Helium Noise] Canvas pixel noising”, then relaunch Helium.",+ "heliumWorkaround": "In Helium, open the address below, disable “[Helium Noise] Canvas pixel noising”, then relaunch Helium.","title": "Canvas protection may corrupt painted strokes"},"copyFailed": "Could not copy browser setting",diff --git a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.browser.test.tsnew file mode 100644index 0000000000..3f1f444398--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.browser.test.ts@@ -0,0 +1,30 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { detectKnownBrowserIssues } from './knownBrowserIssues';++const getWorkaroundIds = (): readonly (readonly string[])[] =>+ detectKnownBrowserIssues().map((issue) => issue.workarounds.map((workaround) => workaround.id));++afterEach(() => {+ vi.restoreAllMocks();+});++describe('known browser issues in Chromium', () => {+ it('detects nothing when the real canvas returns exact pixels', () => {+ expect(getWorkaroundIds()).toEqual([]);+ });++ it('resolves Chromium workarounds from the real navigator when readback is noised', () => {+ const readPixels = CanvasRenderingContext2D.prototype.getImageData;+ vi.spyOn(CanvasRenderingContext2D.prototype, 'getImageData').mockImplementation(function (+ this: CanvasRenderingContext2D,+ ...args: Parameters<CanvasRenderingContext2D['getImageData']>+ ) {+ const imageData = readPixels.apply(this, args);+ imageData.data[0] ^= 1;+ return imageData;+ });++ expect(getWorkaroundIds()).toEqual([['helium', 'other-browser']]);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.tsindex 413e814cf3..c69a40fc4a 100644--- a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts@@ -1,18 +1,22 @@-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import {+ type BrowserFamily,+ type BrowserIssueDetectionEnvironment,detectKnownBrowserIssues,+ identifyBrowserFamily,KNOWN_BROWSER_ISSUES,- type BrowserIssueDetectionEnvironment,} from './knownBrowserIssues';interface TestEnvironmentOptions {+ browserFamily?: BrowserFamily;isContextAvailable?: boolean;mutateReadback?: (pixels: Uint8ClampedArray) => void;readbackError?: Error;}const createTestEnvironment = ({+ browserFamily = 'chromium',isContextAvailable = true,mutateReadback,readbackError,@@ -40,65 +44,114 @@ const createTestEnvironment = ({},} as unknown as CanvasRenderingContext2D;const canvas = {- getContext: vi.fn(() => (isContextAvailable ? context : null)),+ getContext: () => (isContextAvailable ? context : null),height: 0,width: 0,} as unknown as HTMLCanvasElement;return {- createCanvas: vi.fn(() => canvas),+ browserFamily,+ createCanvas: () => canvas,};};-const getDetectedIssueIds = async (environment: BrowserIssueDetectionEnvironment): Promise<readonly string[]> =>- (await detectKnownBrowserIssues(environment)).map((issue) => issue.id);+const noisyReadback = (pixels: Uint8ClampedArray): void => {+ pixels[0] = pixels[0] === 255 ? 254 : pixels[0] + 1;+};++const getDetectedIssueIds = (environment: BrowserIssueDetectionEnvironment): readonly string[] =>+ detectKnownBrowserIssues(environment).map((issue) => issue.id);++const getWorkaroundIds = (browserFamily: BrowserFamily): readonly string[] =>+ detectKnownBrowserIssues(createTestEnvironment({ browserFamily, mutateReadback: noisyReadback })).flatMap((issue) =>+ issue.workarounds.map((workaround) => workaround.id)+ );++const CHROME_USER_AGENT =+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';+const FIREFOX_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0';+const SAFARI_USER_AGENT =+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15';describe('known browser issues', () => {- it('accepts an exact canvas pixel readback', async () => {- expect(await getDetectedIssueIds(createTestEnvironment())).toEqual([]);+ it('accepts an exact canvas pixel readback', () => {+ expect(getDetectedIssueIds(createTestEnvironment())).toEqual([]);});- it('detects a modified RGB byte', async () => {- const environment = createTestEnvironment({- mutateReadback: (pixels) => {- pixels[0] = pixels[0] === 255 ? 254 : pixels[0] + 1;- },- });-- expect(await getDetectedIssueIds(environment)).toEqual(['canvas-readback-integrity']);+ it('detects a modified RGB byte', () => {+ expect(getDetectedIssueIds(createTestEnvironment({ mutateReadback: noisyReadback }))).toEqual([+ 'canvas-readback-integrity',+ ]);});- it('detects a modified alpha byte', async () => {+ it('detects a modified alpha byte', () => {const environment = createTestEnvironment({mutateReadback: (pixels) => {pixels[3] = 254;},});- expect(await getDetectedIssueIds(environment)).toEqual(['canvas-readback-integrity']);+ expect(getDetectedIssueIds(environment)).toEqual(['canvas-readback-integrity']);});- it('detects an unavailable 2D context', async () => {- expect(await getDetectedIssueIds(createTestEnvironment({ isContextAvailable: false }))).toEqual([+ it('detects an unavailable 2D context', () => {+ expect(getDetectedIssueIds(createTestEnvironment({ isContextAvailable: false }))).toEqual(['canvas-readback-integrity',]);});- it('detects a blocked canvas readback', async () => {+ it('detects a blocked canvas readback', () => {+ expect(getDetectedIssueIds(createTestEnvironment({ readbackError: new Error('Canvas readback blocked') }))).toEqual(+ ['canvas-readback-integrity']+ );+ });++ it('returns registry metadata without the detector', () => {+ const [detectedIssue] = detectKnownBrowserIssues(createTestEnvironment({ mutateReadback: noisyReadback }));+ const { detect: _detect, ...registryIssue } = KNOWN_BROWSER_ISSUES[0];++ expect(detectedIssue).not.toHaveProperty('detect');+ expect(detectedIssue).toEqual({+ ...registryIssue,+ workarounds: registryIssue.workarounds.filter(+ (workaround) => workaround.id !== 'brave' && workaround.id !== 'firefox'+ ),+ });+ });++ it('shows Brave users only the Shields instruction plus the generic fallback', () => {+ expect(getWorkaroundIds('brave')).toEqual(['brave', 'other-browser']);+ });++ it('shows Firefox users the canvas permission instruction instead of the Helium flag', () => {+ expect(getWorkaroundIds('firefox')).toEqual(['firefox', 'other-browser']);+ });++ it('keeps the Helium flag for Chromium builds that cannot be told apart from Helium', () => {+ expect(getWorkaroundIds('chromium')).toEqual(['helium', 'other-browser']);+ });++ it('shows only the generic instruction elsewhere', () => {+ expect(getWorkaroundIds('other')).toEqual(['other-browser']);+ });+});++describe('identifyBrowserFamily', () => {+ it('recognizes Brave by its navigator API ahead of its Chrome user agent', () => {expect(- await getDetectedIssueIds(createTestEnvironment({ readbackError: new Error('Canvas readback blocked') }))- ).toEqual(['canvas-readback-integrity']);+ identifyBrowserFamily({ brave: { isBrave: () => Promise.resolve(true) }, userAgent: CHROME_USER_AGENT })+ ).toBe('brave');});- it('returns only registry entries whose detectors match', async () => {- const detectedIssues = await detectKnownBrowserIssues(- createTestEnvironment({- mutateReadback: (pixels) => {- pixels[4] += 1;- },- })- );+ it('does not treat a non-callable brave property as Brave', () => {+ expect(identifyBrowserFamily({ brave: {}, userAgent: CHROME_USER_AGENT })).toBe('chromium');+ });++ it('recognizes Firefox-based browsers', () => {+ expect(identifyBrowserFamily({ userAgent: FIREFOX_USER_AGENT })).toBe('firefox');+ });- expect(detectedIssues).toEqual([KNOWN_BROWSER_ISSUES[0]]);+ it('falls back to other for WebKit browsers', () => {+ expect(identifyBrowserFamily({ userAgent: SAFARI_USER_AGENT })).toBe('other');});});diff --git a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.tsindex 9de8c4064e..5daa53011f 100644--- a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts+++ b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts@@ -2,37 +2,61 @@ export type KnownBrowserIssueId = 'canvas-readback-integrity';export type KnownBrowserIssueSeverity = 'warning' | 'error';+export type BrowserFamily = 'brave' | 'chromium' | 'firefox' | 'other';+export interface KnownBrowserIssueWorkaround {id: string;instructionKey: string;copyableValue?: string;+ /** Families this instruction applies to; omitted means every browser. */+ browsers?: readonly BrowserFamily[];}export interface BrowserIssueDetectionEnvironment {- createCanvas: () => HTMLCanvasElement | null;+ browserFamily: BrowserFamily;+ createCanvas: () => HTMLCanvasElement;}-export interface KnownBrowserIssue {+export interface DetectedBrowserIssue {id: KnownBrowserIssueId;severity: KnownBrowserIssueSeverity;titleKey: string;descriptionKey: string;workarounds: readonly KnownBrowserIssueWorkaround[];- detect: (environment: BrowserIssueDetectionEnvironment) => boolean | Promise<boolean>;}-const CANVAS_PROBE_SIZE = 32;+export interface KnownBrowserIssue extends DetectedBrowserIssue {+ detect: (environment: BrowserIssueDetectionEnvironment) => boolean;+}-const DEFAULT_DETECTION_ENVIRONMENT: BrowserIssueDetectionEnvironment = {- createCanvas: () => {- if (typeof document === 'undefined') {- return null;- }+interface BrowserIdentity {+ brave?: { isBrave?: unknown };+ userAgent: string;+}- return document.createElement('canvas');- },+export const identifyBrowserFamily = ({ brave, userAgent }: BrowserIdentity): BrowserFamily => {+ if (typeof brave?.isBrave === 'function') {+ return 'brave';+ }++ if (userAgent.includes('Firefox/')) {+ return 'firefox';+ }++ if (userAgent.includes('Chrome/')) {+ return 'chromium';+ }++ return 'other';};+const CANVAS_PROBE_SIZE = 32;++const createDefaultDetectionEnvironment = (): BrowserIssueDetectionEnvironment => ({+ browserFamily: identifyBrowserFamily(navigator as Navigator & BrowserIdentity),+ createCanvas: () => document.createElement('canvas'),+});+const createExpectedCanvasPixels = (): Uint8ClampedArray => {const pixels = new Uint8ClampedArray(CANVAS_PROBE_SIZE * CANVAS_PROBE_SIZE * 4);@@ -51,11 +75,6 @@ const createExpectedCanvasPixels = (): Uint8ClampedArray => {const hasUnsafeCanvasReadback = (environment: BrowserIssueDetectionEnvironment): boolean => {try {const canvas = environment.createCanvas();-- if (!canvas) {- return true;- }-canvas.width = CANVAS_PROBE_SIZE;canvas.height = CANVAS_PROBE_SIZE;@@ -91,6 +110,17 @@ export const KNOWN_BROWSER_ISSUES = [titleKey: 'launchpad.browserIssues.canvasReadbackIntegrity.title',workarounds: [{+ browsers: ['brave'],+ id: 'brave',+ instructionKey: 'launchpad.browserIssues.canvasReadbackIntegrity.braveWorkaround',+ },+ {+ browsers: ['firefox'],+ id: 'firefox',+ instructionKey: 'launchpad.browserIssues.canvasReadbackIntegrity.firefoxWorkaround',+ },+ {+ browsers: ['chromium'],copyableValue: 'helium://flags/#helium-noise-canvas',id: 'helium',instructionKey: 'launchpad.browserIssues.canvasReadbackIntegrity.heliumWorkaround',@@ -103,14 +133,20 @@ export const KNOWN_BROWSER_ISSUES = [},] as const satisfies readonly KnownBrowserIssue[];-export const detectKnownBrowserIssues = async (- environment: BrowserIssueDetectionEnvironment = DEFAULT_DETECTION_ENVIRONMENT-): Promise<readonly KnownBrowserIssue[]> => {- const results: (KnownBrowserIssue | null)[] = await Promise.all(- KNOWN_BROWSER_ISSUES.map(async (issue): Promise<KnownBrowserIssue | null> =>- (await issue.detect(environment)) ? issue : null- )+const REGISTERED_ISSUES: readonly KnownBrowserIssue[] = KNOWN_BROWSER_ISSUES;++export const detectKnownBrowserIssues = (+ environment: BrowserIssueDetectionEnvironment = createDefaultDetectionEnvironment()+): readonly DetectedBrowserIssue[] =>+ REGISTERED_ISSUES.flatMap(({ detect, ...issue }): DetectedBrowserIssue[] =>+ detect(environment)+ ? [+ {+ ...issue,+ workarounds: issue.workarounds.filter(+ (workaround) => !workaround.browsers || workaround.browsers.includes(environment.browserFamily)+ ),+ },+ ]+ : []);-- return results.filter((issue): issue is KnownBrowserIssue => issue !== null);-};diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsxindex 151d99c0b2..57f6f7abc4 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx@@ -1,7 +1,7 @@import type * as knownBrowserIssuesModule from '@platform/browser/knownBrowserIssues';import { ChakraProvider } from '@chakra-ui/react';-import { KNOWN_BROWSER_ISSUES } from '@platform/browser/knownBrowserIssues';+import { type DetectedBrowserIssue, KNOWN_BROWSER_ISSUES } from '@platform/browser/knownBrowserIssues';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -16,12 +16,14 @@ vi.mock('@platform/browser/knownBrowserIssues', async (importOriginal) => ({}));const translations: Record<string, string> = {+ 'launchpad.browserIssues.canvasReadbackIntegrity.braveWorkaround':+ 'Click the Brave Shields icon in the address bar and turn Shields off for this site, then reload Invoke.','launchpad.browserIssues.canvasReadbackIntegrity.description':'Your browser is modifying or blocking canvas pixel data. This can make later strokes noisy or pixelated.','launchpad.browserIssues.canvasReadbackIntegrity.genericWorkaround':'If you use another privacy browser or canvas-protection extension, allow unmodified canvas access for this site, then reload Invoke.','launchpad.browserIssues.canvasReadbackIntegrity.heliumWorkaround':- 'Open the setting below, disable “[Helium Noise] Canvas pixel noising”, then relaunch Helium.',+ 'In Helium, open the address below, disable “[Helium Noise] Canvas pixel noising”, then relaunch Helium.','launchpad.browserIssues.canvasReadbackIntegrity.title': 'Canvas protection may corrupt painted strokes','launchpad.browserIssues.copyFailed': 'Could not copy browser setting','launchpad.browserIssues.copySetting': 'Copy browser setting',@@ -36,27 +38,35 @@ vi.mock('react-i18next', () => ({import { KnownBrowserIssuesAlert } from './KnownBrowserIssuesAlert';+const [CANVAS_ISSUE] = KNOWN_BROWSER_ISSUES;++const createDetectedIssue = (...workaroundIds: readonly string[]): DetectedBrowserIssue => {+ const { detect: _detect, ...issue } = CANVAS_ISSUE;++ return {+ ...issue,+ workarounds: issue.workarounds.filter((workaround) => workaroundIds.includes(workaround.id)),+ };+};+let host: HTMLDivElement | null = null;let root: Root | null = null;let originalClipboardDescriptor: PropertyDescriptor | undefined;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const renderAlert = async (): Promise<void> => {- await act(async () => {+ await act(() => {root?.render(<ChakraProvider value={system}><KnownBrowserIssuesAlert /></ChakraProvider>);- await new Promise<void>((resolve) => {- globalThis.setTimeout(resolve, 0);- });});};beforeEach(() => {detectKnownBrowserIssuesMock.mockReset();- detectKnownBrowserIssuesMock.mockResolvedValue([]);+ detectKnownBrowserIssuesMock.mockReturnValue([]);originalClipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');host = document.createElement('div');document.body.append(host);@@ -83,17 +93,16 @@ describe('known browser issues alert', () => {const bodyChildCount = document.body.childElementCount;await renderAlert();- await vi.waitFor(() => expect(detectKnownBrowserIssuesMock).toHaveBeenCalledOnce());+ expect(detectKnownBrowserIssuesMock).toHaveBeenCalledOnce();expect(host?.querySelector('[role="alert"]')).toBeNull();expect(document.body.childElementCount).toBe(bodyChildCount);});- it('renders the detected issue with accessible semantics and both workaround paths', async () => {- detectKnownBrowserIssuesMock.mockResolvedValue([KNOWN_BROWSER_ISSUES[0]]);+ it('renders the detected issue with accessible semantics and the Helium workaround', async () => {+ detectKnownBrowserIssuesMock.mockReturnValue([createDetectedIssue('helium', 'other-browser')]);await renderAlert();- await vi.waitFor(() => expect(host?.textContent).toContain('Canvas protection may corrupt painted strokes'));const alert = host?.querySelector('[role="alert"]');const copyButton = host?.querySelector<HTMLButtonElement>('button[aria-label="Copy browser setting"]');@@ -107,41 +116,32 @@ describe('known browser issues alert', () => {expect(host?.querySelectorAll('button')).toHaveLength(1);});+ it('shows Brave users the Shields instruction without a copyable flag', async () => {+ detectKnownBrowserIssuesMock.mockReturnValue([createDetectedIssue('brave', 'other-browser')]);++ await renderAlert();++ const alert = host?.querySelector('[role="alert"]');++ expect(alert?.textContent).toContain('turn Shields off for this site');+ expect(alert?.textContent).not.toContain('Helium');+ expect(host?.querySelectorAll('button')).toHaveLength(0);+ });+it('copies the Helium setting address', async () => {const writeText = vi.fn(() => Promise.resolve());Object.defineProperty(navigator, 'clipboard', {configurable: true,value: { writeText },});- detectKnownBrowserIssuesMock.mockResolvedValue([KNOWN_BROWSER_ISSUES[0]]);+ detectKnownBrowserIssuesMock.mockReturnValue([createDetectedIssue('helium')]);await renderAlert();- const copyButton = await vi.waitFor(() => {- const button = host?.querySelector<HTMLButtonElement>('button[aria-label="Copy browser setting"]');- expect(button).not.toBeNull();- return button!;- });- await act(() => userEvent.click(copyButton));-- expect(writeText).toHaveBeenCalledWith('helium://flags/#helium-noise-canvas');- });-- it('ignores detection results that resolve after unmount', async () => {- let resolveDetection: ((issues: readonly (typeof KNOWN_BROWSER_ISSUES)[number][]) => void) | undefined;- detectKnownBrowserIssuesMock.mockReturnValueOnce(- new Promise<readonly (typeof KNOWN_BROWSER_ISSUES)[number][]>((resolve) => {- resolveDetection = resolve;- })- );+ const copyButton = host?.querySelector<HTMLButtonElement>('button[aria-label="Copy browser setting"]');- await renderAlert();- await act(() => root?.unmount());- root = null;- await act(async () => {- resolveDetection?.([KNOWN_BROWSER_ISSUES[0]]);- await Promise.resolve();- });+ expect(copyButton).not.toBeNull();+ await act(() => userEvent.click(copyButton!));- expect(host?.childElementCount).toBe(0);+ expect(writeText).toHaveBeenCalledWith('helium://flags/#helium-noise-canvas');});});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsxindex 9e61184ad1..fc152efef9 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx@@ -1,31 +1,17 @@import { Alert, Code, HStack, Icon, Stack, Text } from '@chakra-ui/react';import {detectKnownBrowserIssues,- type KnownBrowserIssue,+ type DetectedBrowserIssue,type KnownBrowserIssueWorkaround,} from '@platform/browser/knownBrowserIssues';-import { useMountEffect } from '@platform/react/useMountEffect';import { IconButton, toaster } from '@platform/ui';import { CopyIcon } from 'lucide-react';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';export const KnownBrowserIssuesAlert = () => {- const [issues, setIssues] = useState<readonly KnownBrowserIssue[]>([]);-- useMountEffect(() => {- let isMounted = true;-- void detectKnownBrowserIssues().then((detectedIssues) => {- if (isMounted) {- setIssues(detectedIssues);- }- });-- return () => {- isMounted = false;- };- });+ // The probe is cheap and its result is fixed for the page's lifetime, so it runs once per mount.+ const [issues] = useState(() => detectKnownBrowserIssues());if (issues.length === 0) {return null;@@ -40,7 +26,7 @@ export const KnownBrowserIssuesAlert = () => {);};-const BrowserIssueAlert = ({ issue }: { issue: KnownBrowserIssue }) => {+const BrowserIssueAlert = ({ issue }: { issue: DetectedBrowserIssue }) => {const { t } = useTranslation();return (