Skip to content

The agent that grows with you

fix(desktop): load local skin before gateway connects

Mohamad Kansoca6782850432
diff --git a/apps/desktop/electron/local-skin.test.ts b/apps/desktop/electron/local-skin.test.ts
new file mode 100644
index 00000000000..dd03de0a103
--- /dev/null
+++ b/apps/desktop/electron/local-skin.test.ts
@@ -0,0 +1,101 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { test } from 'vitest'
+
+import { localSkinHome, readLocalDisplaySkin, readLocalSkinPayload } from './local-skin'
+
+function makeHome() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-local-skin-'))
+}
+
+test('reads a configured custom skin without a live gateway', () => {
+ const home = makeHome()
+
+ try {
+ fs.mkdirSync(path.join(home, 'skins'))
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'display:\n skin: neon\n')
+ fs.writeFileSync(
+ path.join(home, 'skins', 'neon.yaml'),
+ 'name: neon\ndescription: neon after dark\ncolors:\n background: "#101020"\n ui_text: "#eeeeee"\n ui_accent: "#ff33aa"\n'
+ )
+
+ const skin = readLocalDisplaySkin(home, null)
+
+ assert.equal(skin?.name, 'neon')
+ assert.equal(skin?.description, 'neon after dark')
+ assert.equal(skin?.colors?.background, '#101020')
+ assert.equal(skin?.colors?.ui_text, '#eeeeee')
+ assert.equal(skin?.colors?.ui_accent, '#ff33aa')
+ assert.equal(skin?.colors?.status_bar_bg, '#1a1a2e')
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('reads the active named profile instead of the root home', () => {
+ const home = makeHome()
+ const profileHome = localSkinHome(home, 'research')
+
+ try {
+ fs.mkdirSync(path.join(home, 'skins'))
+ fs.mkdirSync(path.join(profileHome, 'skins'), { recursive: true })
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'display:\n skin: root\n')
+ fs.writeFileSync(path.join(profileHome, 'config.yaml'), 'display:\n skin: profile\n')
+ fs.writeFileSync(path.join(profileHome, 'skins', 'profile.yaml'), 'name: profile\ncolors:\n ui_accent: "#00ffff"\n')
+
+ const skin = readLocalDisplaySkin(home, 'research')
+
+ assert.equal(skin?.name, 'profile')
+ assert.equal(skin?.colors?.ui_accent, '#00ffff')
+ assert.equal(skin?.colors?.status_bar_bg, '#1a1a2e')
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('uses a routed session or hud profile before any gateway can connect', () => {
+ const home = makeHome()
+ const profileHome = localSkinHome(home, 'research')
+
+ try {
+ fs.mkdirSync(path.join(profileHome, 'skins'), { recursive: true })
+ fs.writeFileSync(path.join(profileHome, 'config.yaml'), 'display:\n skin: research\n')
+ fs.writeFileSync(path.join(profileHome, 'skins', 'research.yaml'), 'name: research\ncolors:\n ui_accent: "#00ffff"\n')
+
+ const payload = readLocalSkinPayload(home, 'research', 'default')
+
+ assert.equal(payload?.profile, 'research')
+ assert.equal(payload?.skin.name, 'research')
+ assert.equal(payload?.skin.colors?.ui_accent, '#00ffff')
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('returns built-in names even though they have no local skin file', () => {
+ const home = makeHome()
+
+ try {
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'display: { skin: mono }\n')
+ assert.deepEqual(readLocalDisplaySkin(home, null), { name: 'mono' })
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('fails closed for malformed config and traversal-like skin names', () => {
+ const home = makeHome()
+
+ try {
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'display: [not, a, mapping]\n')
+ assert.equal(readLocalDisplaySkin(home, null), null)
+
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'display:\n skin: ../../config\n')
+ assert.equal(readLocalDisplaySkin(home, null), null)
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/local-skin.ts b/apps/desktop/electron/local-skin.ts
new file mode 100644
index 00000000000..3883c42929e
--- /dev/null
+++ b/apps/desktop/electron/local-skin.ts
@@ -0,0 +1,192 @@
+// Read the local display skin without asking the active gateway. This is used
+// at renderer boot so a Desktop window can still paint its configured local
+// skin when its primary connection is a remote gateway that is offline.
+import fs from 'node:fs'
+import path from 'node:path'
+
+import type { HermesSkin, SkinColors } from '@hermes/shared/skin'
+import { parse } from 'yaml'
+
+const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/
+const SKIN_FILE_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/
+const MAX_CONFIG_BYTES = 1_000_000
+const MAX_SKIN_BYTES = 256_000
+
+// Custom skin files are overlays in hermes_cli/skin_engine.py. Keep this in
+// step with its default `colors` block so a partial local skin paints exactly
+// like the resolved gateway payload when Desktop starts offline.
+const DEFAULT_SKIN_COLORS: SkinColors = {
+ banner_border: '#CD7F32',
+ banner_title: '#FFD700',
+ banner_accent: '#FFBF00',
+ banner_dim: '#B8860B',
+ banner_text: '#FFF8DC',
+ ui_accent: '#FFBF00',
+ ui_label: '#DAA520',
+ ui_ok: '#4caf50',
+ ui_error: '#ef5350',
+ ui_warn: '#ffa726',
+ prompt: '#FFF8DC',
+ input_rule: '#CD7F32',
+ response_border: '#FFD700',
+ status_bar_bg: '#1a1a2e',
+ status_bar_text: '#C0C0C0',
+ status_bar_strong: '#FFD700',
+ status_bar_dim: '#8A7A4A',
+ status_bar_good: '#8FBC8F',
+ status_bar_warn: '#FFD700',
+ status_bar_bad: '#FF8C00',
+ status_bar_critical: '#FF6B6B',
+ session_label: '#DAA520',
+ session_border: '#8B8682',
+ completion_menu_bg: '#1a1a2e',
+ completion_menu_current_bg: '#333355',
+ selection_bg: '#3a3a55',
+ shell_dollar: '#4dabf7',
+ voice_status_bg: '#1a1a2e'
+}
+
+type UnknownRecord = Record<string, unknown>
+
+const isRecord = (value: unknown): value is UnknownRecord =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+
+const readText = (filePath: string, maxBytes: number): string | null => {
+ try {
+ const stat = fs.statSync(filePath)
+
+ if (!stat.isFile() || stat.size > maxBytes) {
+ return null
+ }
+
+ return fs.readFileSync(filePath, 'utf8')
+ } catch {
+ return null
+ }
+}
+
+const parseRecord = (source: string | null): UnknownRecord | null => {
+ if (!source) {
+ return null
+ }
+
+ try {
+ const parsed = parse(source, { maxAliasCount: 20 })
+
+ return isRecord(parsed) ? parsed : null
+ } catch {
+ return null
+ }
+}
+
+const text = (value: unknown): string | null => {
+ if (typeof value !== 'string') {
+ return null
+ }
+
+ const trimmed = value.trim()
+
+ return trimmed && trimmed.length <= 128 ? trimmed : null
+}
+
+const stringMap = (value: unknown): SkinColors | undefined => {
+ if (!isRecord(value)) {
+ return undefined
+ }
+
+ const entries: SkinColors = {}
+
+ for (const [key, entry] of Object.entries(value)) {
+ if (key.length <= 128 && typeof entry === 'string' && entry.length <= 1_024) {
+ entries[key] = entry
+ }
+ }
+
+ return entries
+}
+
+/** The profile key mirrors `hermes --profile <name>` and is safe for a path. */
+export function localSkinProfileKey(profile: null | string | undefined): string {
+ const name = typeof profile === 'string' ? profile.trim() : ''
+
+ return name && name !== 'default' && PROFILE_NAME_RE.test(name) ? name : 'default'
+}
+
+/** The profile home mirrors `hermes --profile <name>`: `<root>/profiles/<name>`. */
+export function localSkinHome(hermesHome: string, profile: null | string): string {
+ const name = localSkinProfileKey(profile)
+
+ return name === 'default' ? hermesHome : path.join(hermesHome, 'profiles', name)
+}
+
+function skinFromFile(filePath: string, configuredName: string): HermesSkin | null {
+ const parsed = parseRecord(readText(filePath, MAX_SKIN_BYTES))
+
+ if (!parsed) {
+ return null
+ }
+
+ const name = text(parsed.name) ?? configuredName
+ const description = text(parsed.description)
+ const colors = stringMap(parsed.colors)
+ const darkColors = stringMap(parsed.dark_colors)
+ const lightColors = stringMap(parsed.light_colors)
+
+ return {
+ name,
+ ...(description ? { description } : {}),
+ // The backend emits this skin after merging its base palette. Do the same
+ // here because custom YAMLs are allowed to only override one token.
+ colors: { ...DEFAULT_SKIN_COLORS, ...colors },
+ ...(darkColors ? { dark_colors: darkColors } : {}),
+ ...(lightColors ? { light_colors: lightColors } : {})
+ }
+}
+
+/**
+ * Return the configured local skin as a small renderer-safe payload. The
+ * renderer never gets arbitrary file paths or config contents, and a broken
+ * local config simply leaves the normal desktop theme in place.
+ */
+export function readLocalDisplaySkin(hermesHome: string, profile: null | string): HermesSkin | null {
+ const home = localSkinHome(hermesHome, profile)
+ const config = parseRecord(readText(path.join(home, 'config.yaml'), MAX_CONFIG_BYTES))
+ const display = config && isRecord(config.display) ? config.display : null
+ const configuredName = text(display?.skin)
+
+ if (!configuredName || !SKIN_FILE_NAME_RE.test(configuredName)) {
+ return null
+ }
+
+ // Built-ins do not have a local YAML file. The renderer already owns those
+ // palettes, so the name alone is enough for the boot fallback.
+ const skinsRoot = path.join(home, 'skins')
+ const filePath = path.join(skinsRoot, `${configuredName}.yaml`)
+
+ try {
+ const realRoot = fs.realpathSync(skinsRoot)
+ const realFile = fs.realpathSync(filePath)
+
+ // Do not turn a symlink in skins/ into a generic file-reading bridge for
+ // renderer code. Custom skins are direct children of the local skins root.
+ if (path.dirname(realFile) !== realRoot) {
+ return { name: configuredName }
+ }
+ } catch {
+ return { name: configuredName }
+ }
+
+ return skinFromFile(filePath, configuredName) ?? { name: configuredName }
+}
+
+/** The one small payload preload needs for a window's first theme paint. */
+export function readLocalSkinPayload(
+ hermesHome: string,
+ routedProfile: null | string | undefined,
+ fallbackProfile: null | string | undefined
+): { profile: string; skin: HermesSkin } | null {
+ const profile = localSkinProfileKey(routedProfile ?? fallbackProfile)
+ const skin = readLocalDisplaySkin(hermesHome, profile)
+
+ return skin ? { profile, skin } : null
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 78f4966791c..6749b8bdd08 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -286,6 +286,7 @@ import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle
import { CHROMIUM_LOG_FILENAME, enableLinuxCrashDiagnostics, linuxCrashDiagnostics } from './linux-crash-diagnostics'
import { notifyLauncherWindowRevealed } from './linux-launcher-ready'
import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
+import { localSkinProfileKey, readLocalSkinPayload } from './local-skin'
import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation'
import { ensureMainWindow } from './main-window-lifecycle'
import {
@@ -14006,6 +14007,13 @@ function spawnSecondaryWindow({
streamThrottle.register(win)
wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat'))
attachRendererConsoleCapture(win, 'session-window', rememberLog)
+ // The preload asks for its skin before it can publish its own active route.
+ // Register the profile carried in the window URL before loading the renderer.
+ recordWindowConnectionRoute(win.webContents, {
+ connectionId: null,
+ profile: localSkinProfileKey(profile ?? primaryProfileKey()),
+ registryScoped: false
+ })
// Renderer lifecycle diagnostics + recovery (#81290): a dead session-window
// renderer used to log nothing and stay black; now it logs with its window
@@ -14906,6 +14914,13 @@ function spawnHudWindow(sessionId, profile) {
// Log-only lifecycle (#81290): the HUD is a compact auxiliary surface the
// user can re-toggle; a dead renderer should be diagnosable, not resurrected.
installWindowRendererLifecycle(win, { kind: 'hud', callbacks: { log: rememberLog } })
+ // Same timing as a session window: the profile query is known now, while the
+ // renderer cannot announce its route until after preload has already run.
+ recordWindowConnectionRoute(win.webContents, {
+ connectionId: null,
+ profile: localSkinProfileKey(profile ?? primaryProfileKey()),
+ registryScoped: false
+ })
loadWindowUrl(win, hudUrl(sessionId, profile), 'HUD')
return win
@@ -18181,6 +18196,19 @@ ipcMain.on('hermes:logs:renderer-error', (_event, report) => {
flushDesktopLogBufferSync()
})
+// The preload reads this small, sanitized payload synchronously so the renderer
+// can register the local skin before its first theme paint. It stays independent
+// of the selected gateway, which can be an offline remote primary.
+ipcMain.on('hermes:skin:local', event => {
+ // The window route is more specific than the global next-launch preference:
+ // a peer can be booting another profile while that preference changes.
+ event.returnValue = readLocalSkinPayload(
+ HERMES_HOME,
+ windowConnectionRoutes.get(event.sender.id)?.profile,
+ primaryProfileKey()
+ )
+})
+
// Local filesystem + plugin-root IPC (readDir/reveal/rename/trash/…) — see fs-ipc.ts.
registerFsIpc({
hermesHome: HERMES_HOME,
diff --git a/apps/desktop/electron/preload-local-skin.test.ts b/apps/desktop/electron/preload-local-skin.test.ts
new file mode 100644
index 00000000000..695a484b580
--- /dev/null
+++ b/apps/desktop/electron/preload-local-skin.test.ts
@@ -0,0 +1,30 @@
+import assert from 'node:assert/strict'
+
+import { test, vi } from 'vitest'
+
+const skin = {
+ profile: 'default',
+ skin: { name: 'neon', colors: { background: '#101020', ui_accent: '#ff33aa', banner_text: '#eeeeee' } }
+}
+
+const electron = vi.hoisted(() => ({
+ contextBridge: { exposeInMainWorld: vi.fn() },
+ ipcRenderer: {
+ invoke: vi.fn(async () => ({ ok: true })),
+ on: vi.fn(),
+ removeListener: vi.fn(),
+ sendSync: vi.fn((channel: string) => (channel === 'hermes:skin:local' ? skin : {}))
+ },
+ webFrame: {},
+ webUtils: {}
+}))
+
+vi.mock('electron', () => electron)
+
+test('the preload carries the local skin across before the renderer starts', async () => {
+ await import('./preload')
+ const [, bridge] = electron.contextBridge.exposeInMainWorld.mock.calls[0]
+
+ assert.deepEqual(bridge.localSkin, skin)
+ assert.equal(electron.ipcRenderer.sendSync.mock.calls.some(([channel]) => channel === 'hermes:skin:local'), true)
+})
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index f6f772acf41..54599422392 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -15,6 +15,10 @@ const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support')
const hudWindowing = ipcRenderer.sendSync('hermes:hud:windowing')
const hudNativeDrag = hudWindowing?.nativeDrag === true
const launchFlags = ipcRenderer.sendSync('hermes:launch-flags')
+// Local, sanitized skin payload for the first renderer theme paint. This does
+// not wait on `gateway.ready`, so an unreachable remote primary cannot force
+// the built-in palette over the skin configured on this machine.
+const localSkin = ipcRenderer.sendSync('hermes:skin:local')
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
@@ -26,6 +30,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
// (HERMES_GUEST_ONBOARDING=1 or --guest-onboarding). Read-only; the same
// decision is stamped onto every backend the app spawns.
guestOnboardingEnabled: launchFlags?.guestOnboarding === true,
+ localSkin: localSkin && typeof localSkin === 'object' ? localSkin : null,
// Launch-flag fact: skip the first-run film (HERMES_SKIP_INTRO=1 or
// --skip-intro). Rehearsal aid for the guided chat behind it.
skipIntro: launchFlags?.skipIntro === true,
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 46fd736c05f..d117ae4e20b 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -153,7 +153,8 @@
"unist-util-visit-parents": "6.0.2",
"use-stick-to-bottom": "1.1.6",
"vfile": "6.0.3",
- "web-haptics": "0.0.6"
+ "web-haptics": "0.0.6",
+ "yaml": "2.8.1"
},
"optionalDependencies": {
"get-windows": "9.3.0"
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index a10fe6e89b3..b331b634172 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1,4 +1,5 @@
import type { GatewayWsUrlResult } from '@hermes/shared'
+import type { HermesSkin } from '@hermes/shared/skin'
import type { TranslucencyState } from '@hermes/shared/translucency'
import type { ScreenshotApi } from '../electron/command-screenshot-types'
@@ -375,6 +376,8 @@ declare global {
* (HERMES_GUEST_ONBOARDING=1 or --guest-onboarding). Read-only fact the
* main process also stamps onto every backend it spawns. */
guestOnboardingEnabled?: boolean
+ /** Sanitized local `display.skin`, available before any gateway connects. */
+ localSkin?: { profile: string; skin: HermesSkin } | null
/** Launch flag: skip the first-run film (HERMES_SKIP_INTRO=1 or
* --skip-intro) so a fresh HERMES_HOME lands on the guided chat. */
skipIntro?: boolean
diff --git a/apps/desktop/src/themes/backend-sync.ts b/apps/desktop/src/themes/backend-sync.ts
index e12b2bcb7fd..cc00d6cdcd4 100644
--- a/apps/desktop/src/themes/backend-sync.ts
+++ b/apps/desktop/src/themes/backend-sync.ts
@@ -31,6 +31,14 @@ import { type DesktopTheme, isValidTheme } from './types'
// and the app silently painted the default until the next `skin.changed`.
const BACKEND_THEMES_KEY = 'hermes-desktop-backend-themes-v1'
+// Electron reads the active local `display.skin` before it creates the
+// renderer. Seed it alongside the existing cache so an unreachable primary
+// gateway cannot leave a first-time custom skin unknown to the theme registry.
+const localSkinPayload = typeof window === 'undefined' ? null : window.hermesDesktop?.localSkin ?? null
+const localSkin = localSkinPayload?.skin ?? null
+export const localDisplaySkinName = (localSkin?.name ?? '').trim() || null
+export const localDisplaySkinProfile = localDisplaySkinName ? (localSkinPayload?.profile ?? '').trim() || 'default' : null
+
const readCached = (): Record<string, DesktopTheme> =>
Object.fromEntries(
Object.entries(readJson<Record<string, unknown>>(BACKEND_THEMES_KEY) ?? {}).filter(
@@ -109,3 +117,10 @@ export function ingestBackendSkin(skin: HermesSkin | undefined | null, { apply }
$pendingSkinApply.set(name)
}
}
+
+// This is a boot fallback, not a remote activation. ThemeProvider uses the
+// name only when the desktop has no saved appearance of its own, while this
+// registers the custom palette early enough for that first paint to resolve.
+if (localSkin) {
+ ingestBackendSkin(localSkin, { apply: false })
+}
diff --git a/apps/desktop/src/themes/context.test.tsx b/apps/desktop/src/themes/context.test.tsx
index 780f9155625..08e70668dec 100644
--- a/apps/desktop/src/themes/context.test.tsx
+++ b/apps/desktop/src/themes/context.test.tsx
@@ -1,5 +1,5 @@
import { act, cleanup, render } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { __resetBackendSkinSync, ingestBackendSkin } from './backend-sync'
import { skinPref, ThemeProvider, useTheme } from './context'
@@ -91,6 +91,78 @@ describe('ThemeProvider ← backend skin sync', () => {
expect(cssVar('--theme-background-seed')).toBe('#000000')
expect(skinPref.resolve('default')).toBe('bloomberg')
})
+
+ it('uses the local bridge skin when a remote gateway has not connected yet', async () => {
+ const previous = Object.getOwnPropertyDescriptor(window, 'hermesDesktop')
+
+ try {
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { localSkin: { profile: 'research', skin: bloomberg('#ff9f0a') } }
+ })
+ vi.resetModules()
+
+ const [{ ThemeProvider: FreshThemeProvider }, freshSync] = await Promise.all([
+ import('./context'),
+ import('./backend-sync')
+ ])
+
+ expect(freshSync.$backendThemes.get().bloomberg?.name).toBe('bloomberg')
+
+ render(
+ <FreshThemeProvider>
+ <div />
+ </FreshThemeProvider>
+ )
+
+ expect(cssVar('--theme-background-seed')).toBe('#000000')
+ } finally {
+ cleanup()
+ window.localStorage.clear()
+
+ if (previous) {
+ Object.defineProperty(window, 'hermesDesktop', previous)
+ } else {
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ }
+
+ vi.resetModules()
+ }
+ })
+
+ it('keeps a saved desktop appearance ahead of the local bridge fallback', async () => {
+ const previous = Object.getOwnPropertyDescriptor(window, 'hermesDesktop')
+
+ try {
+ window.localStorage.setItem('hermes-desktop-theme-v2', 'everforest')
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { localSkin: { profile: 'research', skin: bloomberg('#ff9f0a') } }
+ })
+ vi.resetModules()
+
+ const { ThemeProvider: FreshThemeProvider } = await import('./context')
+
+ render(
+ <FreshThemeProvider>
+ <div />
+ </FreshThemeProvider>
+ )
+
+ expect(window.document.documentElement.dataset.hermesTheme).toBe('everforest')
+ } finally {
+ cleanup()
+ window.localStorage.clear()
+
+ if (previous) {
+ Object.defineProperty(window, 'hermesDesktop', previous)
+ } else {
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ }
+
+ vi.resetModules()
+ }
+ })
})
describe('ThemeProvider highlight preview', () => {
diff --git a/apps/desktop/src/themes/context.tsx b/apps/desktop/src/themes/context.tsx
index 5c65b145cd3..f9f2ed1a651 100644
--- a/apps/desktop/src/themes/context.tsx
+++ b/apps/desktop/src/themes/context.tsx
@@ -17,10 +17,11 @@ import { $registryVersion } from '@/contrib/registry'
import { matchesQuery, useMediaQuery } from '@/hooks/use-media-query'
import { persistString, persistStringRecord, storedString, storedStringRecord } from '@/lib/storage'
import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'
+import { $connection } from '@/store/session'
import { setAppearance } from '@/store/translucency'
import { $accentOverride } from './accent-override'
-import { $backendThemes, $pendingSkinApply } from './backend-sync'
+import { $backendThemes, $pendingSkinApply, localDisplaySkinName, localDisplaySkinProfile } from './backend-sync'
import { $chatFontFamily, resolveChatFontFamily } from './chat-font'
import { harmonize, readableInk } from './color'
import { BUILTIN_THEME_LIST, DEFAULT_SKIN_NAME, DEFAULT_TYPOGRAPHY, nousTheme } from './presets'
@@ -90,17 +91,21 @@ const profilePref = <T extends string>(record: string, legacy: string, normalize
export const skinPref = profilePref(PROFILE_SKINS_KEY, SKIN_KEY, normalizeSkin)
export const modePref = profilePref(PROFILE_MODES_KEY, MODE_KEY, normalizeMode)
+// The bridge's local skin is only a fallback for the profile this window booted
+// into. A desktop-side pick remains the source of truth, and switching to a
+// different profile cannot borrow a skin from this machine's initial profile.
+const readBootProfileKey = () => normalizeProfileKey(storedString(LAST_PROFILE_KEY))
+const BOOT_PROFILE_KEY = typeof window === 'undefined' ? 'default' : localDisplaySkinProfile ?? readBootProfileKey()
+
// Provider state keeps the raw pick so a name nothing resolves YET (a backend
// skin the gateway hasn't seeded on this launch) isn't flattened to the default
// for the rest of the session — it paints as soon as the registry can resolve it.
-const storedSkin = (profile: string): string => skinPref.stored(profile) ?? DEFAULT_SKIN_NAME
+const storedSkin = (profile: string): string =>
+ skinPref.stored(profile) ?? (profile === BOOT_PROFILE_KEY ? localDisplaySkinName ?? DEFAULT_SKIN_NAME : DEFAULT_SKIN_NAME)
/** Everything a peer window could change that this one has to repaint for. */
const APPEARANCE_KEYS = new Set([SKIN_KEY, PROFILE_SKINS_KEY, MODE_KEY, PROFILE_MODES_KEY])
-// Last active profile — lets the boot paint pick its appearance before the
-// gateway reports which profile actually launched.
-const readBootProfileKey = () => normalizeProfileKey(storedString(LAST_PROFILE_KEY))
const rememberActiveProfileKey = (profile: string) => persistString(LAST_PROFILE_KEY, profile)
// ─── Color math (for synthesised light variants of dark-only skins) ────────
@@ -324,10 +329,10 @@ const syncNativeTheme = (pref: ThemeMode, rendered: 'light' | 'dark') =>
// active profile's appearance so a non-default profile relaunch paints its own
// skin + light/dark mode.
if (typeof window !== 'undefined') {
- const profile = readBootProfileKey()
+ const profile = BOOT_PROFILE_KEY
const pref = modePref.resolve(profile)
const resolved = resolveMode(pref)
- const theme = deriveTheme(skinPref.resolve(profile), resolved)
+ const theme = deriveTheme(normalizeSkin(storedSkin(profile)), resolved)
applyTheme(theme, resolved)
syncNativeTheme(pref, renderedModeFor(theme.colors, resolved))
}
@@ -378,7 +383,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
// Skin + mode are assigned per profile; the active profile drives which
// appearance shows. Single-profile users only ever see "default", so their
// behavior is unchanged.
- const profileKey = normalizeProfileKey(useStore($activeGatewayProfile))
+ const activeGatewayProfile = useStore($activeGatewayProfile)
+ const connection = useStore($connection)
+ // Before a gateway descriptor exists, the bridge is the only authoritative
+ // profile for this window. Once one arrives, follow the live route as usual.
+ const profileKey = normalizeProfileKey(connection?.profile ?? (connection ? activeGatewayProfile : BOOT_PROFILE_KEY))
// Built-ins + user-installed + registry-contributed themes. Reactive so an
// import or a plugin registration shows up live in the palette, settings
@@ -400,11 +409,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
)
const [themeName, setThemeNameState] = useState(() =>
- typeof window === 'undefined' ? DEFAULT_SKIN_NAME : storedSkin(readBootProfileKey())
+ typeof window === 'undefined' ? DEFAULT_SKIN_NAME : storedSkin(BOOT_PROFILE_KEY)
)
const [mode, setModeState] = useState<ThemeMode>(() =>
- typeof window === 'undefined' ? 'system' : modePref.resolve(readBootProfileKey())
+ typeof window === 'undefined' ? 'system' : modePref.resolve(BOOT_PROFILE_KEY)
)
// Follow profile switches: paint the profile's assigned skin + mode and
diff --git a/package-lock.json b/package-lock.json
index 0970a7e8dd5..eb42fc77909 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -143,7 +143,8 @@
"unist-util-visit-parents": "6.0.2",
"use-stick-to-bottom": "1.1.6",
"vfile": "6.0.3",
- "web-haptics": "0.0.6"
+ "web-haptics": "0.0.6",
+ "yaml": "2.8.1"
},
"devDependencies": {
"@babel/core": "8.0.1",
@@ -19367,6 +19368,18 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/yaml": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",
+ "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ }
+ },
"node_modules/yargs": {
"version": "18.0.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",