Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add lighting presets switched with Shift+digits and other apps
shinshin8667174931b0e2
diff --git a/README.ja.md b/README.ja.mdindex 94095c6..b2d2887 100644--- a/README.ja.md+++ b/README.ja.md@@ -86,6 +86,8 @@ npm run dev「表情」のボタンか、キー1〜8で、笑顔、驚き、ウインクなどに切り替えられます。切り替えている間も、まばたきや口の動きはカメラとマイクに合わせて動きます。Stream Deck のボタンやキーボードショートカットを使えば、OBS など他のアプリを操作中でも切り替えられます。macOS の「ショートカット」アプリで割り当てたキーは、前面のアプリによっては効かないことがあります([設定方法](docs/reference.md#switching-expressions-from-other-apps)、英語)。+ライティングの設定は、プリセットとして8つまで保存できます。ホラーゲーム用に下から赤い光を当てる設定などを保存しておき、Shift+1〜8 や同じ仕組みのショートカットで切り替えられます([詳しく](docs/reference.md#lighting-presets)、英語)。+カメラは使わなくてもかまいません。マイクだけをオンにすると、アバターは待機動作を続けながら、声に合わせて口を動かします。Zoom や Google Meet などの Web 会議にアバターで参加するときは、OBS の仮想カメラを使います([手順](docs/reference.md#video-calls)、英語)。配信用画面の URL で指定できる項目、うまく動かないときの確認点、プライバシーについては[リファレンス](docs/reference.md#live-and-streaming)(英語)にまとめています。diff --git a/README.md b/README.mdindex fd98281..dc36053 100644--- a/README.md+++ b/README.md@@ -124,6 +124,10 @@ keys **1**–**8** while tracking continues. A Stream Deck button or a keyboardswitch them while another app such as OBS is in front; macOS Shortcuts keys do not work inevery app ([details](docs/reference.md#switching-expressions-from-other-apps)).+Save up to eight lighting setups, such as a red light from below for a horror game, as+presets, and switch them with **Shift**+**1**–**8** or the same kind of shortcut+([details](docs/reference.md#lighting-presets)).+The camera is optional: with only the microphone on, the avatar keeps its idle motion andyour voice moves the mouth. To appear as the avatar in Zoom, Google Meet and similar apps, useOBS's Virtual Camera ([steps](docs/reference.md#video-calls)).diff --git a/docs/reference.md b/docs/reference.mdindex f889992..64ee275 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -149,6 +149,30 @@ are kept; the light deepens colours on the far side and keeps the painted colourin `rig.json`, but each project remembers them in this browser. With lighting off, the avatarrenders exactly as without the feature.+### Lighting presets++The Live page's **Lighting** section has eight preset slots, for example a normal light, a+red light from below for a horror game, and a sunset colour. **Save** stores every current+lighting setting (position, colours, shading and on or off) in that slot; saving again+overwrites it. Click a saved slot, or press **Shift**+**1**–**8** while the Live page is+focused, to switch to it at once. The swatch shows the light colour and the ambient colour.+Presets are kept per project in this browser, like the current lighting.++A preset does not change the expression, and an expression does not change the lighting, so+both can be switched independently. To return to normal lighting, save it in a slot (for+example 1) and switch to that slot. Switching to an empty slot changes nothing.++Other apps switch presets the same way as+[expressions](#switching-expressions-from-other-apps), with the same token: `POST` to+`/__live/lighting` (shown as **Preset request URL** under the presets) with a JSON body+such as `{"preset": 2}`. Numbers are 1–8, and `"project"` works as for expressions.++```sh+curl -X POST http://127.0.0.1:5173/__live/lighting \+ -H "X-Studio-Token: <token>" -H "Content-Type: application/json" \+ -d '{"preset": 2}'+```+## Live and streamingTwo pages served by the development server (`npm run dev`):diff --git a/e2e/lighting-presets.spec.ts b/e2e/lighting-presets.spec.tsnew file mode 100644index 0000000..b4fcf0f--- /dev/null+++ b/e2e/lighting-presets.spec.ts@@ -0,0 +1,59 @@+import { expect, test } from '@playwright/test';+import { samplePresent, sampleSkipReason } from './sample';++test.beforeEach(() => test.skip(!samplePresent, sampleSkipReason));++test('lighting presets are saved per slot, applied with Shift+digits and other apps, and reach the stream view', async ({ context, page, request }) => {+ const outside: string[] = [];+ await context.route('**/*', route => { const url = route.request().url(); if (new URL(url).hostname !== '127.0.0.1') { outside.push(url); return route.abort(); } return route.continue(); });+ await page.goto('/live.html'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');+ const stream = await context.newPage(); await stream.goto('/stream.html'); await expect(stream.locator('canvas')).toHaveAttribute('data-state', 'ready');+ await stream.evaluate(async () => {+ const path = '/src/live/relay.ts', { receiveLighting } = await import(path);+ Object.assign(window, { colors: [] });+ receiveLighting('sample-miko-qipao', (value: { color: number }) => (window as unknown as { colors: number[] }).colors.push(value.color));+ });+ const streamColor = () => stream.evaluate(() => (window as unknown as { colors: number[] }).colors.at(-1));++ const section = page.getByTestId('lighting-section'); await section.locator('summary').click();+ const slots = page.getByRole('group', { name: 'Presets' }), color = section.getByLabel('Light color', { exact: true });+ const slot = (n: number) => slots.getByRole('button', { name: new RegExp(`^Preset ${n}`) });+ await expect(slots.getByRole('button', { name: /^Preset/ })).toHaveCount(8);+ await expect(slot(1)).toBeDisabled(); await expect(slot(1)).toHaveAccessibleName('Preset 1 (Empty)'); await expect(slot(1)).toHaveText('⇧1Empty');++ await section.getByLabel('Enable lighting').check();+ await color.fill('#ff2000'); await section.getByRole('button', { name: 'Save: Preset 1' }).click();+ await expect(slot(1)).toHaveAttribute('aria-pressed', 'true');+ await color.fill('#2060ff'); await section.getByRole('button', { name: 'Save: Preset 2' }).click();+ await expect(slot(1)).toHaveAttribute('aria-pressed', 'false'); await expect(slot(2)).toHaveAttribute('aria-pressed', 'true');++ await page.locator('body').press('Shift+Digit1');+ await expect(color).toHaveValue('#ff2000'); await expect(slot(1)).toHaveAttribute('aria-pressed', 'true');+ await expect.poll(streamColor).toBe(0xff2000);+ // Shift+digits leave the expression alone, and an empty slot changes nothing.+ await expect(page.getByTestId('expression-section').locator('.expression-on')).toHaveCount(0);+ await page.locator('body').press('Shift+Digit5');+ await expect(color).toHaveValue('#ff2000');+ await slot(2).click(); await expect(color).toHaveValue('#2060ff');+ await page.locator('body').press('Shift+Digit1'); await expect(color).toHaveValue('#ff2000');++ const expression = page.getByTestId('expression-section'); await expression.locator('summary').click();+ const token = await expression.getByRole('textbox', { name: /Token/ }).inputValue();+ const url = await section.getByRole('textbox', { name: 'Preset request URL' }).inputValue();+ expect(new URL(url).pathname).toBe('/__live/lighting');+ const send = (body: unknown) => request.post(url, { data: body, headers: { 'X-Studio-Token': token } });+ expect((await send({ preset: 2, project: 'sample-miko-qipao' })).status()).toBe(200);+ await expect(color).toHaveValue('#2060ff'); await expect.poll(streamColor).toBe(0x2060ff);+ await page.waitForTimeout(60);+ expect((await send({ preset: 1, project: 'another-project' })).status()).toBe(200);+ await page.waitForTimeout(200); await expect(color).toHaveValue('#2060ff');+ expect((await send({ preset: 9 })).status()).toBe(400);++ // Presets stay in this browser for the project.+ await page.reload(); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');+ await page.getByTestId('lighting-section').locator('summary').click();+ await expect(slot(1)).toBeEnabled(); await expect(slot(2)).toBeEnabled(); await expect(slot(3)).toBeDisabled();+ await page.getByRole('button', { name: '日本語', exact: true }).click();+ await expect(page.getByRole('group', { name: 'プリセット' }).getByRole('button', { name: 'プリセット 3 (未保存)' })).toHaveText('⇧3未保存');+ expect(outside).toEqual([]);+});diff --git a/src/lighting/presets.ts b/src/lighting/presets.tsnew file mode 100644index 0000000..313d55c--- /dev/null+++ b/src/lighting/presets.ts@@ -0,0 +1,23 @@+import { DEFAULT_LIGHTING, parseLighting, type LightingSettings } from './settings';++export const LIGHTING_PRESET_COUNT = 8;+/** Slot i holds preset number i + 1; empty slots are null. */+export type LightingPresets = (LightingSettings | null)[];++export function parseLightingPresets(stored: unknown): LightingPresets {+ return Array.from({ length: LIGHTING_PRESET_COUNT }, (_, i) => {+ const value: unknown = Array.isArray(stored) ? stored[i] : null;+ // Presets saved before newer options existed keep their values; missing options use defaults.+ return value && typeof value === 'object' && !Array.isArray(value) ? parseLighting({ ...DEFAULT_LIGHTING, ...value }) : null;+ });+}+export function sameLighting(a: LightingSettings, b: LightingSettings) {+ return (Object.keys(DEFAULT_LIGHTING) as (keyof LightingSettings)[]).every(key => a[key] === b[key]);+}+export function loadLightingPresets(project: string): LightingPresets {+ try { return parseLightingPresets(JSON.parse(localStorage.getItem(`mesh-avatar:lighting-presets:${project}`) ?? 'null')); }+ catch { return parseLightingPresets(null); }+}+export function saveLightingPresets(project: string, presets: LightingPresets) {+ try { localStorage.setItem(`mesh-avatar:lighting-presets:${project}`, JSON.stringify(presets)); } catch { /* Storage is optional. */ }+}diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsxindex d7821ca..4c68dfe 100644--- a/src/live/LiveApp.tsx+++ b/src/live/LiveApp.tsx@@ -1,5 +1,6 @@import { LightingControls, LightHandle, lightingText } from '../lighting/Controls';-import { loadLighting, saveLighting } from '../lighting/settings';+import { colorHex, loadLighting, saveLighting } from '../lighting/settings';+import { loadLightingPresets, sameLighting, saveLightingPresets } from '../lighting/presets';import { LIVE_EXPRESSIONS, type LiveExpression, type MeshAvatar } from '../engine';import { useEffect, useRef, useState } from 'react';import { useI18n } from '../editor/i18n';@@ -9,13 +10,15 @@ import { FacePose, type TrackingOptions } from './tracking';import { CameraCapture, MicrophoneCapture, type CameraState, type MicState, type BackgroundTracking } from './media';import { liveText } from './i18n';import { Icon } from '../editor/Icon';-import { createLiveSender, receiveExpression, sendLighting, watchDuplicateLivePages } from './relay';-import { EXPRESSION_TOKEN_PATH } from './expression-protocol';+import { createLiveSender, receiveExpression, receiveLightingPreset, sendLighting, watchDuplicateLivePages } from './relay';+import { EXPRESSION_TOKEN_PATH, LIGHTING_PRESET_PATH } from './expression-protocol';export function LiveApp() {const { language, setLanguage } = useI18n(), t = liveText[language];const [settings, setSettings] = useState(() => { const view = viewSettings(location.search); return { ...view, lighting: view.lighting ?? loadLighting(view.project) }; });const [lightingOpen, setLightingOpen] = useState(false);+ const [presets, setPresets] = useState(() => loadLightingPresets(settings.project));+ const presetsRef = useRef(presets); presetsRef.current = presets;const [duplicatePage, setDuplicatePage] = useState(false);const [expression, setExpression] = useState<LiveExpression>('neutral');const expressionRef = useRef(expression); expressionRef.current = expression;@@ -85,6 +88,14 @@ export function LiveApp() {useEffect(() => { avatarRef.current?.setExpression(expression); }, [expression]);useEffect(() => watchDuplicateLivePages(settings.project, setDuplicatePage), [settings.project]);useEffect(() => receiveExpression(settings.project, setExpression), [settings.project]);+ // Empty slots are ignored, so a shortcut for an unsaved preset changes nothing.+ const applyPreset = (preset: number) => { const value = presetsRef.current[preset - 1]; if (value) changeLighting({ ...value }); };+ const savePreset = (index: number) => {+ const next = presets.map((value, i) => i === index ? { ...settings.lighting } : value);+ setPresets(next); saveLightingPresets(settings.project, next);+ };+ const applyPresetRef = useRef(applyPreset); applyPresetRef.current = applyPreset;+ useEffect(() => receiveLightingPreset(settings.project, preset => applyPresetRef.current(preset)), [settings.project]);const loadRemote = (method: 'GET' | 'POST') => fetch(EXPRESSION_TOKEN_PATH, { method, headers: { 'x-studio-request': '1' } }).then(response => response.ok ? response.json() : null).then((data: { token?: unknown; path?: unknown } | null) => setRemote(typeof data?.token === 'string' && typeof data.path === 'string' ? { url: `${location.origin}${data.path}`, token: data.token } : null))@@ -95,6 +106,13 @@ export function LiveApp() {const onKey = (event: KeyboardEvent) => {const target = event.target as HTMLElement | null;if (event.repeat || event.altKey || event.ctrlKey || event.metaKey || target?.closest('input, select, textarea, [contenteditable="true"]')) return;+ // Shift with a digit applies a lighting preset. The physical key is used because Shift+ // changes the typed character (Shift+1 is "!" on common layouts).+ if (event.shiftKey) {+ const preset = /^Digit([1-8])$/.exec(event.code);+ if (preset) { event.preventDefault(); applyPresetRef.current(Number(preset[1])); }+ return;+ }const name = LIVE_EXPRESSIONS[Number(event.key) - 1];if (!/^[1-8]$/.test(event.key) || !name) return;event.preventDefault(); setExpression(name);@@ -158,6 +176,17 @@ export function LiveApp() {</details><details className="live-lighting" data-testid="lighting-section" onToggle={event => setLightingOpen(event.currentTarget.open)}><summary><Icon name="light" />{lightingText[language].title}{settings.lighting.enabled && <span className="lighting-on">ON</span>}</summary>+ <div className="lighting-presets"><h3>{t.presets}</h3>+ <div className="preset-slots" role="group" aria-label={t.presets}>+ {presets.map((value, i) => <div className="preset-slot" key={i}>+ {/* The swatch shows the light and ambient colours; the slot number is in the key hint. */}+ <button type="button" disabled={!value} aria-label={`${t.preset} ${i + 1}${value ? '' : ` (${t.presetEmpty})`}`} aria-pressed={!!value && sameLighting(value, settings.lighting)} aria-keyshortcuts={`Shift+${i + 1}`} onClick={() => applyPreset(i + 1)}>+ <kbd>⇧{i + 1}</kbd>{value ? <span className={`preset-swatch${value.enabled ? '' : ' off'}`} style={value.enabled ? { background: `linear-gradient(135deg, ${colorHex(value.color)} 50%, ${colorHex(value.ambientColor)} 50%)` } : undefined} /> : t.presetEmpty}</button>+ <button type="button" className="preset-save" aria-label={`${t.presetSave}: ${t.preset} ${i + 1}`} onClick={() => savePreset(i)}>{t.presetSave}</button>+ </div>)}+ </div><small>{t.presetHint}</small>+ {remote && <label>{t.presetUrl}<span className="remote-field"><input readOnly value={`${location.origin}${LIGHTING_PRESET_PATH}`} onFocus={event => event.target.select()} /></span></label>}+ </div><LightingControls value={settings.lighting} onChange={changeLighting} language={language} /></details><p className="live-privacy">{t.privacy}</p>diff --git a/src/live/expression-protocol.ts b/src/live/expression-protocol.tsindex f68cdcb..3cfe898 100644--- a/src/live/expression-protocol.ts+++ b/src/live/expression-protocol.ts@@ -1,20 +1,36 @@-// Expression switches sent from other apps (keyboard shortcuts, button panels) through the-// local development server to the Live page.+import { LIGHTING_PRESET_COUNT } from '../lighting/presets';++// Expression and lighting preset switches sent from other apps (keyboard shortcuts, button+// panels) through the local development server to the Live page.export const EXPRESSION_EVENT = 'studio:expression';export const EXPRESSION_PATH = '/__live/expression';+export const LIGHTING_PRESET_EVENT = 'studio:lighting-preset';+export const LIGHTING_PRESET_PATH = '/__live/lighting';export const EXPRESSION_TOKEN_PATH = '/__live/expression-token';export const TOKEN_HEADER = 'x-studio-token';export const REMOTE_EXPRESSIONS = ['neutral', 'smile', 'shy', 'surprise', 'halfLidded', 'angry', 'sad', 'wink'] as const;export type RemoteExpression = typeof REMOTE_EXPRESSIONS[number];export interface ExpressionMessage { expression: RemoteExpression; project: string | null }+export interface LightingPresetMessage { preset: number; project: string | null }const projectName = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;-/** Accepts `{ expression, project? }` with a known expression and a plain project name only. */-export function expressionMessage(input: unknown): ExpressionMessage | null {+/** The object with only `field` and an optional plain project name, or null. */+function remoteBody(input: unknown, field: string) {if (!input || typeof input !== 'object' || Array.isArray(input)) return null;const data = input as Record<string, unknown>;- if (Object.keys(data).some(key => key !== 'expression' && key !== 'project')) return null;- if (typeof data.expression !== 'string' || !(REMOTE_EXPRESSIONS as readonly string[]).includes(data.expression)) return null;+ if (Object.keys(data).some(key => key !== field && key !== 'project')) return null;if (data.project !== undefined && data.project !== null && (typeof data.project !== 'string' || !projectName.test(data.project))) return null;- return { expression: data.expression as RemoteExpression, project: typeof data.project === 'string' ? data.project : null };+ return { value: data[field], project: typeof data.project === 'string' ? data.project : null };+}+/** Accepts `{ expression, project? }` with a known expression and a plain project name only. */+export function expressionMessage(input: unknown): ExpressionMessage | null {+ const body = remoteBody(input, 'expression');+ if (!body || typeof body.value !== 'string' || !(REMOTE_EXPRESSIONS as readonly string[]).includes(body.value)) return null;+ return { expression: body.value as RemoteExpression, project: body.project };+}+/** Accepts `{ preset, project? }` with a preset number from 1 to 8. */+export function lightingPresetMessage(input: unknown): LightingPresetMessage | null {+ const body = remoteBody(input, 'preset');+ if (!body || !Number.isInteger(body.value) || (body.value as number) < 1 || (body.value as number) > LIGHTING_PRESET_COUNT) return null;+ return { preset: body.value as number, project: body.project };}diff --git a/src/live/i18n.ts b/src/live/i18n.tsindex 54deff6..d3c8b48 100644--- a/src/live/i18n.ts+++ b/src/live/i18n.ts@@ -24,6 +24,8 @@ export const liveEn = {remoteUrl: 'Request URL', remoteToken: 'Token (X-Studio-Token header)', copy: 'Copy', copiedShort: 'Copied', regenerate: 'Regenerate token',regenerateHelp: 'Regenerating stops shortcuts that use the old token.', remoteNames: 'Expression names: neutral, smile, shy, surprise, halfLidded, angry, sad, wink. Send neutral to return to the normal face.',remoteDocs: 'Setup for macOS Shortcuts and Stream Deck', remoteUnavailable: 'Available while the local development server is running.',+ presets: 'Presets', preset: 'Preset', presetEmpty: 'Empty', presetSave: 'Save', presetUrl: 'Preset request URL',+ presetHint: 'Save stores the current lighting in that slot. While this page is focused, Shift+1–8 apply presets. Other apps can send {"preset": 1} to the URL below with the same token as expressions.',};const liveJa: typeof liveEn = {title: '配信', back: 'エディタに戻る', camera: 'カメラ', device: 'デバイス', defaultDevice: '既定のデバイス',@@ -51,6 +53,8 @@ const liveJa: typeof liveEn = {remoteUrl: '送信先URL', remoteToken: 'トークン(X-Studio-Token ヘッダー)', copy: 'コピー', copiedShort: 'コピーしました', regenerate: 'トークンを作り直す',regenerateHelp: '作り直すと、古いトークンを使っているショートカットは動かなくなります。', remoteNames: '表情の名前: neutral, smile, shy, surprise, halfLidded, angry, sad, wink。通常に戻すときは neutral を送ります。',remoteDocs: 'macOSのショートカットとStream Deckでの設定方法', remoteUnavailable: 'ローカルの開発サーバーで起動しているときに使えます。',+ presets: 'プリセット', preset: 'プリセット', presetEmpty: '未保存', presetSave: '保存', presetUrl: 'プリセットの送信先URL',+ presetHint: '「保存」で今のライティングをその枠に保存します。この画面を操作している間は、Shift+1〜8でプリセットを呼び出せます。他のアプリからは、表情と同じトークンを付けて下のURLに {"preset": 1} を送ります。',};const liveZh: typeof liveEn = {title: '直播', back: '返回编辑器', camera: '摄像头', device: '设备', defaultDevice: '默认设备',@@ -78,5 +82,7 @@ const liveZh: typeof liveEn = {remoteUrl: '请求 URL', remoteToken: '令牌(X-Studio-Token 请求头)', copy: '复制', copiedShort: '已复制', regenerate: '重新生成令牌',regenerateHelp: '重新生成后,使用旧令牌的快捷方式将无法使用。', remoteNames: '表情名称:neutral, smile, shy, surprise, halfLidded, angry, sad, wink。发送 neutral 恢复普通表情。',remoteDocs: 'macOS 快捷指令和 Stream Deck 的设置方法', remoteUnavailable: '在本地开发服务器运行时可用。',+ presets: '预设', preset: '预设', presetEmpty: '未保存', presetSave: '保存', presetUrl: '预设请求 URL',+ presetHint: '“保存”会把当前光照存入该栏位。在此页面操作时,可用 Shift+1–8 应用预设。其他应用可附上与表情相同的令牌,向下方 URL 发送 {"preset": 1}。',};export const liveText = { en: liveEn, ja: liveJa, zh: liveZh };diff --git a/src/live/live.css b/src/live/live.cssindex 26e07a6..92c1b21 100644--- a/src/live/live.css+++ b/src/live/live.css@@ -59,3 +59,16 @@ input[type="color"] { width: 100%; height: 32px; border: 0; padding: 0; }.remote-actions { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; margin: 10px 0; }.live-expression-body small { display: block; color: #5a6a80; }.live-warning { margin: 0; padding: 12px 14px; border: 1px solid #e3b341; border-radius: 12px; background: #fff8e1; color: #6b4e00; font-size: 13px; line-height: 1.5; }+.lighting-presets { padding: 0 16px 4px; }+.lighting-presets h3 { margin: 4px 0 8px; font-size: 13px; }+.preset-slots { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; margin-bottom: 8px; }+.preset-slot { display: flex; gap: 4px; min-width: 0; }+.preset-slot button { font-size: 12px; }+.preset-slot button:first-child { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; text-align: left; white-space: nowrap; overflow: hidden; }+.preset-slot button[aria-pressed="true"] { border-color: #3977d8; background: #e8f0fd; color: #1d4f9c; font-weight: 600; }+.preset-slot kbd { padding: 0 4px; border: 1px solid #c8d3e2; border-radius: 4px; font: 11px/1.5 ui-monospace, monospace; color: #5a6a80; background: #f6f8fb; }+.preset-swatch { flex: 1; height: 16px; border-radius: 4px; border: 1px solid #0003; }+.preset-swatch.off { border-style: dashed; background: transparent; }+.preset-save { flex: none; padding-inline: 8px; }+.lighting-presets small { display: block; color: #5a6a80; line-height: 1.5; }+.live-controls .live-lighting .lighting-presets label { flex-direction: column; align-items: stretch; gap: 4px; }diff --git a/src/live/relay.ts b/src/live/relay.tsindex a687259..ec5cd6d 100644--- a/src/live/relay.ts+++ b/src/live/relay.ts@@ -1,7 +1,7 @@import { LIGHTING_EVENT, lightingWire, lightingMessage, lightingValue } from '../lighting/protocol';import type { LightingSettings } from '../lighting/settings';import { LIVE_EVENT, liveMessage } from './protocol';-import { EXPRESSION_EVENT, expressionMessage, type RemoteExpression } from './expression-protocol';+import { EXPRESSION_EVENT, LIGHTING_PRESET_EVENT, expressionMessage, lightingPresetMessage, type RemoteExpression } from './expression-protocol';export function createLiveSender(project: string, sender = randomSender()) {let sent = -Infinity;@@ -32,6 +32,12 @@ export function receiveExpression(project: string, callback: (expression: Remoteimport.meta.hot?.on(EXPRESSION_EVENT, receive);return () => import.meta.hot?.off(EXPRESSION_EVENT, receive);}+/** Lighting preset numbers (1–8) sent from other apps, addressed like expressions. */+export function receiveLightingPreset(project: string, callback: (preset: number) => void) {+ const receive = (data: unknown) => { const message = lightingPresetMessage(data); if (message && (message.project === null || message.project === project)) callback(message.preset); };+ import.meta.hot?.on(LIGHTING_PRESET_EVENT, receive);+ return () => import.meta.hot?.off(LIGHTING_PRESET_EVENT, receive);+}export function randomSender() {return Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('');diff --git a/src/server/expression-remote.ts b/src/server/expression-remote.tsindex 1c588ed..6327d1d 100644--- a/src/server/expression-remote.ts+++ b/src/server/expression-remote.ts@@ -2,18 +2,30 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';import type { IncomingMessage, ServerResponse } from 'node:http';import { dirname } from 'node:path';-import { EXPRESSION_PATH, EXPRESSION_TOKEN_PATH, TOKEN_HEADER, expressionMessage, type ExpressionMessage } from '../live/expression-protocol';+import { EXPRESSION_PATH, EXPRESSION_TOKEN_PATH, LIGHTING_PRESET_PATH, TOKEN_HEADER, expressionMessage, lightingPresetMessage,+ type ExpressionMessage, type LightingPresetMessage } from '../live/expression-protocol';const MAX_BODY = 1024, MIN_INTERVAL_MS = 50;const newToken = () => randomBytes(24).toString('base64url');/**- * Lets keyboard-shortcut and button-panel apps on this machine switch the Live page's expression.- * Requests need the token shown on the Live page. No CORS headers are sent, so other websites can- * neither read the token nor send the custom token header.+ * Lets keyboard-shortcut and button-panel apps on this machine switch the Live page's expression+ * and lighting preset. Requests need the token shown on the Live page. No CORS headers are sent,+ * so other websites can neither read the token nor send the custom token header.*/-export function expressionRemote(tokenFile: string, broadcast: (message: ExpressionMessage) => void) {- let token: string | null = null, last = -Infinity;+export function expressionRemote(tokenFile: string, broadcast: (message: ExpressionMessage) => void,+ broadcastPreset: (message: LightingPresetMessage) => void) {+ let token: string | null = null;+ // Each route validates a body and returns what to broadcast and reply, or null. Routes keep+ // separate rate limits so one shortcut can switch an expression and a preset together.+ const route = <T,>(parse: (data: unknown) => T | null, send: (message: T) => void, reply: (message: T) => object, invalid: string) => ({+ last: -Infinity, invalid,+ accept: (data: unknown) => { const message = parse(data); return message && { send: () => send(message), reply: reply(message) }; },+ });+ const routes: Record<string, ReturnType<typeof route>> = {+ [EXPRESSION_PATH]: route(expressionMessage, broadcast, m => ({ expression: m.expression }), 'Send {"expression": "smile"} with a known expression.'),+ [LIGHTING_PRESET_PATH]: route(lightingPresetMessage, broadcastPreset, m => ({ preset: m.preset }), 'Send {"preset": 1} with a preset number from 1 to 8.'),+ };const load = async () => {if (token) return token;try { const saved = (await readFile(tokenFile, 'utf8')).trim(); if (/^[A-Za-z0-9_-]{32}$/.test(saved)) return (token = saved); } catch { /* Created below. */ }@@ -41,8 +53,9 @@ export function expressionRemote(tokenFile: string, broadcast: (message: Expressreturn a.length === b.length && timingSafeEqual(a, b);};return async (req: IncomingMessage, res: ServerResponse, next: () => void) => {- const path = req.url?.split('?')[0];- if (path !== EXPRESSION_PATH && path !== EXPRESSION_TOKEN_PATH) { next(); return; }+ const path = req.url?.split('?')[0] ?? '';+ const target = Object.hasOwn(routes, path) ? routes[path] : null;+ if (!target && path !== EXPRESSION_TOKEN_PATH) { next(); return; }try {if (path === EXPRESSION_TOKEN_PATH) {// Only the Live page itself reads or renews the token: a browser sends this custom header@@ -57,12 +70,12 @@ export function expressionRemote(tokenFile: string, broadcast: (message: Expressconst body = await readBody(req);if (body === null) { json(res, 413, { error: 'Request too large.' }); return; }let data: unknown; try { data = JSON.parse(body); } catch { data = null; }- const message = expressionMessage(data);- if (!message) { json(res, 400, { error: 'Send {"expression": "smile"} with a known expression.' }); return; }+ const accepted = target!.accept(data);+ if (!accepted) { json(res, 400, { error: target!.invalid }); return; }const now = performance.now();- if (now - last < MIN_INTERVAL_MS) { json(res, 429, { error: 'Too many requests.' }); return; }- last = now; broadcast(message);- json(res, 200, { ok: true, expression: message.expression });- } catch { json(res, 500, { error: 'Expression switch failed.' }); }+ if (now - target!.last < MIN_INTERVAL_MS) { json(res, 429, { error: 'Too many requests.' }); return; }+ target!.last = now; accepted.send();+ json(res, 200, { ok: true, ...accepted.reply });+ } catch { json(res, 500, { error: 'Switch failed.' }); }};}diff --git a/src/server/live-relay.ts b/src/server/live-relay.tsindex e388de3..356f5f7 100644--- a/src/server/live-relay.ts+++ b/src/server/live-relay.ts@@ -2,14 +2,15 @@ import { LIGHTING_EVENT, lightingMessage } from '../lighting/protocol';import type { Plugin, WebSocketClient } from 'vite';import { LIVE_EVENT, liveMessage } from '../live/protocol';import { resolve } from 'node:path';-import { EXPRESSION_EVENT } from '../live/expression-protocol';+import { EXPRESSION_EVENT, LIGHTING_PRESET_EVENT } from '../live/expression-protocol';import { expressionRemote } from './expression-remote';export function liveRelay(root: string): Plugin {return {name: 'local-live-relay',configureServer(server) {- server.middlewares.use(expressionRemote(resolve(root, 'projects', '.expression-token'), message => server.ws.send(EXPRESSION_EVENT, message)));+ server.middlewares.use(expressionRemote(resolve(root, 'projects', '.expression-token'),+ message => server.ws.send(EXPRESSION_EVENT, message), message => server.ws.send(LIGHTING_PRESET_EVENT, message)));const lastLighting = new WeakMap<WebSocketClient['socket'], number>();server.ws.on(LIGHTING_EVENT, (data, client) => {const message = lightingMessage(data), now = performance.now();diff --git a/tests/expression-remote.test.ts b/tests/expression-remote.test.tsindex 496f7f0..5e4d943 100644--- a/tests/expression-remote.test.ts+++ b/tests/expression-remote.test.ts@@ -5,7 +5,9 @@ import { join } from 'node:path';import { Readable } from 'node:stream';import type { IncomingMessage, ServerResponse } from 'node:http';import { expressionRemote } from '../src/server/expression-remote';-import { REMOTE_EXPRESSIONS, expressionMessage } from '../src/live/expression-protocol';+import { REMOTE_EXPRESSIONS, expressionMessage, lightingPresetMessage } from '../src/live/expression-protocol';+import { DEFAULT_LIGHTING } from '../src/lighting/settings';+import { parseLightingPresets, sameLighting } from '../src/lighting/presets';import { OVERLAY_EXPRESSIONS } from '../src/engine/expression-overlay.js';async function call(handler: ReturnType<typeof expressionRemote>, method: string, url: string, headers: Record<string, string> = {}, body = '') {@@ -24,7 +26,7 @@ test('the remote accepts the same expressions as the Live page', () => {test('token is private, persistent and regenerable; requests need it and a valid body', async () => {const dir = await mkdtemp(join(tmpdir(), 'expr-')), file = join(dir, 'nested', '.expression-token'), sent: unknown[] = [];- const handler = expressionRemote(file, message => sent.push(message));+ const handler = expressionRemote(file, message => sent.push(message), () => undefined);expect((await call(handler, 'GET', '/other')).passed).toBe(true);expect((await call(handler, 'GET', '/__live/expression-token')).status).toBe(403);const first = await call(handler, 'GET', '/__live/expression-token', { 'x-studio-request': '1' });@@ -33,7 +35,7 @@ test('token is private, persistent and regenerable; requests need it and a validexpect(token).toMatch(/^[A-Za-z0-9_-]{32}$/);expect((await readFile(file, 'utf8')).trim()).toBe(token); expect((await stat(file)).mode & 0o777).toBe(0o600);// A fresh server instance reuses the saved token.- const again = expressionRemote(file, () => undefined);+ const again = expressionRemote(file, () => undefined, () => undefined);expect((await call(again, 'GET', '/__live/expression-token', { 'x-studio-request': '1' })).json.token).toBe(token);const post = (headers: Record<string, string>, body: string) => call(handler, 'POST', '/__live/expression', { 'content-type': 'application/json', ...headers }, body);@@ -54,6 +56,42 @@ test('token is private, persistent and regenerable; requests need it and a valid// A corrupted token file is replaced instead of trusted.await writeFile(file, 'short\n');- const fresh = await call(expressionRemote(file, () => undefined), 'GET', '/__live/expression-token', { 'x-studio-request': '1' });+ const fresh = await call(expressionRemote(file, () => undefined, () => undefined), 'GET', '/__live/expression-token', { 'x-studio-request': '1' });expect(fresh.json.token).toMatch(/^[A-Za-z0-9_-]{32}$/);});++test('lighting preset requests accept only preset numbers 1 to 8', () => {+ expect(lightingPresetMessage({ preset: 1 })).toEqual({ preset: 1, project: null });+ expect(lightingPresetMessage({ preset: 8, project: 'demo' })).toEqual({ preset: 8, project: 'demo' });+ for (const bad of [null, [], 3, { preset: 0 }, { preset: 9 }, { preset: 1.5 }, { preset: '1' }, { preset: 1, x: 1 }, { preset: 1, project: '../a' }, { expression: 'smile' }]) expect(lightingPresetMessage(bad)).toBeNull();+});++test('lighting presets use the expression token and their own rate limit', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'preset-')), file = join(dir, '.expression-token'), expressions: unknown[] = [], presets: unknown[] = [];+ const handler = expressionRemote(file, message => expressions.push(message), message => presets.push(message));+ const token = (await call(handler, 'GET', '/__live/expression-token', { 'x-studio-request': '1' })).json.token as string;+ const post = (path: string, headers: Record<string, string>, body: string) => call(handler, 'POST', path, headers, body);+ expect((await post('/__live/lighting', {}, '{"preset":2}')).status).toBe(401);+ expect((await call(handler, 'GET', '/__live/lighting', { 'x-studio-token': token })).status).toBe(405);+ const bad = await post('/__live/lighting', { 'x-studio-token': token }, '{"preset":9}');+ expect(bad.status).toBe(400); expect(bad.json.error).toMatch(/preset/);+ expect((await post('/__live/lighting', { 'x-studio-token': `${token}x` }, '{"preset":2}')).status).toBe(401);+ const ok = await post('/__live/lighting', { 'x-studio-token': token }, '{"preset":2,"project":"demo"}');+ expect(ok.status).toBe(200); expect(ok.json).toEqual({ ok: true, preset: 2 });+ // One shortcut may switch an expression and a preset together.+ expect((await post('/__live/expression', { 'x-studio-token': token }, '{"expression":"sad"}')).json).toEqual({ ok: true, expression: 'sad' });+ expect((await post('/__live/lighting', { authorization: `Bearer ${token}` }, '{"preset":3}')).status).toBe(429);+ expect(presets).toEqual([{ preset: 2, project: 'demo' }]); expect(expressions).toEqual([{ expression: 'sad', project: null }]);+});++test('stored lighting presets keep eight slots and drop invalid entries', () => {+ const red = { ...DEFAULT_LIGHTING, enabled: true, color: 0xff2000, y: 0.95 };+ const presets = parseLightingPresets([red, null, { ...red, mode: 'glow' }, 'x', { color: 0x00ff00 }]);+ expect(presets).toHaveLength(8);+ expect(presets[0]).toEqual(red); expect(presets[1]).toBeNull(); expect(presets[2]).toBeNull(); expect(presets[3]).toBeNull();+ // Presets saved before newer options existed take defaults for the missing ones.+ expect(presets[4]).toEqual({ ...DEFAULT_LIGHTING, color: 0x00ff00 });+ expect(presets.slice(5)).toEqual([null, null, null]);+ expect(parseLightingPresets({ 0: red })).toEqual(Array(8).fill(null));+ expect(sameLighting(red, { ...red })).toBe(true); expect(sameLighting(red, { ...red, x: 0.3 })).toBe(false);+});