Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Switch expressions from other apps; collapse the Expression section

shinshin863227865390e0
diff --git a/README.ja.md b/README.ja.md
index 84e1bcb..c3cb4d5 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -84,7 +84,7 @@ npm run dev
![緑の背景にした配信用の画面](docs/images/ja/08-stream.png)
-「表情」のボタンか、キー1〜8で、笑顔、驚き、ウインクなどに切り替えられます。切り替えている間も、まばたきや口の動きはカメラとマイクに合わせて動きます([詳しく](docs/reference.md#expressions)、英語)。
+「表情」のボタンか、キー1〜8で、笑顔、驚き、ウインクなどに切り替えられます。切り替えている間も、まばたきや口の動きはカメラとマイクに合わせて動きます。macOS の「ショートカット」アプリや Stream Deck のボタンを使えば、他のアプリを操作中でも切り替えられます([設定方法](docs/reference.md#switching-expressions-from-other-apps)、英語)。
配信用画面の URL で指定できる項目、うまく動かないときの確認点、プライバシーについては[リファレンス](docs/reference.md#live-and-streaming)(英語)にまとめています。
diff --git a/README.md b/README.md
index 9c3e253..a7c1b4b 100644
--- a/README.md
+++ b/README.md
@@ -120,7 +120,9 @@ stopped or slowed while hidden, bring its window to the front.
![The stream view with a green background](docs/images/en/08-stream.png)
Switch expressions such as a smile, surprise or a wink with the **Expression** buttons or
-keys **1**–**8** while tracking continues ([details](docs/reference.md#expressions)).
+keys **1**–**8** while tracking continues. Keyboard shortcuts from macOS Shortcuts or a
+Stream Deck button can switch them while another app is in front
+([details](docs/reference.md#switching-expressions-from-other-apps)).
Stream view options, troubleshooting and privacy details are in the
[reference](docs/reference.md#live-and-streaming).
diff --git a/docs/reference.md b/docs/reference.md
index 02bd8e3..a29d86a 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -202,17 +202,61 @@ for software without transparency support.
### Expressions
-The Live page's **Expression** buttons switch the face to Neutral, Smile, Shy, Surprised,
-Half-lidded, Angry, Sad or Wink. Keys **1**–**8** do the same while the Live page is focused;
-press the same key or button again to return to Neutral. Keys typed into a form field are
-ignored. Because browsers receive keys only for the focused page, a key press from another app
-reaches the Live page only when its window is in front.
+The collapsed **Expression** section on the Live page switches the face to Neutral, Smile, Shy, Surprised,
+Half-lidded, Angry, Sad or Wink. Keys **1**–**8** do the same while the Live page is focused,
+even with the section closed; press the same key or button again to return to Neutral. Keys
+typed into a form field are ignored. The section title shows the current expression. Browsers
+receive keys only for the focused page; to switch while another app is in front, use
+[other apps](#switching-expressions-from-other-apps).
An expression is layered over tracking: blinking, gaze and the mouth keep following the camera
or microphone, while the eyes, brows and blush hold the expression. Switching fades smoothly.
An expression also reaches the stream view without the camera or microphone. Brows hidden
under bangs show less difference between Half-lidded, Angry and Sad.
+### Switching expressions from other apps
+
+Keyboard-shortcut apps and button panels such as Stream Deck can switch expressions while
+another app is in front. They send a request to the development server, which forwards it to
+the Live page; keep the Live page open.
+
+Open **Expression → Switch from other apps** on the Live page to copy the request URL and the
+token. Each request is:
+
+- `POST` to the request URL, for example `http://127.0.0.1:5173/__live/expression`
+- the header `X-Studio-Token: <token>` (or `Authorization: Bearer <token>`)
+- a JSON body such as `{"expression": "smile"}`. Names: `neutral`, `smile`, `shy`, `surprise`,
+ `halfLidded`, `angry`, `sad`, `wink`. Add `"project": "<name>"` to reach only the Live page
+ for that project.
+
+Sending the expression already shown returns to Neutral, so one shortcut can toggle it.
+
+**macOS Shortcuts**
+
+1. In the Shortcuts app, create a shortcut and add the **Get Contents of URL** action.
+2. Enter the request URL, then expand the action: set **Method** to **POST**, add the header
+ `X-Studio-Token` with the token, and set **Request Body** to **JSON** with the key
+ `expression` and the text value `smile`.
+3. In the shortcut's details, choose **Add Keyboard Shortcut** and press the keys to use.
+4. Repeat for each expression you want. Run the shortcut once from the app to check it.
+
+**Stream Deck**: use a plugin action that sends web requests in the background, set it to
+POST with the same URL, header and JSON body, and assign one button per expression. The
+built-in **Website** action opens a browser tab instead, so it does not work for this.
+
+**Command line** (also usable from AutoHotkey or other tools):
+
+```sh
+curl -X POST http://127.0.0.1:5173/__live/expression \
+ -H "X-Studio-Token: <token>" -H "Content-Type: application/json" \
+ -d '{"expression": "smile"}'
+```
+
+The token is stored in `projects/.expression-token`, which is excluded from version control.
+**Regenerate token** replaces it; shortcuts that use the old token then receive `401`. Only
+apps on this machine can reach the server. Websites open in the browser can neither read the
+token nor send the token header.
+
### Privacy
Camera video and microphone audio are processed in the browser and never leave your machine.
diff --git a/e2e/expressions.spec.ts b/e2e/expressions.spec.ts
index 234ed6c..8022f8c 100644
--- a/e2e/expressions.spec.ts
+++ b/e2e/expressions.spec.ts
@@ -10,31 +10,69 @@ test('expression keys and buttons drive the stream view without camera or microp
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', { receiveLiveParameters } = await import(path);
- Object.assign(window, { latest: null });
- receiveLiveParameters((data: { params: Record<string, number> }) => Object.assign(window, { latest: data.params }));
+ // Keep every message: another Live page on the shared development server may relay too.
+ Object.assign(window, { seen: [] });
+ receiveLiveParameters((data: { params: Record<string, number> }) => (window as unknown as { seen: Record<string, number>[] }).seen.push(data.params));
});
- const latest = () => stream.evaluate(() => (window as unknown as { latest: Record<string, number> | null }).latest);
- const group = page.getByRole('group', { name: 'Expression' });
+ const seen = () => stream.evaluate(() => (window as unknown as { seen: Record<string, number>[] }).seen);
+ const section = page.getByTestId('expression-section'), group = page.getByRole('group', { name: 'Expression' });
+ // Closed by default; keys still work while it is closed.
+ await expect(section).not.toHaveAttribute('open', '');
+ await page.locator('body').press('8');
+ await expect(section.locator('.expression-on')).toHaveText('Wink');
+ await page.locator('body').press('8');
+ await expect(section.locator('.expression-on')).toHaveCount(0);
+ await section.locator('summary').click();
await expect(group.getByRole('button')).toHaveCount(8);
await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
await page.locator('body').press('2');
await expect(group.getByRole('button', { name: /Smile/ })).toHaveAttribute('aria-pressed', 'true');
- await expect.poll(async () => (await latest())?.eyeSmile ?? 0).toBeGreaterThan(0.9);
- expect((await latest())!.blush).toBeGreaterThan(0.3);
+ await expect.poll(async () => (await seen()).some(p => p.eyeSmile > 0.9 && p.blush > 0.3)).toBe(true);
- // The same key returns to neutral; the fade-out reaches the stream before updates stop.
+ // The same key returns to neutral. (Whether updates stop after the fade is covered by unit
+ // tests: another Live page on the shared development server may be relaying at the same time.)
await page.locator('body').press('2');
await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
- await expect.poll(async () => (await latest())?.eyeSmile ?? 1).toBeLessThan(0.05);
// Keys typed into form fields do not switch expressions.
await page.getByRole('textbox', { name: 'Copy OBS URL' }).press('4');
await expect(group.getByRole('button', { name: /Neutral/ })).toHaveAttribute('aria-pressed', 'true');
await group.getByRole('button', { name: /Wink/ }).click();
- await expect.poll(async () => (await latest())?.eyeLOpen ?? 1).toBeLessThan(0.05);
+ await expect.poll(async () => (await seen()).some(p => p.eyeLOpen < 0.05 && p.eyeROpen > 0.5)).toBe(true);
await page.getByRole('button', { name: '日本語', exact: true }).click();
await expect(page.getByRole('group', { name: '表情' }).getByRole('button', { name: /ウインク/ })).toHaveAttribute('aria-pressed', 'true');
expect(outside).toEqual([]);
});
+
+test('other apps switch expressions with the token, and requests without it are refused', async ({ page, request }) => {
+ await page.goto('/live.html'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');
+ const section = page.getByTestId('expression-section'); await section.locator('summary').click();
+ const token = await section.getByRole('textbox', { name: /Token/ }).inputValue();
+ const url = await section.getByRole('textbox', { name: 'Request URL' }).inputValue();
+ expect(token).toMatch(/^[A-Za-z0-9_-]{32}$/); expect(new URL(url).pathname).toBe('/__live/expression');
+ const send = (body: unknown, headers: Record<string, string> = { 'X-Studio-Token': token }) => request.post(url, { data: body, headers });
+
+ expect((await send({ expression: 'surprise' })).status()).toBe(200);
+ await expect(section.locator('.expression-on')).toHaveText('Surprised');
+ await page.waitForTimeout(60);
+ // Sending the shown expression again returns to neutral, like pressing its key twice.
+ expect((await send({ expression: 'surprise' })).status()).toBe(200);
+ await expect(section.locator('.expression-on')).toHaveCount(0);
+ await page.waitForTimeout(60);
+ expect((await send({ expression: 'smile', project: 'sample-miko-qipao' }, { Authorization: `Bearer ${token}` })).status()).toBe(200);
+ await expect(section.locator('.expression-on')).toHaveText('Smile');
+ await page.waitForTimeout(60);
+ expect((await send({ expression: 'wink', project: 'another-project' })).status()).toBe(200);
+ await page.waitForTimeout(200); await expect(section.locator('.expression-on')).toHaveText('Smile');
+
+ expect((await send({ expression: 'smile' }, {})).status()).toBe(401);
+ expect((await send({ expression: 'smile' }, { 'X-Studio-Token': 'x'.repeat(32) })).status()).toBe(401);
+ await page.waitForTimeout(60);
+ for (const body of [{ expression: 'toString' }, { expression: 'smile', extra: 1 }, ['smile'], { expression: 'smile', project: '../x' }]) expect((await send(body)).status()).toBe(400);
+ expect((await request.get(url, { headers: { 'X-Studio-Token': token } })).status()).toBe(405);
+ // The token is readable only with the Live page's own request header, and no CORS is granted.
+ const tokenResponse = await request.get(new URL('/__live/expression-token', url).href);
+ expect(tokenResponse.status()).toBe(403); expect(tokenResponse.headers()['access-control-allow-origin']).toBeUndefined();
+});
diff --git a/src/editor/Icon.tsx b/src/editor/Icon.tsx
index a9896d3..976931c 100644
--- a/src/editor/Icon.tsx
+++ b/src/editor/Icon.tsx
@@ -11,6 +11,7 @@ const paths = {
copy: 'M8 8h13v13H8V8Z M16 8V3H3v13h5',
live: 'M3 7h12v10H3V7Z M15 10l6-3v10l-6-3',
external: 'M14 4h6v6 M20 4l-9 9 M18 14v6H4V6h6',
+ face: 'M12 3a9 9 0 1 1 0 18 9 9 0 0 1 0-18Z M9 10h.01 M15 10h.01 M8.5 14.5a4 4 0 0 0 7 0',
pose: 'M12 3a2 2 0 1 1 0 4 2 2 0 0 1 0-4Z M5 9l7 1 7-1 M12 10v5 M8 21l4-6 4 6',
mouth: 'M3 12c3-4 6-4 9-2 3-2 6-2 9 2-3 5-15 5-18 0Z M3 12h18',
brush: 'M4 20h4L19 9l-4-4L4 16v4Z M13 7l4 4',
diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsx
index b0c59d2..b898b3f 100644
--- a/src/live/LiveApp.tsx
+++ b/src/live/LiveApp.tsx
@@ -9,7 +9,8 @@ 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, sendLighting } from './relay';
+import { createLiveSender, receiveExpression, sendLighting } from './relay';
+import { EXPRESSION_TOKEN_PATH } from './expression-protocol';
export function LiveApp() {
const { language, setLanguage } = useI18n(), t = liveText[language];
@@ -17,6 +18,7 @@ export function LiveApp() {
const [lightingOpen, setLightingOpen] = useState(false);
const [expression, setExpression] = useState<LiveExpression>('neutral');
const expressionRef = useRef(expression); expressionRef.current = expression;
+ const [remote, setRemote] = useState<{ url: string; token: string } | null>(null), [remoteCopied, setRemoteCopied] = useState<'url' | 'token' | null>(null);
const [options, setOptions] = useState<TrackingOptions>({ mirror: true, sensitivity: 1, smoothing: 0.35 });
const [cameraState, setCameraState] = useState<CameraState>('stopped');
const [micState, setMicState] = useState<MicState>('micOff');
@@ -80,6 +82,13 @@ export function LiveApp() {
}, [settings.project]);
const changeLighting = (lighting: typeof settings.lighting) => setSettings(current => ({ ...current, lighting }));
useEffect(() => { avatarRef.current?.setExpression(expression); }, [expression]);
+ useEffect(() => receiveExpression(settings.project, name => name === 'neutral' ? setExpression('neutral') : toggleExpression(name)), [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))
+ .catch(() => setRemote(null));
+ useEffect(() => { void loadRemote('GET'); }, []);
+ const copyRemote = (kind: 'url' | 'token', value: string) => { void navigator.clipboard.writeText(value).then(() => { setRemoteCopied(kind); setTimeout(() => setRemoteCopied(null), 1500); }).catch(() => undefined); };
const toggleExpression = (name: LiveExpression) => setExpression(current => current === name ? 'neutral' : name);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
@@ -123,9 +132,6 @@ export function LiveApp() {
<select aria-label={t.microphone} value={micId} disabled={micActive} onChange={event => setMicId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'audioinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.microphone} ${i + 1}`}</option>)}</select>
<label>{t.gain}<input type="range" min="0.25" max="5" step="0.05" value={gain} onChange={event => setGain(Number(event.target.value))} /></label><small role="status">{t[micState]}</small>
</section>
- <section><h2>{t.expression}</h2><div className="expression-buttons" role="group" aria-label={t.expression}>
- {LIVE_EXPRESSIONS.map((name, i) => <button key={name} type="button" aria-pressed={expression === name} aria-keyshortcuts={String(i + 1)} onClick={() => toggleExpression(name)}><kbd>{i + 1}</kbd>{t[name]}</button>)}
- </div><small>{t.expressionHint}</small></section>
<section><h2>{t.background}</h2><select aria-label={t.background} value={settings.background} onChange={event => setSettings(current => ({ ...current, background: backgroundColor(event.target.value) }))}>
<option value="transparent">{t.transparent}</option><option value="#00ff00">{t.green}</option><option value="#0000ff">{t.blue}</option>{!['transparent', '#00ff00', '#0000ff'].includes(settings.background) && <option value={settings.background}>{t.custom}</option>}
</select><label>{t.custom}<input type="color" value={settings.background === 'transparent' ? '#ffffff' : settings.background} onChange={event => setSettings(current => ({ ...current, background: event.target.value }))} /></label>
@@ -134,6 +140,20 @@ export function LiveApp() {
<a className="live-open" href={url} target="_blank" rel="noreferrer">{t.openStream}</a></div>
{copyState && <p role="status">{t[copyState]}</p>}<input className="obs-url" aria-label={t.obs} readOnly value={url} onFocus={event => event.target.select()} /><small>{t.obsHelp}</small>
</section>
+ <details className="live-expression" data-testid="expression-section">
+ <summary><Icon name="face" />{t.expression}{expression !== 'neutral' && <span className="expression-on">{t[expression]}</span>}</summary>
+ <div className="live-expression-body"><div className="expression-buttons" role="group" aria-label={t.expression}>
+ {LIVE_EXPRESSIONS.map((name, i) => <button key={name} type="button" aria-pressed={expression === name} aria-keyshortcuts={String(i + 1)} onClick={() => toggleExpression(name)}><kbd>{i + 1}</kbd>{t[name]}</button>)}
+ </div><small>{t.expressionHint}</small>
+ <h3>{t.remoteTitle}</h3><p className="remote-help">{t.remoteHelp}</p>
+ {remote ? <>
+ <label>{t.remoteUrl}<span className="remote-field"><input readOnly value={remote.url} onFocus={event => event.target.select()} /><button type="button" onClick={() => copyRemote('url', remote.url)}>{remoteCopied === 'url' ? t.copiedShort : t.copy}</button></span></label>
+ <label>{t.remoteToken}<span className="remote-field"><input readOnly value={remote.token} onFocus={event => event.target.select()} /><button type="button" onClick={() => copyRemote('token', remote.token)}>{remoteCopied === 'token' ? t.copiedShort : t.copy}</button></span></label>
+ <small>{t.remoteNames}</small>
+ <div className="remote-actions"><button type="button" onClick={() => { void loadRemote('POST'); }}>{t.regenerate}</button><small>{t.regenerateHelp}</small></div>
+ </> : <small>{t.remoteUnavailable}</small>}
+ <a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#switching-expressions-from-other-apps" target="_blank" rel="noreferrer">{t.remoteDocs}</a></div>
+ </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>
<LightingControls value={settings.lighting} onChange={changeLighting} language={language} />
diff --git a/src/live/expression-protocol.ts b/src/live/expression-protocol.ts
new file mode 100644
index 0000000..f68cdcb
--- /dev/null
+++ b/src/live/expression-protocol.ts
@@ -0,0 +1,20 @@
+// Expression 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 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 }
+
+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 {
+ 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 (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 };
+}
diff --git a/src/live/i18n.ts b/src/live/i18n.ts
index 0e3ff5a..9db5ec3 100644
--- a/src/live/i18n.ts
+++ b/src/live/i18n.ts
@@ -19,6 +19,10 @@ export const liveEn = {
liveUnavailable: 'Open this project from the local project list before using Live.',
expression: 'Expression', expressionHint: 'While this page is focused, keys 1–8 switch expressions. Press the same key again to return to neutral.',
neutral: 'Neutral', smile: 'Smile', shy: 'Shy', surprise: 'Surprised', halfLidded: 'Half-lidded', angry: 'Angry', sad: 'Sad', wink: 'Wink',
+ remoteTitle: 'Switch from other apps', remoteHelp: 'Keyboard-shortcut apps and button panels can switch expressions even when this page is not in front. Send a POST request with the token header and a JSON body such as {"expression": "smile"}.',
+ 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. Sending the expression already shown returns to neutral.',
+ remoteDocs: 'Setup for macOS Shortcuts and Stream Deck', remoteUnavailable: 'Available while the local development server is running.',
};
const liveJa: typeof liveEn = {
title: '配信', back: 'エディタに戻る', camera: 'カメラ', device: 'デバイス', defaultDevice: '既定のデバイス',
@@ -41,6 +45,10 @@ const liveJa: typeof liveEn = {
liveUnavailable: '配信するには、エディタのローカルプロジェクト一覧からこのプロジェクトを開いてください。',
expression: '表情', expressionHint: 'この画面を操作している間は、キー1〜8で表情を切り替えられます。同じキーをもう一度押すと通常に戻ります。',
neutral: '通常', smile: '笑顔', shy: '照れ', surprise: '驚き', halfLidded: 'ジト目', angry: '怒り', sad: '悲しみ', wink: 'ウインク',
+ remoteTitle: '他のアプリから切り替える', remoteHelp: 'キーボードショートカットのアプリやボタン操作盤から、この画面が前面になくても表情を切り替えられます。トークンをヘッダーに付けて、{"expression": "smile"} のような JSON を POST で送ってください。',
+ remoteUrl: '送信先URL', remoteToken: 'トークン(X-Studio-Token ヘッダー)', copy: 'コピー', copiedShort: 'コピーしました', regenerate: 'トークンを作り直す',
+ regenerateHelp: '作り直すと、古いトークンを使っているショートカットは動かなくなります。', remoteNames: '表情の名前: neutral, smile, shy, surprise, halfLidded, angry, sad, wink。表示中の表情をもう一度送ると通常に戻ります。',
+ remoteDocs: 'macOSのショートカットとStream Deckでの設定方法', remoteUnavailable: 'ローカルの開発サーバーで起動しているときに使えます。',
};
const liveZh: typeof liveEn = {
title: '直播', back: '返回编辑器', camera: '摄像头', device: '设备', defaultDevice: '默认设备',
@@ -63,5 +71,9 @@ const liveZh: typeof liveEn = {
liveUnavailable: '请先从本地项目列表打开此项目,再使用直播功能。',
expression: '表情', expressionHint: '在此页面操作时,可用 1–8 键切换表情。再按一次同一键恢复普通表情。',
neutral: '普通', smile: '微笑', shy: '害羞', surprise: '惊讶', halfLidded: '半眯眼', angry: '生气', sad: '难过', wink: '眨眼',
+ remoteTitle: '从其他应用切换', remoteHelp: '即使此页面不在前台,也可以通过快捷键应用或按键面板切换表情。请在请求头中附上令牌,用 POST 发送 {"expression": "smile"} 这样的 JSON。',
+ remoteUrl: '请求 URL', remoteToken: '令牌(X-Studio-Token 请求头)', copy: '复制', copiedShort: '已复制', regenerate: '重新生成令牌',
+ regenerateHelp: '重新生成后,使用旧令牌的快捷方式将无法使用。', remoteNames: '表情名称:neutral, smile, shy, surprise, halfLidded, angry, sad, wink。再次发送当前表情会恢复普通。',
+ remoteDocs: 'macOS 快捷指令和 Stream Deck 的设置方法', remoteUnavailable: '在本地开发服务器运行时可用。',
};
export const liveText = { en: liveEn, ja: liveJa, zh: liveZh };
diff --git a/src/live/live.css b/src/live/live.css
index f913c77..9e78a41 100644
--- a/src/live/live.css
+++ b/src/live/live.css
@@ -45,3 +45,16 @@ input[type="color"] { width: 100%; height: 32px; border: 0; padding: 0; }
.expression-buttons button { display: flex; align-items: center; gap: 8px; text-align: left; }
.expression-buttons button[aria-pressed="true"] { border-color: #3977d8; background: #e8f0fd; color: #1d4f9c; font-weight: 600; }
.expression-buttons kbd { min-width: 1.4em; padding: 0 4px; border: 1px solid #c8d3e2; border-radius: 4px; font: 11px/1.5 ui-monospace, monospace; text-align: center; color: #5a6a80; background: #f6f8fb; }
+.live-expression { border: 1px solid #d5dfeb; border-radius: 12px; background: white; }
+.live-expression > summary { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 12px 16px; font-weight: 600; list-style: none; }
+.live-expression > summary::-webkit-details-marker { display: none; }
+.live-expression > summary::before { content: '▸'; }
+.live-expression[open] > summary::before { content: '▾'; }
+.expression-on { margin-left: auto; padding: 1px 7px; border-radius: 999px; background: #e8f0fd; color: #1d4f9c; font-size: 11px; font-weight: 600; }
+.live-expression-body { padding: 0 16px 16px; }
+.live-expression-body h3 { margin: 16px 0 4px; font-size: 13px; }
+.remote-help { margin: 0 0 4px; font-size: 12px; color: #4a5a70; }
+.remote-field { display: flex; gap: 6px; }
+.remote-field input { flex: 1; min-width: 0; font: 12px ui-monospace, monospace; padding: 6px 8px; border: 1px solid #c8d3e2; border-radius: 7px; }
+.remote-actions { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; margin: 10px 0; }
+.live-expression-body small { display: block; color: #5a6a80; }
diff --git a/src/live/relay.ts b/src/live/relay.ts
index b3a2fb0..da30f02 100644
--- a/src/live/relay.ts
+++ b/src/live/relay.ts
@@ -1,6 +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';
export function createLiveSender(project: string) {
let sent = -Infinity;
@@ -24,3 +25,10 @@ export function receiveLighting(project: string, callback: (value: LightingSetti
import.meta.hot?.on(LIGHTING_EVENT, receive);
return () => import.meta.hot?.off(LIGHTING_EVENT, receive);
}
+
+/** Expressions sent from other apps; a message without a project applies to every Live page. */
+export function receiveExpression(project: string, callback: (expression: RemoteExpression) => void) {
+ const receive = (data: unknown) => { const message = expressionMessage(data); if (message && (message.project === null || message.project === project)) callback(message.expression); };
+ import.meta.hot?.on(EXPRESSION_EVENT, receive);
+ return () => import.meta.hot?.off(EXPRESSION_EVENT, receive);
+}
diff --git a/src/server/expression-remote.ts b/src/server/expression-remote.ts
new file mode 100644
index 0000000..1c588ed
--- /dev/null
+++ b/src/server/expression-remote.ts
@@ -0,0 +1,68 @@
+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';
+
+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.
+ */
+export function expressionRemote(tokenFile: string, broadcast: (message: ExpressionMessage) => void) {
+ let token: string | null = null, last = -Infinity;
+ 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. */ }
+ return save(newToken());
+ };
+ const save = async (value: string) => {
+ await mkdir(dirname(tokenFile), { recursive: true });
+ await writeFile(tokenFile, `${value}\n`, { mode: 0o600 }); await chmod(tokenFile, 0o600);
+ return (token = value);
+ };
+ const json = (res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}) => {
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers }); res.end(JSON.stringify(body));
+ };
+ const readBody = (req: IncomingMessage) => new Promise<string | null>(resolve => {
+ let size = 0; const chunks: Buffer[] = [];
+ // Oversized bodies are drained and dropped so the response can still be written.
+ req.on('data', (chunk: Buffer) => { size += chunk.length; if (size <= MAX_BODY) chunks.push(chunk); });
+ req.on('end', () => resolve(size > MAX_BODY ? null : Buffer.concat(chunks).toString('utf8')));
+ req.on('error', () => resolve(null));
+ });
+ const matches = (given: string | string[] | undefined, expected: string) => {
+ const header = Array.isArray(given) ? given[0] : given ?? '';
+ const value = header.startsWith('Bearer ') ? header.slice(7) : header;
+ const a = Buffer.from(value), b = Buffer.from(expected);
+ return 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; }
+ try {
+ if (path === EXPRESSION_TOKEN_PATH) {
+ // Only the Live page itself reads or renews the token: a browser sends this custom header
+ // cross-site only after a CORS preflight, which this server never approves.
+ if (req.headers['x-studio-request'] !== '1') { json(res, 403, { error: 'Forbidden.' }); return; }
+ if (req.method === 'GET') { json(res, 200, { token: await load(), path: EXPRESSION_PATH }); return; }
+ if (req.method === 'POST') { json(res, 200, { token: await save(newToken()), path: EXPRESSION_PATH }); return; }
+ json(res, 405, { error: 'Method not allowed.' }, { allow: 'GET, POST' }); return;
+ }
+ if (req.method !== 'POST') { json(res, 405, { error: 'Use POST.' }, { allow: 'POST' }); return; }
+ if (!matches(req.headers[TOKEN_HEADER] ?? req.headers.authorization, await load())) { json(res, 401, { error: 'Missing or wrong token.' }); return; }
+ const 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 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.' }); }
+ };
+}
diff --git a/src/server/live-relay.ts b/src/server/live-relay.ts
index 502f90f..e388de3 100644
--- a/src/server/live-relay.ts
+++ b/src/server/live-relay.ts
@@ -1,11 +1,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 { expressionRemote } from './expression-remote';
-export function liveRelay(): Plugin {
+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)));
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.ts
new file mode 100644
index 0000000..496f7f0
--- /dev/null
+++ b/tests/expression-remote.test.ts
@@ -0,0 +1,59 @@
+import { expect, test } from 'vitest';
+import { mkdtemp, readFile, stat, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+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 { OVERLAY_EXPRESSIONS } from '../src/engine/expression-overlay.js';
+
+async function call(handler: ReturnType<typeof expressionRemote>, method: string, url: string, headers: Record<string, string> = {}, body = '') {
+ const req = Object.assign(Readable.from(body ? [Buffer.from(body)] : []), { method, url, headers }) as unknown as IncomingMessage;
+ let status = 0, payload = '', head: Record<string, string> = {}, passed = false;
+ const res = { writeHead: (s: number, h: Record<string, string>) => { status = s; head = h; }, end: (b: string) => { payload = b; } } as unknown as ServerResponse;
+ await handler(req, res, () => { passed = true; });
+ return { status, head, passed, json: payload ? JSON.parse(payload) : null };
+}
+
+test('the remote accepts the same expressions as the Live page', () => {
+ expect([...REMOTE_EXPRESSIONS]).toEqual(Object.keys(OVERLAY_EXPRESSIONS));
+ expect(expressionMessage({ expression: 'smile' })).toEqual({ expression: 'smile', project: null });
+ for (const bad of [null, [], 'smile', { expression: 'constructor' }, { expression: 'smile', x: 1 }, { expression: 'smile', project: '../a' }, { expression: 'smile', project: 3 }]) expect(expressionMessage(bad)).toBeNull();
+});
+
+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));
+ 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' });
+ expect(first.status).toBe(200); expect(first.head['access-control-allow-origin']).toBeUndefined();
+ const token = first.json.token as string;
+ expect(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);
+ 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);
+ expect((await post({}, '{"expression":"smile"}')).status).toBe(401);
+ expect((await post({ 'x-studio-token': `${token}x` }, '{"expression":"smile"}')).status).toBe(401);
+ expect((await call(handler, 'GET', '/__live/expression', { 'x-studio-token': token })).status).toBe(405);
+ expect((await post({ 'x-studio-token': token }, 'not json')).status).toBe(400);
+ expect((await post({ 'x-studio-token': token }, JSON.stringify({ expression: 'smile', pad: 'x'.repeat(2000) }))).status).toBe(413);
+ expect((await post({ 'x-studio-token': token }, '{"expression":"smile","project":"demo"}')).status).toBe(200);
+ expect(sent).toEqual([{ expression: 'smile', project: 'demo' }]);
+ expect((await post({ authorization: `Bearer ${token}` }, '{"expression":"wink"}')).status).toBe(429);
+
+ const renewed = await call(handler, 'POST', '/__live/expression-token', { 'x-studio-request': '1' });
+ expect(renewed.json.token).not.toBe(token);
+ await new Promise(resolve => setTimeout(resolve, 60));
+ expect((await post({ 'x-studio-token': token }, '{"expression":"wink"}')).status).toBe(401);
+ expect((await post({ authorization: `Bearer ${renewed.json.token}` }, '{"expression":"wink"}')).status).toBe(200);
+
+ // 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' });
+ expect(fresh.json.token).toMatch(/^[A-Za-z0-9_-]{32}$/);
+});
diff --git a/tests/live-relay.test.ts b/tests/live-relay.test.ts
index 3f9621b..3ef5ac5 100644
--- a/tests/live-relay.test.ts
+++ b/tests/live-relay.test.ts
@@ -27,8 +27,8 @@ test('stream isolates projects and smoothly returns to idle after one second wit
test('server rebroadcasts validated numbers at most 60 times per second per socket', () => {
const handlers = new Map<string, (data: unknown, client: WebSocketClient) => void>();
const send = vi.fn();
- const server = { ws: { on: (event: string, handler: (data: unknown, client: WebSocketClient) => void) => handlers.set(event, handler), send } } as unknown as ViteDevServer;
- const plugin = liveRelay();
+ const server = { middlewares: { use: vi.fn() }, ws: { on: (event: string, handler: (data: unknown, client: WebSocketClient) => void) => handlers.set(event, handler), send } } as unknown as ViteDevServer;
+ const plugin = liveRelay('/unused');
if (typeof plugin.configureServer !== 'function') throw new Error('Missing configureServer');
plugin.configureServer.call({} as never, server);
const receive = handlers.get(LIVE_EVENT)!, socket = {} as WebSocketClient['socket'];
diff --git a/vite.config.ts b/vite.config.ts
index f7d8503..9000e56 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -7,7 +7,7 @@ import { mediapipeAssets } from './src/server/mediapipe-assets';
import { liveRelay } from './src/server/live-relay';
export default defineConfig({
server: { host: '127.0.0.1' },
- plugins: [react(), localProjectsPlugin(fileURLToPath(new URL('.', import.meta.url))), mediapipeAssets(fileURLToPath(new URL('.', import.meta.url))), liveRelay(), {
+ plugins: [react(), localProjectsPlugin(fileURLToPath(new URL('.', import.meta.url))), mediapipeAssets(fileURLToPath(new URL('.', import.meta.url))), liveRelay(fileURLToPath(new URL('.', import.meta.url))), {
name: 'sample-rig',
resolveId(id) {
if (id === 'virtual:sample-rig') return '\0sample-rig';