Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Push a desktop window's theme source once per change (#4766)

Nick Gomez89fb4cea27e0
diff --git a/.changeset/theme-source-push-once-per-change.md b/.changeset/theme-source-push-once-per-change.md
new file mode 100644
index 000000000..f0d841004
--- /dev/null
+++ b/.changeset/theme-source-push-once-per-change.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+A desktop window now sends its theme preference to the native appearance once per change, instead of re-sending it whenever the colour palette or the config connection settles. When one window's appearance is changed by another, switch the affected window's own theme preference and back to restore it.
diff --git a/.changeset/theme-source-rejected-payload-bounded.md b/.changeset/theme-source-rejected-payload-bounded.md
new file mode 100644
index 000000000..41b0782ee
--- /dev/null
+++ b/.changeset/theme-source-rejected-payload-bounded.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+A bug report from the desktop app now carries each theme-preference change and the window that made it, and for a refused preference, the kind of value that arrived and, for text, its first 64 characters.
diff --git a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
index 5606287a1..a7eb1fe80 100644
--- a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
+++ b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
@@ -50,6 +50,40 @@ function makeRejectingBridge(rejectionError: Error): StubBridge {
};
}
+interface DeferredBridge extends StubBridge {
+ resolveCall: (index: number) => void;
+ rejectCall: (index: number, error: Error) => void;
+}
+
+function makeDeferredBridge(): DeferredBridge {
+ const setCalls: string[] = [];
+ const signalCalls: Array<{ reducedTransparency: boolean }> = [];
+ const pending: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];
+ return {
+ setThemeSource: (value: string) => {
+ setCalls.push(value);
+ return new Promise<{ ok: true }>((resolve, reject) => {
+ pending.push({ resolve: () => resolve({ ok: true as const }), reject });
+ });
+ },
+ signalThemeApplied: (payload: { reducedTransparency: boolean }) => {
+ signalCalls.push(payload);
+ },
+ setThemeSourceCalls: setCalls,
+ signalThemeAppliedCalls: signalCalls,
+ resolveCall: (index: number) => {
+ const deferred = pending[index];
+ if (!deferred) throw new Error(`no pending setThemeSource call at index ${index}`);
+ deferred.resolve();
+ },
+ rejectCall: (index: number, error: Error) => {
+ const deferred = pending[index];
+ if (!deferred) throw new Error(`no pending setThemeSource call at index ${index}`);
+ deferred.reject(error);
+ },
+ };
+}
+
function HookProbe({
bridge,
themeValue,
@@ -319,6 +353,127 @@ describe('useThemeBridge (Tier-3 mount)', () => {
},
{ timeout: ASYNC_EFFECT_TIMEOUT_MS },
);
+ expect(stubBridge.setThemeSourceCalls).toEqual(['dark']);
+ });
+
+ test('a readiness re-entry with an unchanged preference re-reports chrome without re-pushing the source', async () => {
+ const stubBridge = makeStubBridge();
+ const typedBridge = stubBridge as unknown as OkDesktopBridge;
+ const { rerender } = render(<HookProbe bridge={undefined} themeValue={undefined} />);
+
+ rerender(<HookProbe bridge={typedBridge} themeValue="system" />);
+ await waitFor(
+ () => {
+ expect(stubBridge.signalThemeAppliedCalls.length).toBe(1);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+ expect(stubBridge.setThemeSourceCalls).toEqual(['system']);
+
+ rerender(<HookProbe bridge={undefined} themeValue={undefined} />);
+ rerender(<HookProbe bridge={typedBridge} themeValue="system" />);
+
+ await waitFor(
+ () => {
+ expect(stubBridge.signalThemeAppliedCalls.length).toBe(2);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+ expect(stubBridge.setThemeSourceCalls).toEqual(['system']);
+ });
+
+ test('a re-render with a referentially distinct bridge re-pushes the unchanged preference', async () => {
+ const firstBridge = makeStubBridge();
+ const secondBridge = makeStubBridge();
+ expect(secondBridge).not.toBe(firstBridge);
+ const { rerender } = render(
+ <HookProbe bridge={firstBridge as unknown as OkDesktopBridge} themeValue="system" />,
+ );
+ await waitFor(
+ () => {
+ expect(firstBridge.setThemeSourceCalls).toEqual(['system']);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+
+ rerender(<HookProbe bridge={secondBridge as unknown as OkDesktopBridge} themeValue="system" />);
+
+ await waitFor(
+ () => {
+ expect(secondBridge.setThemeSourceCalls).toEqual(['system']);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+ expect(firstBridge.setThemeSourceCalls).toEqual(['system']);
+ });
+
+ test('a superseded push that later fails leaves the push that replaced it recorded', async () => {
+ const deferredBridge = makeDeferredBridge();
+ const typedBridge = deferredBridge as unknown as OkDesktopBridge;
+ const { rerender } = render(
+ <HookProbe bridge={typedBridge} themeValue="light" colorThemeKey="before" />,
+ );
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['light']);
+
+ rerender(<HookProbe bridge={typedBridge} themeValue="dark" colorThemeKey="before" />);
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['light', 'dark']);
+
+ await act(async () => {
+ deferredBridge.resolveCall(1);
+ });
+ await act(async () => {
+ deferredBridge.rejectCall(0, new Error('ipc-teardown: superseded push unreachable'));
+ });
+
+ rerender(<HookProbe bridge={typedBridge} themeValue="dark" colorThemeKey="after" />);
+
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['light', 'dark']);
+ });
+
+ test('a re-entry that skips the push waits for that push before signalling the theme applied', async () => {
+ const deferredBridge = makeDeferredBridge();
+ const typedBridge = deferredBridge as unknown as OkDesktopBridge;
+ const { rerender } = render(
+ <HookProbe bridge={typedBridge} themeValue="system" colorThemeKey="before" />,
+ );
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['system']);
+ expect(deferredBridge.signalThemeAppliedCalls).toHaveLength(0);
+
+ rerender(<HookProbe bridge={typedBridge} themeValue="system" colorThemeKey="after" />);
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['system']);
+ expect(deferredBridge.signalThemeAppliedCalls).toHaveLength(0);
+
+ await act(async () => {
+ deferredBridge.resolveCall(0);
+ });
+ await waitFor(
+ () => {
+ expect(deferredBridge.signalThemeAppliedCalls).toHaveLength(1);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+ });
+
+ test('a push that fails without being superseded is re-attempted on the next re-entry', async () => {
+ const deferredBridge = makeDeferredBridge();
+ const typedBridge = deferredBridge as unknown as OkDesktopBridge;
+ const { rerender } = render(
+ <HookProbe bridge={typedBridge} themeValue="dark" colorThemeKey="before" />,
+ );
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['dark']);
+
+ await act(async () => {
+ deferredBridge.rejectCall(0, new Error('ipc-teardown: setThemeSource bridge unreachable'));
+ });
+
+ rerender(<HookProbe bridge={typedBridge} themeValue="dark" colorThemeKey="after" />);
+
+ expect(deferredBridge.setThemeSourceCalls).toEqual(['dark', 'dark']);
});
test('waits for the final transition sample without rerendering its owner', async () => {
diff --git a/packages/app/src/hooks/use-theme-bridge.ts b/packages/app/src/hooks/use-theme-bridge.ts
index aeec737f4..c85e7d8fe 100644
--- a/packages/app/src/hooks/use-theme-bridge.ts
+++ b/packages/app/src/hooks/use-theme-bridge.ts
@@ -1,4 +1,4 @@
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
import { subscribeColorThemeEpoch } from '@/lib/color-theme-epoch';
import { cssColorToHex } from '@/lib/css-color-to-hex';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
@@ -31,11 +31,19 @@ function readChromeColors(): { bg: string; symbol: string } | undefined {
}
}
+type PushedSource = {
+ readonly bridge: OkDesktopBridge;
+ readonly source: ThemePreference;
+ readonly settled: Promise<unknown>;
+};
+
export function useThemeBridge(
bridge: OkDesktopBridge | undefined,
themeValue: ThemePreference | undefined,
colorThemeKey?: string,
): void {
+ const pushedSource = useRef<PushedSource | null>(null);
+
// biome-ignore lint/correctness/useExhaustiveDependencies: colorThemeKey requests a fresh settled report for same-mode palette changes
useEffect(() => {
if (themeValue !== 'light' && themeValue !== 'dark' && themeValue !== 'system') return;
@@ -57,22 +65,32 @@ export function useThemeBridge(
};
const unsubscribe = subscribeColorThemeEpoch(signalSettledTheme);
mql.addEventListener('change', signalSettledTheme);
- bridge
- .setThemeSource(themeValue)
- .catch((err: unknown) => {
- console.warn(
- JSON.stringify({
- event: 'theme-source-set-failed',
- themeValue,
- error: err instanceof Error ? err.message : String(err),
- }),
- );
- })
- .finally(() => {
- if (cancelled) return;
- applied = true;
- signalSettledTheme();
- });
+ const settle = () => {
+ if (cancelled) return;
+ applied = true;
+ signalSettledTheme();
+ };
+ const pushed = pushedSource.current;
+ if (pushed?.bridge === bridge && pushed.source === themeValue) {
+ void pushed.settled.then(settle);
+ } else {
+ const entry: PushedSource = {
+ bridge,
+ source: themeValue,
+ settled: bridge.setThemeSource(themeValue).catch((err: unknown) => {
+ if (pushedSource.current === entry) pushedSource.current = null;
+ console.warn(
+ JSON.stringify({
+ event: 'theme-source-set-failed',
+ themeValue,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ }),
+ };
+ pushedSource.current = entry;
+ void entry.settled.then(settle);
+ }
return () => {
cancelled = true;
unsubscribe();
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 6b5397f75..9b4d15504 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -499,7 +499,7 @@ import {
} from './terminal-window.ts';
import { getTerminalWindowContext, resolvePtyProjectRoot } from './terminal-window-registry.ts';
import { applyThemeApplied } from './theme-applied-handler.ts';
-import { applyThemeSource, isOkThemeSource } from './theme-handler.ts';
+import { applyThemeSource, emitThemeSourceRecord, isOkThemeSource } from './theme-handler.ts';
import { createUninstallScreenRegistry } from './uninstall-ipc.ts';
import {
loadUninstallEntry,
@@ -4403,7 +4403,7 @@ function registerIpcHandlers() {
return { ok: true };
});
- handle('ok:theme:set-source', async (_event, { source }) => {
+ handle('ok:theme:set-source', async (event, { source }) => {
return applyThemeSource(
{
getThemeSource: () =>
@@ -4411,9 +4411,10 @@ function registerIpcHandlers() {
setThemeSource: (s) => {
nativeTheme.themeSource = s;
},
- warn: (line) => console.warn(line),
+ emit: emitThemeSourceRecord,
},
source,
+ BrowserWindow.fromWebContents(event.sender)?.id ?? null,
);
});
diff --git a/packages/desktop/src/main/theme-handler.ts b/packages/desktop/src/main/theme-handler.ts
index aab18fe75..de4bc47a9 100644
--- a/packages/desktop/src/main/theme-handler.ts
+++ b/packages/desktop/src/main/theme-handler.ts
@@ -1,4 +1,5 @@
import type { OkThemeSource } from '../shared/bridge-contract.ts';
+import { getLogger } from './desktop-logger.ts';
const VALID_THEME_SOURCES: ReadonlySet<OkThemeSource> = new Set(['system', 'light', 'dark']);
@@ -6,33 +7,106 @@ export function isOkThemeSource(value: unknown): value is OkThemeSource {
return typeof value === 'string' && VALID_THEME_SOURCES.has(value as OkThemeSource);
}
+type AppliedThemeSourceRecord = {
+ readonly event: 'theme-source-set';
+ readonly source: OkThemeSource;
+ readonly prevSource: OkThemeSource;
+ readonly trigger: 'ipc';
+ readonly senderWindowId: number | null;
+};
+
+export type ThemeSourceRecord =
+ | AppliedThemeSourceRecord
+ | {
+ readonly event: 'theme-source-set-rejected';
+ readonly received: unknown;
+ readonly reason: 'invalid-source';
+ readonly senderWindowId: number | null;
+ };
+
+type ReceivedKind =
+ | 'string'
+ | 'number'
+ | 'bigint'
+ | 'boolean'
+ | 'symbol'
+ | 'function'
+ | 'object'
+ | 'array'
+ | 'null'
+ | 'undefined';
+
+type DurableThemeSourceRecord =
+ | AppliedThemeSourceRecord
+ | {
+ readonly event: 'theme-source-set-rejected';
+ readonly receivedKind: ReceivedKind;
+ readonly receivedSample: string | null;
+ readonly reason: 'invalid-source';
+ readonly senderWindowId: number | null;
+ };
+
+const RECEIVED_SAMPLE_MAX_CHARS = 64;
+
+function classifyReceived(received: unknown): ReceivedKind {
+ if (received === null) return 'null';
+ if (Array.isArray(received)) return 'array';
+ return typeof received;
+}
+
+function sampleReceived(received: unknown): string | null {
+ return typeof received === 'string' ? received.slice(0, RECEIVED_SAMPLE_MAX_CHARS) : null;
+}
+
+export function emitThemeSourceRecord(record: ThemeSourceRecord): void {
+ const durable: DurableThemeSourceRecord =
+ record.event === 'theme-source-set-rejected'
+ ? {
+ event: record.event,
+ reason: record.reason,
+ senderWindowId: record.senderWindowId,
+ receivedKind: classifyReceived(record.received),
+ receivedSample: sampleReceived(record.received),
+ }
+ : record;
+
+ try {
+ console.warn(JSON.stringify(record));
+ } catch {
+ console.warn(JSON.stringify(durable));
+ }
+ getLogger('theme').info(durable, record.event);
+}
+
interface ApplyThemeSourceDeps {
getThemeSource: () => OkThemeSource;
setThemeSource: (source: OkThemeSource) => void;
- warn: (line: string) => void;
+ emit: (record: ThemeSourceRecord) => void;
}
-export function applyThemeSource(deps: ApplyThemeSourceDeps, source: OkThemeSource): { ok: true } {
+export function applyThemeSource(
+ deps: ApplyThemeSourceDeps,
+ source: OkThemeSource,
+ senderWindowId: number | null,
+): { ok: true } {
if (!VALID_THEME_SOURCES.has(source)) {
- deps.warn(
- JSON.stringify({
- event: 'theme-source-set-rejected',
- received: source,
- reason: 'invalid-source',
- }),
- );
+ deps.emit({
+ event: 'theme-source-set-rejected',
+ received: source,
+ reason: 'invalid-source',
+ senderWindowId,
+ });
return { ok: true };
}
const prevSource = deps.getThemeSource();
deps.setThemeSource(source);
- deps.warn(
- JSON.stringify({
- event: 'theme-source-set',
- source,
- prevSource,
- trigger: 'ipc',
- }),
- );
+ deps.emit({
+ event: 'theme-source-set',
+ source,
+ prevSource,
+ trigger: 'ipc',
+ senderWindowId,
+ });
return { ok: true };
}
diff --git a/packages/desktop/tests/main/theme-handler.test.ts b/packages/desktop/tests/main/theme-handler.test.ts
index b6b623f68..91c39859b 100644
--- a/packages/desktop/tests/main/theme-handler.test.ts
+++ b/packages/desktop/tests/main/theme-handler.test.ts
@@ -1,9 +1,28 @@
-import { describe, expect, test } from 'vitest';
-import { applyThemeSource, isOkThemeSource } from '../../src/main/theme-handler.ts';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+const desktopLog = vi.hoisted(() => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+}));
+const getLogger = vi.hoisted(() => vi.fn(() => desktopLog));
+vi.mock('../../src/main/desktop-logger.ts', () => ({ getLogger }));
+
+import {
+ applyThemeSource,
+ emitThemeSourceRecord,
+ isOkThemeSource,
+ type ThemeSourceRecord,
+} from '../../src/main/theme-handler.ts';
import type { OkThemeSource } from '../../src/shared/bridge-contract.ts';
+import {
+ APPLIED_RECORD,
+ REJECTED_RECORD_WITH_UNSERIALIZABLE_PAYLOAD,
+} from './theme-source-records.test-helper.ts';
interface TraceEvent {
- step: 'getThemeSource' | 'setThemeSource' | 'warn';
+ step: 'getThemeSource' | 'setThemeSource' | 'emit';
args?: unknown;
}
@@ -13,6 +32,8 @@ function makeDeps(initialThemeSource: OkThemeSource = 'system') {
return {
trace,
getCurrent: () => current,
+ emitted: () =>
+ trace.filter((t) => t.step === 'emit').map((t) => t.args as Record<string, unknown>),
deps: {
getThemeSource: () => {
trace.push({ step: 'getThemeSource' });
@@ -22,8 +43,8 @@ function makeDeps(initialThemeSource: OkThemeSource = 'system') {
trace.push({ step: 'setThemeSource', args: { source } });
current = source;
},
- warn: (line: string) => {
- trace.push({ step: 'warn', args: { line } });
+ emit: (record: ThemeSourceRecord) => {
+ trace.push({ step: 'emit', args: record });
},
},
};
@@ -32,30 +53,30 @@ function makeDeps(initialThemeSource: OkThemeSource = 'system') {
describe('applyThemeSource happy path', () => {
test('flips nativeTheme.themeSource from system to dark', () => {
const { deps, getCurrent } = makeDeps('system');
- const result = applyThemeSource(deps, 'dark');
+ const result = applyThemeSource(deps, 'dark', 3);
expect(result).toEqual({ ok: true });
expect(getCurrent()).toBe('dark');
});
- test('emits structured warn with prevSource and trigger=ipc', () => {
- const { deps, trace } = makeDeps('light');
- applyThemeSource(deps, 'dark');
- const warns = trace.filter((t) => t.step === 'warn');
- expect(warns).toHaveLength(1);
- const line = (warns[0]?.args as { line: string } | undefined)?.line;
- expect(JSON.parse(line)).toEqual({
- event: 'theme-source-set',
- source: 'dark',
- prevSource: 'light',
- trigger: 'ipc',
- });
+ test('emits a structured record with prevSource and trigger=ipc', () => {
+ const { deps, emitted } = makeDeps('light');
+ applyThemeSource(deps, 'dark', 7);
+ expect(emitted()).toEqual([
+ {
+ event: 'theme-source-set',
+ source: 'dark',
+ prevSource: 'light',
+ trigger: 'ipc',
+ senderWindowId: 7,
+ },
+ ]);
});
test.each([['system' as OkThemeSource], ['light' as OkThemeSource], ['dark' as OkThemeSource]])(
'accepts each user-intent value: %s',
(source) => {
const { deps, getCurrent } = makeDeps('system');
- const result = applyThemeSource(deps, source);
+ const result = applyThemeSource(deps, source, 1);
expect(result).toEqual({ ok: true });
expect(getCurrent()).toBe(source);
},
@@ -65,23 +86,39 @@ describe('applyThemeSource happy path', () => {
describe('applyThemeSource defensive rejection', () => {
test('does not call setThemeSource for an out-of-range value', () => {
const { deps, trace, getCurrent } = makeDeps('system');
- const result = applyThemeSource(deps, 'auto' as unknown as OkThemeSource);
+ const result = applyThemeSource(deps, 'auto' as unknown as OkThemeSource, 1);
expect(result).toEqual({ ok: true });
expect(getCurrent()).toBe('system');
expect(trace.find((t) => t.step === 'setThemeSource')).toBeUndefined();
});
- test('emits structured warn with reason=invalid-source on rejection', () => {
- const { deps, trace } = makeDeps('system');
- applyThemeSource(deps, 'rainbow' as unknown as OkThemeSource);
- const warns = trace.filter((t) => t.step === 'warn');
- expect(warns).toHaveLength(1);
- const line = (warns[0]?.args as { line: string } | undefined)?.line;
- expect(JSON.parse(line)).toEqual({
- event: 'theme-source-set-rejected',
- received: 'rainbow',
- reason: 'invalid-source',
- });
+ test('emits a structured record with reason=invalid-source on rejection', () => {
+ const { deps, emitted } = makeDeps('system');
+ applyThemeSource(deps, 'rainbow' as unknown as OkThemeSource, 4);
+ expect(emitted()).toEqual([
+ {
+ event: 'theme-source-set-rejected',
+ received: 'rainbow',
+ reason: 'invalid-source',
+ senderWindowId: 4,
+ },
+ ]);
+ });
+});
+
+describe('applyThemeSource sender attribution', () => {
+ test('records a null senderWindowId when the sender has no window', () => {
+ const { deps, emitted } = makeDeps('system');
+ applyThemeSource(deps, 'light', null);
+ expect(emitted()).toHaveLength(1);
+ expect(emitted()[0]?.senderWindowId).toBeNull();
+ });
+
+ test('distinguishes two windows pushing the same source', () => {
+ const { deps, emitted } = makeDeps('system');
+ applyThemeSource(deps, 'system', 1);
+ applyThemeSource(deps, 'system', 2);
+ expect(emitted().map((record) => record.senderWindowId)).toEqual([1, 2]);
});
});
@@ -89,7 +126,133 @@ describe('applyThemeSource side-effect boundaries', () => {
test('does not require setBackgroundColor or saveAppState — those deps are absent', () => {
const { deps } = makeDeps('system');
const depKeys = new Set(Object.keys(deps));
- expect(depKeys).toEqual(new Set(['getThemeSource', 'setThemeSource', 'warn']));
+ expect(depKeys).toEqual(new Set(['getThemeSource', 'setThemeSource', 'emit']));
+ });
+});
+
+describe('emitThemeSourceRecord dual sink', () => {
+ const consoleWarnCalls: unknown[][] = [];
+ let restoreConsoleWarn = () => {};
+
+ beforeEach(() => {
+ consoleWarnCalls.length = 0;
+ getLogger.mockClear();
+ desktopLog.info.mockClear();
+ const spy = vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {
+ consoleWarnCalls.push(args);
+ });
+ restoreConsoleWarn = () => {
+ spy.mockRestore();
+ };
+ });
+
+ afterEach(() => {
+ restoreConsoleWarn();
+ });
+
+ function soleConsoleLine(): string {
+ expect(consoleWarnCalls).toHaveLength(1);
+ const args = consoleWarnCalls[0] ?? [];
+ expect(args).toHaveLength(1);
+ const [line] = args;
+ expect(typeof line).toBe('string');
+ return String(line);
+ }
+
+ function soleDurableRecord(): Record<string, unknown> {
+ expect(desktopLog.info).toHaveBeenCalledTimes(1);
+ const [data] = desktopLog.info.mock.calls[0] ?? [];
+ expect(data).toBeTypeOf('object');
+ return data;
+ }
+
+ test('writes the whole record to the console sink as one JSON line', () => {
+ emitThemeSourceRecord(APPLIED_RECORD);
+ expect(JSON.parse(soleConsoleLine())).toEqual(APPLIED_RECORD);
+ });
+
+ test('writes the whole record to the durable theme log under the event as message', () => {
+ emitThemeSourceRecord(APPLIED_RECORD);
+ expect(getLogger).toHaveBeenCalledWith('theme');
+ expect(desktopLog.info).toHaveBeenCalledTimes(1);
+ expect(desktopLog.info.mock.calls[0]?.[0]).toEqual(APPLIED_RECORD);
+ expect(desktopLog.info.mock.calls[0]?.[1]).toBe('theme-source-set');
+ });
+
+ test('leaves rejection-only fields off an applied record in the durable sink', () => {
+ emitThemeSourceRecord(APPLIED_RECORD);
+ const durable = soleDurableRecord();
+ expect(Object.keys(durable)).toContain('event');
+ expect(durable).not.toHaveProperty('receivedKind');
+ expect(durable).not.toHaveProperty('receivedSample');
+ });
+
+ test('keeps a rejected payload out of the durable sink', () => {
+ emitThemeSourceRecord({
+ event: 'theme-source-set-rejected',
+ received: { auth: { token: 'SHOULD-NOT-APPEAR' } },
+ reason: 'invalid-source',
+ senderWindowId: 2,
+ });
+ const durable = soleDurableRecord();
+ expect(JSON.stringify(durable)).not.toContain('SHOULD-NOT-APPEAR');
+ expect(durable).not.toHaveProperty('received');
+ expect(durable.receivedKind).toBe('object');
+ });
+
+ test('classifies a rejected array as an array, not a bare object', () => {
+ emitThemeSourceRecord({
+ event: 'theme-source-set-rejected',
+ received: ['dark', { auth: { token: 'SHOULD-NOT-APPEAR' } }],
+ reason: 'invalid-source',
+ senderWindowId: 3,
+ });
+ const durable = soleDurableRecord();
+ expect(durable.receivedKind).toBe('array');
+ expect(JSON.stringify(durable)).not.toContain('SHOULD-NOT-APPEAR');
+ expect(durable).not.toHaveProperty('received');
+ });
+
+ test('bounds a long rejected string in the durable sink', () => {
+ emitThemeSourceRecord({
+ event: 'theme-source-set-rejected',
+ received: 'x'.repeat(5000),
+ reason: 'invalid-source',
+ senderWindowId: 2,
+ });
+ const durable = soleDurableRecord();
+ expect(durable.receivedSample).toBeTypeOf('string');
+ expect(durable.receivedSample).toHaveLength(64);
+ });
+
+ test('writes the unbounded rejected payload to the console sink', () => {
+ emitThemeSourceRecord({
+ event: 'theme-source-set-rejected',
+ received: { auth: { token: 'X' } },
+ reason: 'invalid-source',
+ senderWindowId: 5,
+ });
+ expect(JSON.parse(soleConsoleLine())).toEqual({
+ event: 'theme-source-set-rejected',
+ received: { auth: { token: 'X' } },
+ reason: 'invalid-source',
+ senderWindowId: 5,
+ });
+ });
+
+ test('keeps the durable sink reachable when a rejected payload cannot be serialized', () => {
+ expect(() => emitThemeSourceRecord(REJECTED_RECORD_WITH_UNSERIALIZABLE_PAYLOAD)).not.toThrow();
+
+ const degraded = {
+ event: 'theme-source-set-rejected',
+ reason: 'invalid-source',
+ senderWindowId: 4,
+ receivedKind: 'bigint',
+ receivedSample: null,
+ };
+ expect(soleDurableRecord()).toEqual(degraded);
+ expect(desktopLog.info.mock.calls[0]?.[1]).toBe('theme-source-set-rejected');
+ expect(JSON.parse(soleConsoleLine())).toEqual(degraded);
});
});
diff --git a/packages/desktop/tests/main/theme-source-records.test-helper.ts b/packages/desktop/tests/main/theme-source-records.test-helper.ts
new file mode 100644
index 000000000..96b2731c3
--- /dev/null
+++ b/packages/desktop/tests/main/theme-source-records.test-helper.ts
@@ -0,0 +1,16 @@
+import type { ThemeSourceRecord } from '../../src/main/theme-handler.ts';
+
+export const APPLIED_RECORD = {
+ event: 'theme-source-set',
+ source: 'dark',
+ prevSource: 'light',
+ trigger: 'ipc',
+ senderWindowId: 7,
+} as const satisfies ThemeSourceRecord;
+
+export const REJECTED_RECORD_WITH_UNSERIALIZABLE_PAYLOAD = {
+ event: 'theme-source-set-rejected',
+ received: 10n,
+ reason: 'invalid-source',
+ senderWindowId: 4,
+} as const satisfies ThemeSourceRecord;
diff --git a/packages/desktop/tests/smoke/_helpers/theme-source-contract.test.ts b/packages/desktop/tests/smoke/_helpers/theme-source-contract.test.ts
new file mode 100644
index 000000000..8dda7c259
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/theme-source-contract.test.ts
@@ -0,0 +1,82 @@
+import { Console } from 'node:console';
+import { PassThrough } from 'node:stream';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+vi.mock('../../../src/main/desktop-logger.ts', () => ({
+ getLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),
+}));
+
+import { applyThemeSource, emitThemeSourceRecord } from '../../../src/main/theme-handler.ts';
+import type { OkThemeSource } from '../../../src/shared/bridge-contract.ts';
+import { observeThemeSourcePushes } from './theme-source-pushes.ts';
+
+let restoreConsoleWarn = () => {};
+
+afterEach(() => {
+ restoreConsoleWarn();
+ restoreConsoleWarn = () => {};
+});
+
+function wiredMainProcess(initialThemeSource: OkThemeSource = 'system') {
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const mainProcessConsole = new Console({ stdout, stderr });
+ const spy = vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {
+ mainProcessConsole.warn(...args);
+ });
+ restoreConsoleWarn = () => {
+ spy.mockRestore();
+ };
+ let themeSource = initialThemeSource;
+ return {
+ app: { process: () => ({ stdout, stderr }) },
+ deps: {
+ getThemeSource: () => themeSource,
+ setThemeSource: (source: OkThemeSource) => {
+ themeSource = source;
+ },
+ emit: emitThemeSourceRecord,
+ },
+ };
+}
+
+describe('theme source push producer/observer contract', () => {
+ test('the observer recovers the window id the producer was handed', () => {
+ const { app, deps } = wiredMainProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ applyThemeSource(deps, 'dark', 11);
+
+ expect([...pushedBy]).toEqual([11]);
+ });
+
+ test('the observer separates two windows pushing the same source', () => {
+ const { app, deps } = wiredMainProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ applyThemeSource(deps, 'light', 11);
+ applyThemeSource(deps, 'light', 12);
+
+ expect([...pushedBy]).toEqual([11, 12]);
+ });
+
+ test('a push the producer refuses to apply is not observed', () => {
+ const { app, deps } = wiredMainProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ applyThemeSource(deps, 'dark', 11);
+ applyThemeSource(deps, 'rainbow' as unknown as OkThemeSource, 12);
+
+ expect([...pushedBy]).toEqual([11]);
+ });
+
+ test('a sender with no window is not observed as a window push', () => {
+ const { app, deps } = wiredMainProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ applyThemeSource(deps, 'dark', 11);
+ applyThemeSource(deps, 'light', null);
+
+ expect([...pushedBy]).toEqual([11]);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/theme-source-pushes.test.ts b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.test.ts
new file mode 100644
index 000000000..1dc7c62e6
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.test.ts
@@ -0,0 +1,312 @@
+import { PassThrough } from 'node:stream';
+import { describe, expect, test } from 'vitest';
+import {
+ observeThemeSourcePushes,
+ probeLiveWindowsInMain,
+ type ThemeSourceWindowProbe,
+ windowsStillOwingAThemeSourcePush,
+} from './theme-source-pushes';
+
+function pushLine(senderWindowId: number): string {
+ return `${JSON.stringify({ event: 'theme-source-set', source: 'dark', senderWindowId })}\n`;
+}
+
+function fakeElectronProcess() {
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ return { stdout, stderr, app: { process: () => ({ stdout, stderr }) } };
+}
+
+describe('observeThemeSourcePushes', () => {
+ test('records the sender of a push line delivered whole on stderr', () => {
+ const { stderr, app } = fakeElectronProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ stderr.emit('data', Buffer.from(pushLine(3), 'utf8'));
+
+ expect([...pushedBy]).toEqual([3]);
+ });
+
+ test('records the sender of a push line delivered whole on stdout', () => {
+ const { stdout, app } = fakeElectronProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+
+ stdout.emit('data', Buffer.from(pushLine(4), 'utf8'));
+
+ expect([...pushedBy]).toEqual([4]);
+ });
+
+ test('reassembles a stderr push line split around a chunk from stdout', () => {
+ const { stdout, stderr, app } = fakeElectronProcess();
+ const pushedBy = observeThemeSourcePushes(app);
+ const line = pushLine(7);
+ const splitAt = line.indexOf('"source"');
+
+ stderr.emit('data', Buffer.from(line.slice(0, splitAt), 'utf8'));
+ stdout.emit('data', Buffer.from('[1:0921/084326.1:INFO:x.cc(9)] unrelated noise\n', 'utf8'));
+ stderr.emit('data', Buffer.from(line.slice(splitAt), 'utf8'));
+
+ expect([...pushedBy]).toEqual([7]);
+ });
+});
+
+interface FakeProbedWindow {
+ id: number;
+ url?: string;
+ loading?: boolean;
+ destroyed?: boolean;
+ executeJavaScript: (code: string) => Promise<unknown>;
+}
+
+function fakeElectron(windows: readonly FakeProbedWindow[]) {
+ return {
+ BrowserWindow: {
+ getAllWindows: () =>
+ windows.map((win) => ({
+ id: win.id,
+ isDestroyed: () => win.destroyed === true,
+ webContents: {
+ getURL: () => win.url ?? `file:///app/index.html#/${win.id}`,
+ isLoading: () => win.loading === true,
+ executeJavaScript: win.executeJavaScript,
+ },
+ })),
+ },
+ };
+}
+
+const PROBE_LIMITS = { abandonProbeAfterMs: 20, maxCauseChars: 200 };
+
+describe('probeLiveWindowsInMain', () => {
+ test('reports a renderer that answers with the bridge exposed as present', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([{ id: 1, executeJavaScript: async () => true }]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes).toEqual([
+ { id: 1, url: 'file:///app/index.html#/1', loading: false, bridge: 'present' },
+ ]);
+ });
+
+ test('reports a renderer that answers without the bridge as absent', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([{ id: 2, executeJavaScript: async () => false }]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['absent']);
+ expect(probes[0]?.cause).toBeUndefined();
+ });
+
+ test('reports a renderer whose probe is rejected as probe-rejected, quoting the rejection', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([
+ {
+ id: 3,
+ executeJavaScript: async () => {
+ throw new Error('Render frame was disposed before executeJavaScript could be run');
+ },
+ },
+ ]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['probe-rejected']);
+ expect(probes[0]?.cause).toContain('Render frame was disposed');
+ });
+
+ test('reports a renderer whose probe never answers as probe-unanswered, naming the bound', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([{ id: 4, executeJavaScript: () => new Promise<never>(() => {}) }]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['probe-unanswered']);
+ expect(probes[0]?.cause).toContain('20ms');
+ });
+
+ test('bounds a runaway rejection message at maxCauseChars', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([
+ {
+ id: 5,
+ executeJavaScript: async () => {
+ throw new Error('x'.repeat(5_000));
+ },
+ },
+ ]),
+ { abandonProbeAfterMs: 20, maxCauseChars: 32 },
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['probe-rejected']);
+ expect(probes[0]?.cause).toBe('x'.repeat(32));
+ });
+
+ test('records a bounded cause for a rejection that is not an Error', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([{ id: 6, executeJavaScript: () => Promise.reject('script failed') }]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['probe-rejected']);
+ expect(probes[0]?.cause).toBe('script failed');
+ });
+
+ test('carries each live window id, url and load state through its probe', async () => {
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([
+ {
+ id: 7,
+ url: 'file:///app/index.html#/doc',
+ loading: true,
+ executeJavaScript: async () => true,
+ },
+ {
+ id: 8,
+ url: 'http://localhost:3030/',
+ loading: false,
+ executeJavaScript: async () => false,
+ },
+ ]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes).toEqual([
+ { id: 7, url: 'file:///app/index.html#/doc', loading: true, bridge: 'present' },
+ { id: 8, url: 'http://localhost:3030/', loading: false, bridge: 'absent' },
+ ]);
+ });
+
+ test('skips a destroyed window instead of probing it', async () => {
+ const reached: number[] = [];
+ const answerAndRecord = (id: number) => async () => {
+ reached.push(id);
+ return true;
+ };
+
+ const probes = await probeLiveWindowsInMain(
+ fakeElectron([
+ { id: 9, destroyed: true, executeJavaScript: answerAndRecord(9) },
+ { id: 10, executeJavaScript: answerAndRecord(10) },
+ ]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.id)).toEqual([10]);
+ expect(reached).toEqual([10]);
+ });
+
+ test('keeps answering after Playwright serializes it through String(pageFunction)', async () => {
+ const rebuilt = new Function(
+ `return ${String(probeLiveWindowsInMain)}`,
+ )() as typeof probeLiveWindowsInMain;
+
+ const probes = await rebuilt(
+ fakeElectron([
+ {
+ id: 11,
+ executeJavaScript: async () => {
+ throw new Error('Render frame was disposed');
+ },
+ },
+ ]),
+ PROBE_LIMITS,
+ );
+
+ expect(probes.map((probe) => probe.bridge)).toEqual(['probe-rejected']);
+ expect(probes[0]?.cause).toContain('Render frame was disposed');
+ });
+});
+
+describe('windowsStillOwingAThemeSourcePush', () => {
+ test('drops a settled bridgeless window, which has no way to push a theme source', () => {
+ const slidesWindow: ThemeSourceWindowProbe = {
+ id: 5,
+ url: 'http://localhost:3030/',
+ bridge: 'absent',
+ loading: false,
+ };
+
+ expect(windowsStillOwingAThemeSourcePush([slidesWindow], new Set())).toEqual([]);
+ });
+
+ test('keeps a bridged window that has not pushed, and a loading window whose bridge is not up yet', () => {
+ const windows: ThemeSourceWindowProbe[] = [
+ { id: 1, url: 'file:///app/index.html#/doc', bridge: 'present', loading: false },
+ { id: 2, url: '', bridge: 'absent', loading: true },
+ { id: 3, url: 'file:///app/index.html#/other', bridge: 'present', loading: false },
+ ];
+
+ const owed = windowsStillOwingAThemeSourcePush(windows, new Set([3]));
+
+ expect(owed.map(({ id, reason }) => ({ id, reason }))).toEqual([
+ { id: 1, reason: 'owes' },
+ { id: 2, reason: 'loading' },
+ ]);
+ });
+
+ test('names each stalled window by its own url', () => {
+ const windows: ThemeSourceWindowProbe[] = [
+ { id: 11, url: 'file:///app/index.html#/first', bridge: 'present', loading: false },
+ { id: 12, url: 'file:///app/uninstall.html', bridge: 'present', loading: false },
+ ];
+
+ expect(windowsStillOwingAThemeSourcePush(windows, new Set())).toEqual([
+ { id: 11, url: 'file:///app/index.html#/first', reason: 'owes' },
+ { id: 12, url: 'file:///app/uninstall.html', reason: 'owes' },
+ ]);
+ });
+
+ test('keeps a settled window whose bridge probe was rejected, and carries the rejection cause', () => {
+ const rejectedWindow: ThemeSourceWindowProbe = {
+ id: 9,
+ url: 'file:///app/index.html#/stalled',
+ bridge: 'probe-rejected',
+ loading: false,
+ cause: 'Render frame was disposed',
+ };
+
+ expect(windowsStillOwingAThemeSourcePush([rejectedWindow], new Set())).toEqual([
+ {
+ id: 9,
+ url: 'file:///app/index.html#/stalled',
+ reason: 'probe-rejected',
+ cause: 'Render frame was disposed',
+ },
+ ]);
+ });
+
+ test('keeps a settled window whose bridge probe never answered, since it cannot be told apart from one that owes a push', () => {
+ const unansweredWindow: ThemeSourceWindowProbe = {
+ id: 10,
+ url: 'file:///app/index.html#/silent',
+ bridge: 'probe-unanswered',
+ loading: false,
+ cause: 'bridge probe went unanswered for 2000ms',
+ };
+
+ expect(windowsStillOwingAThemeSourcePush([unansweredWindow], new Set())).toEqual([
+ {
+ id: 10,
+ url: 'file:///app/index.html#/silent',
+ reason: 'probe-unanswered',
+ cause: 'bridge probe went unanswered for 2000ms',
+ },
+ ]);
+ });
+
+ test('a push settles a window regardless of load state', () => {
+ const pushedWhileStillLoading: ThemeSourceWindowProbe = {
+ id: 8,
+ url: 'file:///app/index.html#/booting',
+ bridge: 'present',
+ loading: true,
+ };
+
+ expect(windowsStillOwingAThemeSourcePush([pushedWhileStillLoading], new Set())).toEqual([
+ { id: 8, url: 'file:///app/index.html#/booting', reason: 'loading' },
+ ]);
+ expect(windowsStillOwingAThemeSourcePush([pushedWhileStillLoading], new Set([8]))).toEqual([]);
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/theme-source-pushes.ts b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.ts
new file mode 100644
index 000000000..d3e113431
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.ts
@@ -0,0 +1,182 @@
+import type { ChildProcess } from 'node:child_process';
+import { type ElectronApplication, expect } from '@playwright/test';
+
+export interface ThemeSourcePushSource {
+ process(): Pick<ChildProcess, 'stdout' | 'stderr'>;
+}
+
+export function observeThemeSourcePushes(app: ThemeSourcePushSource): ReadonlySet<number> {
+ const senderWindowIds = new Set<number>();
+ const absorbLines = () => {
+ let pending = '';
+ return (chunk: Buffer | string) => {
+ pending += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
+ const lines = pending.split('\n');
+ pending = lines.pop() ?? '';
+ for (const line of lines) {
+ const brace = line.indexOf('{');
+ if (brace === -1) continue;
+ let parsed: { event?: string; senderWindowId?: unknown };
+ try {
+ parsed = JSON.parse(line.slice(brace)) as typeof parsed;
+ } catch {
+ continue;
+ }
+ if (parsed.event === 'theme-source-set' && typeof parsed.senderWindowId === 'number') {
+ senderWindowIds.add(parsed.senderWindowId);
+ }
+ }
+ };
+ };
+ const proc = app.process();
+ proc.stderr?.on('data', absorbLines());
+ proc.stdout?.on('data', absorbLines());
+ return senderWindowIds;
+}
+
+type ThemeSourceProbeFailure = 'probe-rejected' | 'probe-unanswered';
+
+interface ProbedWindowIdentity {
+ id: number;
+ url: string;
+ loading: boolean;
+}
+
+export type ThemeSourceWindowProbe =
+ | (ProbedWindowIdentity & { bridge: 'present' | 'absent'; cause?: never })
+ | (ProbedWindowIdentity & { bridge: ThemeSourceProbeFailure; cause: string });
+
+interface ThemeSourcePushDebtIdentity {
+ id: number;
+ url: string;
+}
+
+export type ThemeSourcePushDebt =
+ | (ThemeSourcePushDebtIdentity & { reason: 'owes'; cause?: never })
+ | (ThemeSourcePushDebtIdentity & { reason: 'loading'; cause?: string })
+ | (ThemeSourcePushDebtIdentity & { reason: ThemeSourceProbeFailure; cause: string });
+
+export function windowsStillOwingAThemeSourcePush(
+ windows: readonly ThemeSourceWindowProbe[],
+ pushedBy: ReadonlySet<number>,
+): readonly ThemeSourcePushDebt[] {
+ const owed: ThemeSourcePushDebt[] = [];
+ for (const probe of windows) {
+ if (pushedBy.has(probe.id)) continue;
+ const { id, url } = probe;
+ if (probe.loading) {
+ owed.push(
+ probe.cause === undefined
+ ? { id, url, reason: 'loading' }
+ : { id, url, reason: 'loading', cause: probe.cause },
+ );
+ continue;
+ }
+ if (probe.bridge === 'probe-rejected') {
+ owed.push({ id, url, reason: 'probe-rejected', cause: probe.cause });
+ continue;
+ }
+ if (probe.bridge === 'probe-unanswered') {
+ owed.push({ id, url, reason: 'probe-unanswered', cause: probe.cause });
+ continue;
+ }
+ if (probe.bridge === 'absent') continue;
+ owed.push({ id, url, reason: 'owes' });
+ }
+ return owed;
+}
+
+const NO_WINDOW_HAS_PUSHED: ReadonlySet<number> = new Set();
+
+const ABANDON_UNANSWERED_BRIDGE_PROBE_AFTER_MS = 2_000;
+
+const MAX_PROBE_FAILURE_CAUSE_CHARS = 200;
+
+interface ProbedWebContents {
+ getURL(): string;
+ isLoading(): boolean;
+ executeJavaScript(code: string): Promise<unknown>;
+}
+
+interface ProbedWindow {
+ id: number;
+ isDestroyed(): boolean;
+ webContents: ProbedWebContents;
+}
+
+interface ProbedElectron {
+ BrowserWindow: { getAllWindows(): ProbedWindow[] };
+}
+
+interface ThemeSourceProbeLimits {
+ abandonProbeAfterMs: number;
+ maxCauseChars: number;
+}
+
+/* STOP: probeLiveWindowsInMain is serialized into the Electron main process through
+ String(pageFunction), so it must stay closure-free and import-free. Values reach it
+ only through the limits argument. */
+export const probeLiveWindowsInMain = (
+ { BrowserWindow }: ProbedElectron,
+ limits: ThemeSourceProbeLimits,
+): Promise<ThemeSourceWindowProbe[]> =>
+ Promise.all(
+ BrowserWindow.getAllWindows()
+ .filter((win) => !win.isDestroyed())
+ .map((win) => {
+ const id = win.id;
+ const url = win.webContents.getURL();
+ const loading = win.webContents.isLoading();
+ return new Promise<ThemeSourceWindowProbe>((settle) => {
+ const abandonProbe = setTimeout(
+ () =>
+ settle({
+ id,
+ url,
+ loading,
+ bridge: 'probe-unanswered',
+ cause: `bridge probe went unanswered for ${limits.abandonProbeAfterMs}ms`,
+ }),
+ limits.abandonProbeAfterMs,
+ );
+ win.webContents
+ .executeJavaScript('typeof window.okDesktop?.setThemeSource === "function"')
+ .then((exposed: unknown) => {
+ clearTimeout(abandonProbe);
+ settle({ id, url, loading, bridge: exposed === true ? 'present' : 'absent' });
+ })
+ .catch((cause: unknown) => {
+ clearTimeout(abandonProbe);
+ settle({
+ id,
+ url,
+ loading,
+ bridge: 'probe-rejected',
+ cause: (cause instanceof Error ? cause.message : String(cause)).slice(
+ 0,
+ limits.maxCauseChars,
+ ),
+ });
+ });
+ });
+ }),
+ );
+
+function probeLiveWindows(app: ElectronApplication): Promise<ThemeSourceWindowProbe[]> {
+ return app.evaluate(probeLiveWindowsInMain, {
+ abandonProbeAfterMs: ABANDON_UNANSWERED_BRIDGE_PROBE_AFTER_MS,
+ maxCauseChars: MAX_PROBE_FAILURE_CAUSE_CHARS,
+ });
+}
+
+export async function waitForEveryWindowToPushItsThemeSource(
+ app: ElectronApplication,
+ pushedBy: ReadonlySet<number>,
+): Promise<void> {
+ await expect(async () => {
+ const windows = await probeLiveWindows(app);
+ const couldOwe = windowsStillOwingAThemeSourcePush(windows, NO_WINDOW_HAS_PUSHED);
+ expect(couldOwe.length).toBeGreaterThan(0);
+ expect(windowsStillOwingAThemeSourcePush(windows, pushedBy)).toEqual([]);
+ }).toPass({ timeout: 20_000 });
+}
diff --git a/packages/desktop/tests/smoke/_helpers/theme-source-pushes.type-tests.ts b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.type-tests.ts
new file mode 100644
index 000000000..ed21985db
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/theme-source-pushes.type-tests.ts
@@ -0,0 +1,75 @@
+import type { ThemeSourcePushDebt, ThemeSourceWindowProbe } from './theme-source-pushes.ts';
+
+const _answeredProbeCarriesNoCause: ThemeSourceWindowProbe = {
+ id: 1,
+ url: 'file:///app/index.html#/doc',
+ bridge: 'present',
+ loading: false,
+};
+void _answeredProbeCarriesNoCause;
+
+// @ts-expect-error -- a bridge that answered has no failure to describe; a cause on 'present' is stale text outliving the outcome it names.
+const _presentWithCause: ThemeSourceWindowProbe = {
+ id: 2,
+ url: 'file:///app/index.html#/doc',
+ bridge: 'present',
+ loading: false,
+ cause: 'Render frame was disposed',
+};
+void _presentWithCause;
+
+// @ts-expect-error -- 'absent' is a bridgeless window, not a failed probe; nothing failed for a cause to quote.
+const _absentWithCause: ThemeSourceWindowProbe = {
+ id: 3,
+ url: 'http://localhost:3030/',
+ bridge: 'absent',
+ loading: false,
+ cause: 'bridge probe went unanswered for 2000ms',
+};
+void _absentWithCause;
+
+// @ts-expect-error -- a rejected probe must quote what rejected it; the .catch arm always supplies one.
+const _rejectedWithoutCause: ThemeSourceWindowProbe = {
+ id: 4,
+ url: 'file:///app/index.html#/stalled',
+ bridge: 'probe-rejected',
+ loading: false,
+};
+void _rejectedWithoutCause;
+
+// @ts-expect-error -- an unanswered probe must name the bound it waited on; the abandon timer always supplies one.
+const _unansweredWithoutCause: ThemeSourceWindowProbe = {
+ id: 5,
+ url: 'file:///app/index.html#/silent',
+ bridge: 'probe-unanswered',
+ loading: false,
+};
+void _unansweredWithoutCause;
+
+const _builtElsewhere = {
+ id: 6,
+ url: 'file:///app/index.html#/doc',
+ bridge: 'present' as const,
+ loading: false,
+ cause: 'stale error text',
+};
+// @ts-expect-error -- the pairing must hold through a widened variable, where excess-property checking does not fire; `cause?: never` is what rejects it.
+const _widenedProbe: ThemeSourceWindowProbe = _builtElsewhere;
+void _widenedProbe;
+
+// @ts-expect-error -- 'owes' means the bridge answered and simply has not pushed yet; there is no failure to quote.
+const _owesWithCause: ThemeSourcePushDebt = {
+ id: 7,
+ url: 'file:///app/index.html#/doc',
+ reason: 'owes',
+ cause: 'Render frame was disposed',
+};
+void _owesWithCause;
+
+const _loadingMayCarryARejectionCause: ThemeSourcePushDebt = {
+ id: 8,
+ url: 'file:///app/index.html#/booting',
+ reason: 'loading',
+ cause: 'Render frame was disposed',
+};
+void _loadingMayCarryARejectionCause;
diff --git a/packages/desktop/tests/smoke/theme-sync.e2e.ts b/packages/desktop/tests/smoke/theme-sync.e2e.ts
index 82a7ec1d8..cb5effe36 100644
--- a/packages/desktop/tests/smoke/theme-sync.e2e.ts
+++ b/packages/desktop/tests/smoke/theme-sync.e2e.ts
@@ -7,6 +7,10 @@ import { _electron as electron } from '@playwright/test';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { homeEnv, userDataDirFor } from './_helpers/platform-gate';
import { expect, test } from './_helpers/smoke-test';
+import {
+ observeThemeSourcePushes,
+ waitForEveryWindowToPushItsThemeSource,
+} from './_helpers/theme-source-pushes';
const TARGET = resolveDesktopTarget();
@@ -243,6 +247,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {
}),
);
captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });
+ const pushedBy = observeThemeSourcePushes(app);
await app.firstWindow({ timeout: 15_000 });
const deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir)}&doc=${encodeURIComponent(docName)}`;
@@ -312,6 +317,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {
}
}).toPass({ timeout: 2_000 });
+ await waitForEveryWindowToPushItsThemeSource(app, pushedBy);
await editorPage.evaluate(async () => {
await window.okDesktop?.setThemeSource?.('light');
});