Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): sample chat-history contrast from a settled theme tree (#4761)

Nick Gomez38604da7c99b
diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.ts
index 8c395d932..da8194629 100644
--- a/packages/app/tests/stress/_helpers/index.ts
+++ b/packages/app/tests/stress/_helpers/index.ts
@@ -80,6 +80,8 @@ export {
FADE_DURATION_MS,
FADE_REPORT_WINDOW_MS,
installThemeFadeProbe,
+ runningRootAnimations,
+ switchColorThemeAndSettleFade,
type ThemeFadeProbeWindow,
type ThemeFadeReport,
} from './theme-fade.ts';
diff --git a/packages/app/tests/stress/_helpers/theme-fade.ts b/packages/app/tests/stress/_helpers/theme-fade.ts
index c9c465ca8..4cdc9345a 100644
--- a/packages/app/tests/stress/_helpers/theme-fade.ts
+++ b/packages/app/tests/stress/_helpers/theme-fade.ts
@@ -1,4 +1,5 @@
-import type { Page } from '@playwright/test';
+import { generateColorThemesCss } from '@inkeep/open-knowledge-core';
+import { expect, type Page } from '@playwright/test';
const FADE_REPORT_TIMEOUT_MS = process.env.CI ? 15_000 : 5_000;
const SEQUENTIAL_REPORT_SENTINELS = 2;
@@ -170,3 +171,35 @@ export async function installThemeFadeProbe(page: Page): Promise<void> {
};
}, FADE_REPORT_TIMEOUT_MS);
}
+
+const ATTRIBUTE_SELECTABLE_COLOR_THEMES: readonly string[] = [
+ ...generateColorThemesCss().matchAll(/^html\[data-color-theme="([^"]+)"\]/gm),
+].map(([, id]) => id);
+
+export function runningRootAnimations(page: Page): Promise<string[]> {
+ return page.evaluate(() => {
+ const isTransition = (animation: Animation): animation is CSSTransition =>
+ 'transitionProperty' in animation;
+ return document.documentElement
+ .getAnimations({ subtree: false })
+ .map((animation) =>
+ isTransition(animation) ? animation.transitionProperty : animation.constructor.name,
+ );
+ });
+}
+
+export async function switchColorThemeAndSettleFade(page: Page, colorTheme: string): Promise<void> {
+ if (!ATTRIBUTE_SELECTABLE_COLOR_THEMES.includes(colorTheme)) {
+ throw new Error(
+ `switchColorThemeAndSettleFade cannot apply "${colorTheme}" by writing data-color-theme: the product removes that attribute for default and injects a <style> element for custom and saved themes, so the write would match no stylesheet rule, change no token, start no fade, and this helper would return as a settled switch having changed nothing. It applies: ${ATTRIBUTE_SELECTABLE_COLOR_THEMES.join(', ')}`,
+ );
+ }
+ await page.evaluate((next) => {
+ document.documentElement.dataset.colorTheme = next;
+ }, colorTheme);
+ await expect
+ .poll(() => runningRootAnimations(page), {
+ message: `switchColorThemeAndSettleFade: the switch to ${colorTheme} left animations still running on :root past the product's ${FADE_DURATION_MS}ms fade, so every color read taken after this point samples a frame of the fade rather than the theme`,
+ })
+ .toEqual([]);
+}
diff --git a/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts b/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
index 767dfced9..78aef2074 100644
--- a/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
+++ b/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path';
import AxeBuilder from '@axe-core/playwright';
import type { Locator, Page } from '@playwright/test';
import { HISTORY_PANEL_WIDTH_PX } from '../../src/hooks/use-history-presentation-mode';
-import { expect, test } from './_helpers';
+import { expect, switchColorThemeAndSettleFade, test } from './_helpers';
const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
const AGENTS_REVEAL_TAB = '[data-terminal-reveal="right"]';
@@ -45,60 +45,57 @@ function relativeLuminance(channels: readonly number[]): number {
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
}
-async function readComputedColor(
- locator: Locator,
- property: 'color' | 'backgroundColor',
-): Promise<readonly [number, number, number, number]> {
- return locator.evaluate((element, colorProperty) => {
- const color = getComputedStyle(element)[colorProperty];
- const canvas = new OffscreenCanvas(1, 1);
- const context = canvas.getContext('2d', { willReadFrequently: true });
- if (!context) throw new Error('Could not create a color conversion context');
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = color;
- context.fillRect(0, 0, 1, 1);
- return Array.from(context.getImageData(0, 0, 1, 1).data) as [number, number, number, number];
- }, property);
+interface ContrastPair {
+ foreground: readonly [number, number, number, number];
+ background: readonly [number, number, number, number];
}
-async function readEffectiveBackground(
- locator: Locator,
-): Promise<readonly [number, number, number, number]> {
- return locator.evaluate((element) => {
- const canvas = new OffscreenCanvas(1, 1);
- const context = canvas.getContext('2d', { willReadFrequently: true });
- if (!context) throw new Error('Could not create a color conversion context');
- const layers: Array<[number, number, number, number]> = [];
- let current: Element | null = element;
- while (current !== null) {
- context.clearRect(0, 0, 1, 1);
- context.fillStyle = getComputedStyle(current).backgroundColor;
- context.fillRect(0, 0, 1, 1);
- const layer = Array.from(context.getImageData(0, 0, 1, 1).data) as [
- number,
- number,
- number,
- number,
- ];
- layers.push(layer);
- if (layer[3] === 255) break;
- current = current.parentElement;
- }
- const base = layers.at(-1);
- if (base === undefined || base[3] !== 255) {
- throw new Error('Contrast background has no opaque ancestor');
- }
- const composite = [...base] as [number, number, number, number];
- for (let index = layers.length - 2; index >= 0; index -= 1) {
- const layer = layers[index];
- if (layer === undefined) continue;
- const alpha = layer[3] / 255;
- for (let channel = 0; channel < 3; channel += 1) {
- composite[channel] = layer[channel] * alpha + composite[channel] * (1 - alpha);
+async function readContrastPair(foreground: Locator, background: Locator): Promise<ContrastPair> {
+ const backgroundElement = await background.elementHandle();
+ if (!backgroundElement) throw new Error('the contrast background locator resolved to no element');
+ try {
+ return await foreground.evaluate((foregroundElement, backgroundNode) => {
+ const canvas = new OffscreenCanvas(1, 1);
+ const context = canvas.getContext('2d', { willReadFrequently: true });
+ if (!context) throw new Error('Could not create a color conversion context');
+ const toBytes = (color: string): [number, number, number, number] => {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = color;
+ context.fillRect(0, 0, 1, 1);
+ return Array.from(context.getImageData(0, 0, 1, 1).data) as [
+ number,
+ number,
+ number,
+ number,
+ ];
+ };
+ const foregroundColor = toBytes(getComputedStyle(foregroundElement).color);
+ const layers: Array<[number, number, number, number]> = [];
+ let current: Element | null = backgroundNode;
+ while (current !== null) {
+ const layer = toBytes(getComputedStyle(current).backgroundColor);
+ layers.push(layer);
+ if (layer[3] === 255) break;
+ current = current.parentElement;
}
- }
- return composite;
- });
+ const base = layers.at(-1);
+ if (base === undefined || base[3] !== 255) {
+ throw new Error('Contrast background has no opaque ancestor');
+ }
+ const composite = [...base] as [number, number, number, number];
+ for (let index = layers.length - 2; index >= 0; index -= 1) {
+ const layer = layers[index];
+ if (layer === undefined) continue;
+ const alpha = layer[3] / 255;
+ for (let channel = 0; channel < 3; channel += 1) {
+ composite[channel] = layer[channel] * alpha + composite[channel] * (1 - alpha);
+ }
+ }
+ return { foreground: foregroundColor, background: composite };
+ }, backgroundElement);
+ } finally {
+ await backgroundElement.dispose();
+ }
}
async function expectContrast(
@@ -106,8 +103,10 @@ async function expectContrast(
background: Locator,
minimum: number,
): Promise<void> {
- const foregroundColor = await readComputedColor(foreground, 'color');
- const backgroundColor = await readEffectiveBackground(background);
+ const { foreground: foregroundColor, background: backgroundColor } = await readContrastPair(
+ foreground,
+ background,
+ );
const foregroundAlpha = foregroundColor[3] / 255;
const composite = foregroundColor
.slice(0, 3)
@@ -120,7 +119,10 @@ async function expectContrast(
const ratio =
(Math.max(foregroundLuminance, backgroundLuminance) + 0.05) /
(Math.min(foregroundLuminance, backgroundLuminance) + 0.05);
- expect(ratio).toBeGreaterThanOrEqual(minimum);
+ expect(
+ ratio,
+ `contrast ${ratio.toFixed(4)} is below the required ${minimum} for foreground rgba(${foregroundColor.join(', ')}) composited over background rgba(${backgroundColor.join(', ')})`,
+ ).toBeGreaterThanOrEqual(minimum);
}
function observedOrder(marks: RouteMark[]): RouteMarkRoute[] {
@@ -473,10 +475,7 @@ test.describe('chat history navigation', () => {
await alphaRename.hover();
await expectContrast(alphaRename, alphaListItem, 4.5);
await expectContrast(betaRow, betaRow.locator('xpath=..'), 4.5);
- await page.evaluate(() => {
- document.documentElement.dataset.colorTheme = 'solarized';
- document.documentElement.style.colorScheme = 'light';
- });
+ await switchColorThemeAndSettleFade(page, 'solarized');
await alphaRow.hover();
await expectContrast(alphaRow, alphaListItem, 4.5);
await expectContrast(alphaRename, alphaListItem, 4.5);
@@ -640,9 +639,7 @@ test.describe('chat history navigation', () => {
await expect(archivedDelete).not.toHaveAttribute('aria-disabled');
await archivedDelete.hover();
await expectContrast(archivedDelete, archivedListItem, 3);
- await page.evaluate(() => {
- document.documentElement.dataset.colorTheme = 'solarized';
- });
+ await switchColorThemeAndSettleFade(page, 'solarized');
await archivedRow.hover();
await expectContrast(archivedRename, archivedListItem, 4.5);
await archivedDelete.hover();
diff --git a/packages/app/tests/stress/theme-fade.e2e.ts b/packages/app/tests/stress/theme-fade.e2e.ts
index b15b8f8a2..1fc025668 100644
--- a/packages/app/tests/stress/theme-fade.e2e.ts
+++ b/packages/app/tests/stress/theme-fade.e2e.ts
@@ -1,9 +1,12 @@
+import type { Page } from '@playwright/test';
import {
expect,
FADE_DURATION_MS,
FADE_REPORT_WINDOW_MS,
installThemeFadeProbe,
openColorThemes,
+ runningRootAnimations,
+ switchColorThemeAndSettleFade,
type ThemeFadeProbeWindow,
test,
} from './_helpers';
@@ -135,17 +138,9 @@ test('theme settings retarget rapidly and honor reduced motion', async ({ page }
.getByRole('button', { name: 'Use Monokai for the active light mode' })
.evaluate((button) => button.click());
await expect.poll(() => page.locator('html').getAttribute('data-color-theme')).toBe('monokai');
- const rootTransitions = await page.evaluate(() => {
- const isTransition = (animation: Animation): animation is CSSTransition =>
- 'transitionProperty' in animation;
- return document.documentElement
- .getAnimations({ subtree: false })
- .map((animation) =>
- isTransition(animation) ? animation.transitionProperty : animation.constructor.name,
- );
- });
+ const rootAnimations = await runningRootAnimations(page);
expect(
- rootTransitions,
+ rootAnimations,
'under reduced motion a palette switch must start no transition on the document root',
).toEqual([]);
expect(await page.evaluate(() => document.activeElement?.getAttribute('data-testid'))).toBe(
@@ -388,3 +383,242 @@ test('default light and dark modes fade surfaces without losing selection', asyn
),
).toEqual([]);
});
+
+interface RootFadeWitnessWindow {
+ okRootFadeWitness?: { startedRootTransitions: number };
+ okRootFadeHold?: AbortController;
+}
+
+async function installRootFadeWitness(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const root = document.documentElement;
+ const witness = { startedRootTransitions: 0 };
+ (window as typeof window & RootFadeWitnessWindow).okRootFadeWitness = witness;
+ root.addEventListener('transitionrun', (event) => {
+ if (event.target !== root || !event.propertyName.startsWith('--')) return;
+ witness.startedRootTransitions += 1;
+ });
+ });
+}
+
+async function holdRootFadeOpen(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const root = document.documentElement;
+ const scope = window as typeof window & RootFadeWitnessWindow;
+ if (scope.okRootFadeHold && !scope.okRootFadeHold.signal.aborted) {
+ throw new Error(
+ 'holdRootFadeOpen(page) was called while a hold is still open; releaseRootFade(page) must run first, or the earlier hold can never be revoked',
+ );
+ }
+ const controller = new AbortController();
+ scope.okRootFadeHold = controller;
+ root.addEventListener(
+ 'transitionrun',
+ (event) => {
+ if (event.target !== root || !event.propertyName.startsWith('--')) return;
+ for (const animation of root.getAnimations({ subtree: false })) animation.pause();
+ },
+ { signal: controller.signal },
+ );
+ });
+}
+
+async function releaseRootFade(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const { okRootFadeHold } = window as typeof window & RootFadeWitnessWindow;
+ if (!okRootFadeHold) {
+ throw new Error(
+ 'window.okRootFadeHold is absent; holdRootFadeOpen(page) must run before releaseRootFade(page)',
+ );
+ }
+ if (okRootFadeHold.signal.aborted) {
+ throw new Error(
+ 'releaseRootFade(page) was called on an already-released hold, so it would resume whatever happens to be running rather than the fade a hold was keeping open',
+ );
+ }
+ okRootFadeHold.abort();
+ for (const animation of document.documentElement.getAnimations({ subtree: false })) {
+ animation.play();
+ }
+ });
+}
+
+function readStartedRootTransitions(page: Page): Promise<number> {
+ return page.evaluate(() => {
+ const { okRootFadeWitness } = window as typeof window & RootFadeWitnessWindow;
+ if (!okRootFadeWitness) {
+ throw new Error(
+ 'window.okRootFadeWitness is absent; installRootFadeWitness(page) must run after the last navigation',
+ );
+ }
+ return okRootFadeWitness.startedRootTransitions;
+ });
+}
+
+test('switching the color theme hands control back only once the :root fade has settled, and releasing the hold lets a later switch settle', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await expect(page.locator('html')).toHaveAttribute('data-theme-color-transitions');
+ await expect.poll(() => runningRootAnimations(page)).toEqual([]);
+ await installRootFadeWitness(page);
+ await holdRootFadeOpen(page);
+
+ let switchOutcome = 'pending';
+ const switching = switchColorThemeAndSettleFade(page, 'solarized').then(
+ () => {
+ switchOutcome = 'returned';
+ },
+ (error: Error) => {
+ switchOutcome = `failed: ${error.message}`;
+ },
+ );
+
+ await expect.poll(() => readStartedRootTransitions(page)).toBeGreaterThan(0);
+ const held = await runningRootAnimations(page);
+ expect(
+ held,
+ 'the color theme write started :root animations but none are held open, so the switch not having returned yet would prove nothing',
+ ).not.toEqual([]);
+ expect(
+ switchOutcome,
+ `the color theme switch handed control back while ${held.length} :root animations were held mid-fade, so every color read taken after it samples a frame of the fade rather than the theme`,
+ ).toBe('pending');
+
+ await releaseRootFade(page);
+ await switching;
+ expect(
+ switchOutcome,
+ 'releasing the held :root fade did not let the color theme switch return',
+ ).toBe('returned');
+
+ const startedBeforeAfterRelease = await readStartedRootTransitions(page);
+ let afterReleaseOutcome = 'pending';
+ await switchColorThemeAndSettleFade(page, 'dracula').then(
+ () => {
+ afterReleaseOutcome = 'returned';
+ },
+ (error: Error) => {
+ afterReleaseOutcome = `failed: ${error.message}`;
+ },
+ );
+ expect(
+ await readStartedRootTransitions(page),
+ 'the post-release color theme write started no :root transition, so it exercised no hold and its settling would prove nothing',
+ ).toBeGreaterThan(startedBeforeAfterRelease);
+ expect(
+ afterReleaseOutcome,
+ 'a color theme switch started after the release did not settle; if the reason is that the hold was never disarmed, every :root transition started after the release is paused on arrival with nothing left to play it',
+ ).toBe('returned');
+});
+
+test('switching to a color theme the attribute write cannot select fails the call', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await expect(page.locator('html')).toHaveAttribute('data-theme-color-transitions');
+ const before = await page.locator('html').getAttribute('data-color-theme');
+
+ for (const unselectable of ['default', 'custom', 'solarised']) {
+ await expect(
+ switchColorThemeAndSettleFade(page, unselectable),
+ `no stylesheet rule targets html[data-color-theme="${unselectable}"], so switching to it must fail rather than resolve as a settled switch that changed nothing`,
+ ).rejects.toThrow(/cannot apply/);
+ }
+
+ expect(
+ await page.locator('html').getAttribute('data-color-theme'),
+ 'a rejected color theme switch must leave the attribute the product owns untouched',
+ ).toBe(before);
+});
+
+test('switching the color theme under reduced motion returns with no fade to wait for', async ({
+ page,
+}) => {
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.goto('/');
+ await expect(page.locator('html')).toHaveAttribute('data-theme-color-transitions');
+ await installRootFadeWitness(page);
+
+ await switchColorThemeAndSettleFade(page, 'solarized');
+ const startedAtReturn = await readStartedRootTransitions(page);
+ const runningAtReturn = await runningRootAnimations(page);
+
+ await expect(
+ page.locator('html'),
+ 'the switch returned without applying the color theme, so "no fade was running" proves nothing',
+ ).toHaveAttribute('data-color-theme', 'solarized');
+ expect(
+ startedAtReturn,
+ 'reduced motion must suppress the fade entirely, so this test no longer exercises the nothing-to-wait-for path the barrier has to return from',
+ ).toBe(0);
+ expect(
+ runningAtReturn,
+ 'the color theme switch returned with animations still running on :root under reduced motion',
+ ).toEqual([]);
+});
+
+test('switching the color theme with its fade retargeted mid-flight still hands control back on a settled tree', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await expect(page.locator('html')).toHaveAttribute('data-theme-color-transitions');
+ await expect.poll(() => runningRootAnimations(page)).toEqual([]);
+ await installRootFadeWitness(page);
+ await holdRootFadeOpen(page);
+
+ let firstOutcome = 'pending';
+ const firstSwitch = switchColorThemeAndSettleFade(page, 'solarized').then(
+ () => {
+ firstOutcome = 'returned';
+ },
+ (error: Error) => {
+ firstOutcome = `failed: ${error.message}`;
+ },
+ );
+
+ await expect.poll(() => readStartedRootTransitions(page)).toBeGreaterThan(0);
+ const startedBeforeRetarget = await readStartedRootTransitions(page);
+ expect(
+ await runningRootAnimations(page),
+ 'the first color theme write started no :root animations that are still held open, so retargeting them would prove nothing',
+ ).not.toEqual([]);
+
+ let secondOutcome = 'pending';
+ const secondSwitch = switchColorThemeAndSettleFade(page, 'dracula').then(
+ () => {
+ secondOutcome = 'returned';
+ },
+ (error: Error) => {
+ secondOutcome = `failed: ${error.message}`;
+ },
+ );
+
+ await expect
+ .poll(() => readStartedRootTransitions(page), {
+ message:
+ 'the second color theme write started no new :root token transitions, so the first switch had no fade in flight to retarget and this test does not exercise the case it exists for',
+ })
+ .toBeGreaterThan(startedBeforeRetarget);
+
+ await releaseRootFade(page);
+ await firstSwitch;
+ await secondSwitch;
+
+ expect(
+ firstOutcome,
+ 'a second color theme switch retargeted the first switch’s fade, which cancels every :root token transition the first call was waiting on; the barrier must read the live animation list rather than hold promises for specific animation instances, or it surfaces that cancellation as the first call’s own failure',
+ ).toBe('returned');
+ expect(
+ secondOutcome,
+ 'the color theme switch that retargeted the fade did not hand control back once its own wave settled',
+ ).toBe('returned');
+ expect(
+ await runningRootAnimations(page),
+ 'both color theme switches returned with animations still running on :root',
+ ).toEqual([]);
+ await expect(
+ page.locator('html'),
+ 'the retargeting switch did not leave its own color theme on the attribute the product owns, so the settled tree is not the one the second call asked for',
+ ).toHaveAttribute('data-color-theme', 'dracula');
+});
diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.json
index e8c2f8ece..eaef5e89b 100644
--- a/packages/app/tsconfig.json
+++ b/packages/app/tsconfig.json
@@ -53,8 +53,11 @@
// guarantee also stops at the module boundary: the three `*.e2e.ts` call
// sites stay outside the program, so their
// `window as typeof window & ThemeFadeProbeWindow` casts and their reads off
- // the returned report are unchecked. It imports only `@playwright/test`, so
- // its closure adds no other file to the program.
+ // the returned report are unchecked — which is why the color-theme switch
+ // helper rejects an inapplicable theme id by throwing rather than by typing
+ // its parameter. It imports `@playwright/test` and
+ // `@inkeep/open-knowledge-core`, whose declarations `src` already pulls into
+ // the program, so its closure adds no other file to it.
"include": [
"src",
"*.ts",