Skip to content

The agent that grows with you

feat(desktop): answer theme.apply and theme.pick

alt-glitchaebe8e6f6000
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
index ddc01daaa0c..bbd6abcd7cb 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
@@ -31,6 +31,7 @@ import {
} from '@/store/prompts'
import { requestRoute } from '@/store/recovery-requests'
import { forgetServerRequest } from '@/store/server-requests'
+import { clearThemePick } from '@/store/theme-pick'
import type { GatewayEventContext } from './types'
@@ -191,6 +192,8 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
clearVaultSaveLoginRequest(sessionId, id)
} else if ($vaultUnlockRequests.get()[key]?.requestId === id) {
clearVaultUnlockRequest(sessionId, id)
+ } else if (sessionId && clearThemePick(id, sessionId)) {
+ deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))
}
return true
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
index 9d0bf506216..e437909ab0d 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
@@ -17,6 +17,7 @@ import { translateNow } from '@/i18n'
import { restorePendingClarifyToolCall } from '@/lib/chat-messages'
import type { PreviewActAction } from '@/lib/preview-act/act-in-page'
import type { TourAction, TourStep } from '@/lib/tour'
+import { type AppearanceValues, applyAppearance, THEME_MODES } from '@/store/appearance-apply'
import { type ClarifyRequest, normalizeQuestions, normalizeSetupChoose, setClarifyRequest } from '@/store/clarify'
import type { ScopedServerRequest } from '@/store/gateway'
import { dispatchNativeNotification } from '@/store/native-notifications'
@@ -37,6 +38,7 @@ import {
previewScopeForRuntime,
storedSessionIdForRuntimeId
} from '@/store/session-states'
+import { parkThemePick } from '@/store/theme-pick'
import { requestScrollToBottom } from '@/store/thread-scroll'
import { $toursEnabled } from '@/store/tours'
@@ -104,7 +106,7 @@ type PreviewSessionRoute = 'ignore' | 'retry' | 'run'
* would win the race, so the tool reports "no preview tab / no terminal" while
* the owner's pane is open (#113348).
*/
-const WINDOW_OWNED_REQUESTS = new Set(['preview.act', 'preview.read', 'terminal.read', 'window.read', 'tour'])
+const WINDOW_OWNED_REQUESTS = new Set(['preview.act', 'preview.read', 'terminal.read', 'theme.apply', 'window.read', 'tour'])
/**
* A window not hosting the session declines instead of staying silent. The
@@ -695,6 +697,47 @@ const tour: Handler = ({ deps, isActiveSession, request, sessionId }) => {
)
}
+// ── set_theme ───────────────────────────────────────────────────────────────
+
+const appearanceValues = ({ params }: ScopedServerRequest): AppearanceValues => {
+ const mode = THEME_MODES.find(candidate => candidate === params.mode)
+
+ return {
+ ...(str(params.accent) && { accent: str(params.accent) }),
+ ...(str(params.layout) && { layout: str(params.layout) }),
+ ...(mode && { mode })
+ }
+}
+
+const themeApply: Handler = ({ isActiveSession, request }) => {
+ // Active session only, like the tour: a background turn never repaints the app the user is looking at.
+ answerValue(
+ request,
+ isActiveSession
+ ? applyAppearance(appearanceValues(request))
+ : { error: 'set_theme only changes the app while the user is looking at this chat.', success: false }
+ )
+}
+
+const themePick: Handler = ctx => {
+ const picker = ctx.request.params.picker
+
+ if (!ctx.sessionId || (picker !== 'accent' && picker !== 'layout')) {
+ ctx.request.respond({ cancelled: true })
+
+ return
+ }
+
+ if (declineIfSessionStopped(ctx)) {
+ return
+ }
+
+ rememberServerRequest(ctx.request)
+ parkThemePick({ picker, requestId: ctx.request.id, sessionId: ctx.sessionId })
+ markNeedsInput(ctx)
+ notifyInput(ctx, translateNow(`assistant.themePicker.${picker}`))
+}
+
/** Method → handler. Every `ServerRequestMap` key the desktop answers. */
export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
approval,
@@ -706,6 +749,8 @@ export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
setup_choose: setupChoose,
sudo,
'terminal.read': terminalRead,
+ 'theme.apply': themeApply,
+ 'theme.pick': themePick,
tour,
'vault.code': vaultCode,
'vault.save_login': vaultSaveLogin,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/theme-requests.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/theme-requests.test.ts
new file mode 100644
index 00000000000..d83da6a3656
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/theme-requests.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+
+import { registerLayoutPresets } from '@/app/contrib/layout-presets'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import type { ScopedServerRequest } from '@/store/gateway'
+import { resetServerRequestsForTests } from '@/store/server-requests'
+import { $themePicks, cancelThemePick, pickTheme } from '@/store/theme-pick'
+import { $pendingSkinApply } from '@/themes/backend-sync'
+
+import { handleServerRequest, type ServerRequestContext } from './server-requests'
+
+// SAFETY: the set_theme handlers read only activeSessionIdRef, sessionInterrupted and updateSessionState.
+const deps = {
+ activeSessionIdRef: { current: 'session-a' },
+ sessionInterrupted: () => false,
+ sessionStateByRuntimeIdRef: { current: new Map() },
+ updateSessionState: (_sessionId, update) => update(createClientSessionState('stored-session')),
+ upsertToolCall: () => undefined
+} as ServerRequestContext['deps']
+
+function deliver(method: string, params: ScopedServerRequest['params']) {
+ const respond = vi.fn()
+ const decline = vi.fn()
+
+ handleServerRequest(
+ { decline, fail: vi.fn(), id: 'srq-1', method, params, profile: 'default', respond },
+ deps,
+ 'session-a'
+ )
+
+ return Object.assign(respond, { decline })
+}
+
+describe('set_theme requests', () => {
+ beforeAll(() => {
+ registerLayoutPresets()
+ })
+
+ afterEach(() => {
+ $themePicks.set({})
+ $pendingSkinApply.set(null)
+ resetServerRequestsForTests()
+ })
+
+ it('parks a picker card and answers it with the applied pick', () => {
+ const respond = deliver('theme.pick', { picker: 'accent', session_id: 'session-a' })
+
+ expect($themePicks.get()['session-a']).toMatchObject({ picker: 'accent', requestId: 'srq-1' })
+ expect(respond).not.toHaveBeenCalled()
+
+ expect(pickTheme('session-a', { accent: 'pink' })).toBe(true)
+ expect(respond).toHaveBeenCalledWith({ picked: { accent: 'pink' } })
+ expect($pendingSkinApply.get()).toBe('nous-accent-e0218a')
+ expect($themePicks.get()['session-a']).toBeUndefined()
+ })
+
+ it('answers a dismissed card as cancelled', () => {
+ const respond = deliver('theme.pick', { picker: 'layout', session_id: 'session-a' })
+
+ expect(cancelThemePick('session-a')).toBe(true)
+ expect(respond).toHaveBeenCalledWith({ cancelled: true })
+ })
+
+ it('applies values only in the window showing the chat, and nothing when one value is unknown', () => {
+ const elsewhere = deliver('theme.apply', { accent: 'violet', session_id: 'session-b' })
+ const onScreen = deliver('theme.apply', { accent: 'violet', layout: 'cockpit', session_id: 'session-a' })
+
+ expect(elsewhere.decline).toHaveBeenCalled()
+ expect(elsewhere).not.toHaveBeenCalled()
+ expect(JSON.parse(onScreen.mock.calls[0][0].value)).toMatchObject({ success: false, error: 'Unknown layout "cockpit".' })
+ expect($pendingSkinApply.get()).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/store/theme-pick.ts b/apps/desktop/src/store/theme-pick.ts
new file mode 100644
index 00000000000..f8368ea0c55
--- /dev/null
+++ b/apps/desktop/src/store/theme-pick.ts
@@ -0,0 +1,62 @@
+/**
+ * Open `theme.pick` requests (the set_theme picker card), one per session.
+ *
+ * The card in the tool row reads this to draw the picker; a pick applies the
+ * value at once and answers the request with what was applied. The backend's
+ * `request.cancel` (timeout, Stop) clears the entry by request id, so a late
+ * cancel never erases a newer card the same session raised.
+ */
+
+import type { ThemePicker, ThemePickResult } from '@hermes/shared'
+import { atom } from 'nanostores'
+
+import { type AppearanceValues, applyAppearance } from './appearance-apply'
+import { respondToServerRequest } from './server-requests'
+
+export interface ThemePickRequest {
+ picker: ThemePicker
+ requestId: string
+ sessionId: string
+}
+
+export const $themePicks = atom<Record<string, ThemePickRequest>>({})
+
+export function parkThemePick(request: ThemePickRequest): void {
+ $themePicks.set({ ...$themePicks.get(), [request.sessionId]: request })
+}
+
+/** Drop the card for `requestId`; a no-op when the session's card is a newer one. */
+export function clearThemePick(requestId: string, sessionId: string): boolean {
+ const { [sessionId]: current, ...others } = $themePicks.get()
+
+ if (current?.requestId !== requestId) {
+ return false
+ }
+
+ $themePicks.set(others)
+
+ return true
+}
+
+function answer(sessionId: string, result: ThemePickResult): boolean {
+ const request = $themePicks.get()[sessionId]
+
+ if (!request) {
+ return false
+ }
+
+ clearThemePick(request.requestId, sessionId)
+
+ return respondToServerRequest(request.requestId, { ...result })
+}
+
+/** Apply the user's pick and answer the session's card with it. False when no card waits or the value is unknown. */
+export function pickTheme(sessionId: string, values: AppearanceValues): boolean {
+ const applied = applyAppearance(values)
+
+ return applied.success && answer(sessionId, { picked: applied.applied })
+}
+
+export function cancelThemePick(sessionId: string): boolean {
+ return answer(sessionId, { cancelled: true })
+}