Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/desktop/src/app/DesktopClerk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ vi.mock("@clerk/electron/storage", () => ({

import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
Expand Down Expand Up @@ -52,6 +53,7 @@ const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
Path.layer,
),
),
);
Expand Down Expand Up @@ -173,7 +175,7 @@ describe("DesktopClerk", () => {

assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
assert.deepEqual(registeredEvents, ["second-instance"]);
assert.deepEqual(registeredEvents, ["browser-window-created", "second-instance"]);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Expand Down
71 changes: 70 additions & 1 deletion apps/desktop/src/app/DesktopClerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@ import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";

import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import * as IpcChannels from "../ipc/channels.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
import { readThemeFile, themeFilePathFromArguments } from "./DesktopThemeFileCommand.ts";

declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;

Expand Down Expand Up @@ -72,6 +78,8 @@ export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHos
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);

const { logInfo, logWarning } = makeComponentLogger("desktop-theme-file-command");

export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
return createClerkBridge({
storage: storage({ path: stateDir }),
Expand All @@ -86,6 +94,8 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const electronApp = yield* ElectronApp.ElectronApp;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;

// Electron scopes the single-instance lock to the userData directory and
// creates that directory when the lock is acquired. The SDK bridge takes
Expand Down Expand Up @@ -124,6 +134,32 @@ export const make = Effect.gen(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
const pendingThemePaths: string[] = [];

const readRequestedTheme = (filePath: string) =>
readThemeFile(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.catchCause((cause) =>
logWarning("failed to read requested theme file", { filePath, cause }).pipe(
Effect.as(null),
),
),
);

const sendThemePath = (filePath: string) =>
Effect.gen(function* () {
const file = yield* readRequestedTheme(filePath);
if (file === null) return;
yield* logInfo("applying requested theme file", {
fileName: file.name,
fileSize: file.size,
});
yield* electronWindow.sendAll(IpcChannels.APPLY_THEME_FILE_CHANNEL, file);
});

const initialThemePath = themeFilePathFromArguments(process.argv);
if (initialThemePath) pendingThemePaths.push(initialThemePath);

// The SDK bridge holds Electron's single-instance lock (acquired at
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
Expand All @@ -135,9 +171,42 @@ export const make = Effect.gen(function* () {
return yield* Effect.interrupt;
}

yield* electronApp.on("second-instance", () => {
yield* electronApp.on(
"browser-window-created",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High app/DesktopClerk.ts:175

A --theme-file request during WSL cold boot is dropped instead of being applied to the real main window. currentMainOrFirst returns the connecting splash, so sendThemePath sends the file to that window, and the browser-window-created handler then drains pending paths when the splash finishes loading. Check the actual main window before sending or draining, and keep the path queued until it exists.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/desktop/src/app/DesktopClerk.ts around line 175:

A `--theme-file` request during WSL cold boot is dropped instead of being applied to the real main window. `currentMainOrFirst` returns the connecting splash, so `sendThemePath` sends the file to that window, and the `browser-window-created` handler then drains pending paths when the splash finishes loading. Check the actual main window before sending or draining, and keep the path queued until it exists.

(_event: Electron.Event, window: Electron.BrowserWindow) => {
window.webContents.once("did-finish-load", () => {
const paths = pendingThemePaths.splice(0);
for (const filePath of paths) {
void runPromise(
Effect.gen(function* () {
const file = yield* readRequestedTheme(filePath);
if (file !== null && !window.isDestroyed()) {
yield* logInfo("applying requested startup theme file", {
fileName: file.name,
fileSize: file.size,
});
window.webContents.send(IpcChannels.APPLY_THEME_FILE_CHANNEL, file);
}
}),
);
}
});
},
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Splash drains startup themes

High Severity

browser-window-created attaches to every BrowserWindow, including the WSL connecting splash. That splash’s did-finish-load empties pendingThemePaths and sends the theme to a window with no preload or onThemeFileApply listener, so the cold-start --theme-file is lost before the real main window loads. The same unfiltered currentMainOrFirst check on second-instance treats the splash as ready and uses sendAll instead of queuing for the main renderer.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 51668e9. Configure here.


yield* electronApp.on("second-instance", (_event: unknown, commandLine: unknown) => {
void runPromise(
Effect.gen(function* () {
if (Array.isArray(commandLine)) {
const themePath = themeFilePathFromArguments(
commandLine.filter((argument): argument is string => typeof argument === "string"),
);
if (themePath) {
const currentWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isNone(currentWindow)) pendingThemePaths.push(themePath);
else yield* sendThemePath(themePath);
}
}
const mainWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(mainWindow)) {
yield* electronWindow.reveal(mainWindow.value);
Expand Down
25 changes: 25 additions & 0 deletions apps/desktop/src/app/DesktopThemeFileCommand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { assert, describe, it } from "@effect/vitest";

import { themeFilePathFromArguments } from "./DesktopThemeFileCommand.ts";

describe("DesktopThemeFileCommand", () => {
it("reads a separated theme file argument", () => {
assert.equal(
themeFilePathFromArguments(["t3code", "--theme-file", "/tmp/omarchy theme.json"]),
"/tmp/omarchy theme.json",
);
});

it("reads an inline theme file argument", () => {
assert.equal(
themeFilePathFromArguments(["t3code", "--theme-file=/tmp/theme.json"]),
"/tmp/theme.json",
);
});

it("ignores missing and empty values", () => {
assert.isNull(themeFilePathFromArguments(["t3code", "--theme-file"]));
assert.isNull(themeFilePathFromArguments(["t3code", "--theme-file="]));
assert.isNull(themeFilePathFromArguments(["t3code", "--theme-file", "--inspect"]));
});
});
33 changes: 33 additions & 0 deletions apps/desktop/src/app/DesktopThemeFileCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { PickedThemeFile } from "@t3tools/contracts";
import * as FileSystem from "effect/FileSystem";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";

export const THEME_FILE_ARGUMENT = "--theme-file";
export const THEME_FILE_MAX_BYTES = 256 * 1024;

export function themeFilePathFromArguments(args: readonly string[]): string | null {
for (let index = 0; index < args.length; index += 1) {
const argument = args[index]!;
if (argument === THEME_FILE_ARGUMENT) {
const value = args[index + 1];
return value && !value.startsWith("--") ? value : null;
}
if (argument.startsWith(`${THEME_FILE_ARGUMENT}=`)) {
const value = argument.slice(THEME_FILE_ARGUMENT.length + 1);
return value.length > 0 ? value : null;
}
}
return null;
}

export const readThemeFile = Effect.fn("desktop.themeFileCommand.read")(function* (
filePath: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const info = yield* fileSystem.stat(filePath);
const size = Number(info.size);
const text = size > THEME_FILE_MAX_BYTES ? "" : yield* fileSystem.readFileString(filePath);
return { name: path.basename(filePath), size, text } satisfies PickedThemeFile;
Comment on lines +31 to +32

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High app/DesktopThemeFileCommand.ts:31

When the file grows or is replaced after stat, readThemeFile returns arbitrarily large text while reporting the stale, at-most-256 KiB size, forwarding oversized contents to the renderer. The unbounded readFileString must be bounded or its actual bytes read must be checked before returning.

-  const text = size > THEME_FILE_MAX_BYTES ? "" : yield* fileSystem.readFileString(filePath);
-  return { name: path.basename(filePath), size, text } satisfies PickedThemeFile;
+  const text = size > THEME_FILE_MAX_BYTES ? "" : yield* fileSystem.readFileString(filePath);
+  const actualSize = size > THEME_FILE_MAX_BYTES ? size : new TextEncoder().encode(text).byteLength;
+  return {
+    name: path.basename(filePath),
+    size: actualSize,
+    text: actualSize > THEME_FILE_MAX_BYTES ? "" : text
+  } satisfies PickedThemeFile;
🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/desktop/src/app/DesktopThemeFileCommand.ts around lines 31-32:

When the file grows or is replaced after `stat`, `readThemeFile` returns arbitrarily large `text` while reporting the stale, at-most-256 KiB `size`, forwarding oversized contents to the renderer. The unbounded `readFileString` must be bounded or its actual bytes read must be checked before returning.

});
1 change: 1 addition & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const APPLY_THEME_FILE_CHANNEL = "desktop:apply-theme-file";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
Expand Down
30 changes: 30 additions & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
PickedThemeFile,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
Expand All @@ -11,6 +12,27 @@ import * as IpcChannels from "./ipc/channels.ts";

exposeClerkBridge({ passkeys: true });

let pendingThemeFile: PickedThemeFile | null = null;
const themeFileListeners = new Set<(file: PickedThemeFile) => void>();

ipcRenderer.on(IpcChannels.APPLY_THEME_FILE_CHANNEL, (_event, file: unknown) => {
if (typeof file !== "object" || file === null) return;
const candidate = file as Partial<PickedThemeFile>;
if (
typeof candidate.name !== "string" ||
typeof candidate.size !== "number" ||
typeof candidate.text !== "string"
) {
return;
}
const picked = candidate as PickedThemeFile;
if (themeFileListeners.size === 0) {
pendingThemeFile = picked;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High src/preload.ts:30

Multiple APPLY_THEME_FILE_CHANNEL events received before onThemeFileApply registers are collapsed to the last PickedThemeFile, so earlier startup theme requests are silently dropped. pendingThemeFile is a single slot; replace it with a queue and drain every queued payload when the first listener registers.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/desktop/src/preload.ts around line 30:

Multiple `APPLY_THEME_FILE_CHANNEL` events received before `onThemeFileApply` registers are collapsed to the last `PickedThemeFile`, so earlier startup theme requests are silently dropped. `pendingThemeFile` is a single slot; replace it with a queue and drain every queued payload when the first listener registers.

return;
}
for (const listener of themeFileListeners) listener(picked);
});

function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
Expand Down Expand Up @@ -104,6 +126,14 @@ contextBridge.exposeInMainWorld("desktopBridge", {
pickProjectFavicon: (initialPath) =>
ipcRenderer.invoke(IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, initialPath),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
onThemeFileApply: (listener) => {
themeFileListeners.add(listener);
if (pendingThemeFile) {
listener(pendingThemeFile);
pendingThemeFile = null;
}
return () => themeFileListeners.delete(listener);
},
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/AppRoot.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { RouterProvider } from "@tanstack/react-router";

import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { DesktopThemeFileCommands } from "./components/DesktopThemeFileCommands";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { QuitHoldOverlay } from "./components/QuitHoldOverlay";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
Expand All @@ -15,6 +16,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
return (
<AppAtomRegistryProvider>
<RouterProvider router={router} />
<DesktopThemeFileCommands />
<PreviewAutomationHosts />
<ElectronBrowserHost />
<QuitHoldOverlay />
Expand Down
56 changes: 56 additions & 0 deletions apps/web/src/components/DesktopThemeFileCommands.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { assert } from "@effect/vitest";
import { afterEach, beforeEach, describe, it, vi } from "vite-plus/test";

import { getCustomThemes, invalidateCustomThemes } from "../themePalette";
import { importDesktopThemeFile } from "./DesktopThemeFileCommands";

const vscodeTheme = (background: string) => ({
name: "Omarchy Current",
type: "dark",
colors: {
"editor.background": background,
"editor.foreground": "#cacccc",
},
});

describe("DesktopThemeFileCommands", () => {
beforeEach(() => {
const stored = new Map<string, string>();
vi.stubGlobal("window", {
localStorage: {
clear: () => stored.clear(),
getItem: (key: string) => stored.get(key) ?? null,
removeItem: (key: string) => stored.delete(key),
setItem: (key: string, value: string) => stored.set(key, value),
},
});
invalidateCustomThemes();
});

afterEach(() => {
invalidateCustomThemes();
vi.unstubAllGlobals();
});

it("installs and updates a requested VS Code theme", () => {
const firstId = importDesktopThemeFile({
name: "vscode.json",
size: 100,
text: JSON.stringify(vscodeTheme("#101315")),
});

assert.equal(getCustomThemes().length, 1);
assert.equal(getCustomThemes()[0]?.id, firstId);
const firstCanvas = getCustomThemes()[0]?.colors.canvas;

const secondId = importDesktopThemeFile({
name: "vscode.json",
size: 100,
text: JSON.stringify(vscodeTheme("#202426")),
});

assert.equal(secondId, firstId);
assert.equal(getCustomThemes().length, 1);
assert.notEqual(getCustomThemes()[0]?.colors.canvas, firstCanvas);
});
});
42 changes: 42 additions & 0 deletions apps/web/src/components/DesktopThemeFileCommands.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { PickedThemeFile } from "@t3tools/contracts";
import { useEffect } from "react";

import { useTheme } from "../hooks/useTheme";
import {
getCustomThemes,
installCustomTheme,
parseThemeFile,
updateCustomTheme,
} from "../themePalette";
import { isVsCodeThemeFile, parseVsCodeThemeFile } from "../vscodeThemeImport";

export function importDesktopThemeFile(file: PickedThemeFile): string {
if (!file.text) throw new Error(`Could not read theme file "${file.name}".`);
const value: unknown = JSON.parse(file.text);
const theme = isVsCodeThemeFile(value) ? parseVsCodeThemeFile(value) : parseThemeFile(value);
if (getCustomThemes().some((installed) => installed.id === theme.id)) {
updateCustomTheme(theme);
} else {
installCustomTheme(theme);
}
return theme.id;
}

export function DesktopThemeFileCommands() {
const { setTheme } = useTheme();

useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onThemeFileApply) return;
return bridge.onThemeFileApply((file) => {
try {
const themeId = importDesktopThemeFile(file);
if (!setTheme(themeId)) throw new Error(`Could not activate theme "${themeId}".`);
} catch (cause) {
console.error("Failed to apply desktop theme file.", { file: file.name, cause });
}
});
}, [setTheme]);
Comment on lines +26 to +39

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the requested theme id is already installed and active, this update never reaches the DOM: updateCustomTheme only rewrites storage plus the custom-theme cache, and setTheme(themeId) -> applyTheme early-returns because lastAppliedTheme already matches the same theme id, appearance mode and halves signature (hooks/useTheme.ts L291-300). setTheme still returns true, so no error is logged and the window keeps the stale palette until a reload. That is exactly the documented Omarchy hook loop (docs/user/themes.md: repeated --theme-file runs with the same theme name/id), so the second and later theme switches silently do nothing visible.

The existing update path handles this by re-applying after an update (components/settings/ThemeSettings.tsx L884-887 calls refreshTheme() on updated); consider following the same contract here, and extending DesktopThemeFileCommands.test.ts to cover the re-apply of an already-active theme.

Suggested change
const { setTheme } = useTheme();
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onThemeFileApply) return;
return bridge.onThemeFileApply((file) => {
try {
const themeId = importDesktopThemeFile(file);
if (!setTheme(themeId)) throw new Error(`Could not activate theme "${themeId}".`);
} catch (cause) {
console.error("Failed to apply desktop theme file.", { file: file.name, cause });
}
});
}, [setTheme]);
const { refreshTheme, setTheme } = useTheme();
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onThemeFileApply) return;
return bridge.onThemeFileApply((file) => {
try {
const themeId = importDesktopThemeFile(file);
if (!setTheme(themeId)) throw new Error(`Could not activate theme "${themeId}".`);
// applyTheme dedupes by theme id, so an updated palette for the
// already-active theme needs an explicit re-apply.
refreshTheme();
} catch (cause) {
console.error("Failed to apply desktop theme file.", { file: file.name, cause });
}
});
}, [refreshTheme, setTheme]);

Posted via Macroscope — UI Consistency


return null;
}
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- [Organizing threads](./user/thread-sidebar.md)
- [Review usage](./user/usage.md)
- [Customize a project icon](./user/project-settings.md)
- [Themes and desktop automation](./user/themes.md)
- [Mobile appearance](./user/mobile-appearance.md)
- [Remote access](./user/remote-access.md)
- [Keeping app and server in sync](./user/updating.md)
Expand Down
Loading
Loading