Skip to content

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

Follow one Live page per project and warn about duplicate tabs

shinshin868cbe89c29004
diff --git a/docs/reference.md b/docs/reference.md
index f109cc3..f4721a3 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -296,6 +296,9 @@ upgrading it.
- **Movement is too small or jittery**: raise **Sensitivity**, or raise **Smoothing**.
Calibrate again while facing the camera with a relaxed face.
- **Left and right are swapped**: toggle **Mirror**.
+- **The avatar flickers or an expression keeps flipping**: the project is probably open in two
+ Live tabs; the Live page shows a warning when it is. The stream view follows one of them,
+ but switches from other apps reach both. Close the tab you are not using.
- **The stream view stays idle**: keep the Live page open and running, and make sure both pages
use the same `project`.
diff --git a/e2e/expressions.spec.ts b/e2e/expressions.spec.ts
index 8022f8c..0b6fd2d 100644
--- a/e2e/expressions.spec.ts
+++ b/e2e/expressions.spec.ts
@@ -76,3 +76,13 @@ test('other apps switch expressions with the token, and requests without it are
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();
});
+
+test('a second Live tab for the same project shows a warning on both, and closing one clears it', async ({ context, page }) => {
+ await page.goto('/live.html'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');
+ await expect(page.getByTestId('duplicate-live-page')).toHaveCount(0);
+ const second = await context.newPage(); await second.goto('/live.html'); await expect(second.locator('canvas')).toHaveAttribute('data-state', 'ready');
+ await expect(second.getByTestId('duplicate-live-page')).toBeVisible({ timeout: 5000 });
+ await expect(page.getByTestId('duplicate-live-page')).toBeVisible({ timeout: 5000 });
+ await second.close();
+ await expect(page.getByTestId('duplicate-live-page')).toHaveCount(0, { timeout: 8000 });
+});
diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsx
index b898b3f..0f04e7b 100644
--- a/src/live/LiveApp.tsx
+++ b/src/live/LiveApp.tsx
@@ -9,13 +9,14 @@ 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 } from './relay';
+import { createLiveSender, receiveExpression, sendLighting, watchDuplicateLivePages } from './relay';
import { EXPRESSION_TOKEN_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 [duplicatePage, setDuplicatePage] = 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);
@@ -82,6 +83,7 @@ export function LiveApp() {
}, [settings.project]);
const changeLighting = (lighting: typeof settings.lighting) => setSettings(current => ({ ...current, lighting }));
useEffect(() => { avatarRef.current?.setExpression(expression); }, [expression]);
+ useEffect(() => watchDuplicateLivePages(settings.project, setDuplicatePage), [settings.project]);
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)
@@ -114,6 +116,7 @@ export function LiveApp() {
{lightingOpen && <LightHandle value={settings.lighting} onChange={changeLighting} language={language} />}
</div><p role="status" className={viewState === 'projectError' ? 'live-error' : ''}>{t[viewState]} · {settings.project}</p></section>
<aside className="live-controls">
+ {duplicatePage && <p role="alert" className="live-warning" data-testid="duplicate-live-page">{t.duplicatePage}</p>}
<section><h2>{t.camera}</h2><label>{t.device}<select aria-label={t.camera} value={cameraId} disabled={cameraActive} onChange={event => setCameraId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'videoinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.camera} ${i + 1}`}</option>)}</select></label>
<div className="live-buttons"><button className="live-primary" disabled={!cameraActive && viewState !== 'ready'} onClick={() => {
setCalibrated(false); pose.current.reset();
diff --git a/src/live/i18n.ts b/src/live/i18n.ts
index 9db5ec3..2e30b6f 100644
--- a/src/live/i18n.ts
+++ b/src/live/i18n.ts
@@ -19,6 +19,7 @@ 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',
+ duplicatePage: 'This project is also open in another Live tab. The stream view follows only one of them, and switches from other apps reach both. Close the tab you are not using.',
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.',
@@ -45,6 +46,7 @@ const liveJa: typeof liveEn = {
liveUnavailable: '配信するには、エディタのローカルプロジェクト一覧からこのプロジェクトを開いてください。',
expression: '表情', expressionHint: 'この画面を操作している間は、キー1〜8で表情を切り替えられます。同じキーをもう一度押すと通常に戻ります。',
neutral: '通常', smile: '笑顔', shy: '照れ', surprise: '驚き', halfLidded: 'ジト目', angry: '怒り', sad: '悲しみ', wink: 'ウインク',
+ duplicatePage: 'このプロジェクトの配信画面が別のタブでも開いています。配信用画面はどちらか一方の動きだけを表示し、他のアプリからの切り替えは両方に届きます。使わないタブは閉じてください。',
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。表示中の表情をもう一度送ると通常に戻ります。',
@@ -71,6 +73,7 @@ const liveZh: typeof liveEn = {
liveUnavailable: '请先从本地项目列表打开此项目,再使用直播功能。',
expression: '表情', expressionHint: '在此页面操作时,可用 1–8 键切换表情。再按一次同一键恢复普通表情。',
neutral: '普通', smile: '微笑', shy: '害羞', surprise: '惊讶', halfLidded: '半眯眼', angry: '生气', sad: '难过', wink: '眨眼',
+ duplicatePage: '此项目还在另一个直播标签页中打开。直播画面只跟随其中一个,其他应用发来的切换会同时到达两个页面。请关闭不用的标签页。',
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。再次发送当前表情会恢复普通。',
diff --git a/src/live/live.css b/src/live/live.css
index 9e78a41..26e07a6 100644
--- a/src/live/live.css
+++ b/src/live/live.css
@@ -58,3 +58,4 @@ input[type="color"] { width: 100%; height: 32px; border: 0; padding: 0; }
.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; }
+.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; }
diff --git a/src/live/protocol.ts b/src/live/protocol.ts
index eae01af..96998f2 100644
--- a/src/live/protocol.ts
+++ b/src/live/protocol.ts
@@ -1,11 +1,12 @@
import { parameterRanges } from './tracking';
export const LIVE_EVENT = 'studio:live-params';
-export interface LiveMessage { project: string; params: Record<string, number>; t: number }
+export interface LiveMessage { project: string; params: Record<string, number>; t: number; sender?: string }
export function liveMessage(input: unknown): LiveMessage | null {
if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
const data = input as Record<string, unknown>;
- if (Object.keys(data).some(key => !['project', 'params', 't'].includes(key)) ||
+ if (Object.keys(data).some(key => !['project', 'params', 't', 'sender'].includes(key)) ||
+ (data.sender !== undefined && (typeof data.sender !== 'string' || !/^[a-z0-9]{8,32}$/.test(data.sender))) ||
typeof data.project !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(data.project) ||
typeof data.t !== 'number' || !Number.isFinite(data.t) || data.t < 0 ||
!data.params || typeof data.params !== 'object' || Array.isArray(data.params)) return null;
@@ -17,7 +18,7 @@ export function liveMessage(input: unknown): LiveMessage | null {
if (!range || typeof value !== 'number' || !Number.isFinite(value)) return null;
params[key] = Math.max(range[0], Math.min(range[1], value));
}
- return { project: data.project, params, t: data.t };
+ return { project: data.project, params, t: data.t, ...(typeof data.sender === 'string' ? { sender: data.sender } : {}) };
}
export class LivePose {
@@ -25,10 +26,14 @@ export class LivePose {
private params: Record<string, number> = {};
private weight = 0;
constructor(private project: string) {}
+ private sender: string | undefined;
receive(input: unknown, now: number) {
const message = liveMessage(input);
if (!message || message.project !== this.project) return false;
- this.params = message.params; this.received = now; return true;
+ // With two Live pages open for one project, follow one of them until it goes quiet;
+ // alternating between their poses makes the avatar flicker.
+ if (message.sender !== this.sender && now - this.received <= 1000) return false;
+ this.sender = message.sender; this.params = message.params; this.received = now; return true;
}
sample(now: number, dt: number) {
// Sender timestamps come from another browser clock. Use local receipt time.
diff --git a/src/live/relay.ts b/src/live/relay.ts
index da30f02..a687259 100644
--- a/src/live/relay.ts
+++ b/src/live/relay.ts
@@ -3,11 +3,11 @@ 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) {
+export function createLiveSender(project: string, sender = randomSender()) {
let sent = -Infinity;
return (params: Record<string, number>, now: number) => {
if (!import.meta.hot || now - sent < 1000 / 60) return;
- const message = liveMessage({ project, params, t: now });
+ const message = liveMessage({ project, params, t: now, sender });
if (message) { import.meta.hot.send(LIVE_EVENT, message); sent = now; }
};
}
@@ -32,3 +32,24 @@ export function receiveExpression(project: string, callback: (expression: Remote
import.meta.hot?.on(EXPRESSION_EVENT, receive);
return () => import.meta.hot?.off(EXPRESSION_EVENT, receive);
}
+
+export function randomSender() {
+ return Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('');
+}
+
+/** Tells Live pages in this browser when another one has the same project open. */
+export function watchDuplicateLivePages(project: string, onChange: (duplicate: boolean) => void) {
+ if (typeof BroadcastChannel === 'undefined') return () => undefined;
+ const id = randomSender(), channel = new BroadcastChannel('mesh-avatar-live-pages');
+ let seen = -Infinity, duplicate = false;
+ const update = () => { const next = performance.now() - seen < 5000; if (next !== duplicate) onChange(duplicate = next); };
+ channel.onmessage = (event: MessageEvent) => {
+ const data = event.data as { project?: unknown; id?: unknown; leaving?: unknown } | null;
+ if (!data || data.project !== project || data.id === id) return;
+ seen = data.leaving === true ? -Infinity : performance.now(); update();
+ };
+ const announce = () => channel.postMessage({ project, id });
+ announce();
+ const timer = setInterval(() => { announce(); update(); }, 2000);
+ return () => { clearInterval(timer); channel.postMessage({ project, id, leaving: true }); channel.close(); };
+}
diff --git a/tests/live-relay.test.ts b/tests/live-relay.test.ts
index 3ef5ac5..c8357fd 100644
--- a/tests/live-relay.test.ts
+++ b/tests/live-relay.test.ts
@@ -48,3 +48,17 @@ test('server rebroadcasts validated numbers at most 60 times per second per sock
expect(send).toHaveBeenCalledTimes(count + 1);
} finally { clock.mockRestore(); }
});
+
+test('the stream follows one Live page until it goes quiet, so two open pages do not flicker', () => {
+ const pose = new LivePose('p');
+ const from = (sender: string, mouthOpen: number) => ({ project: 'p', params: { mouthOpen }, t: 1, sender });
+ expect(pose.receive(from('aaaaaaaa', 0.6), 0)).toBe(true);
+ expect(pose.receive(from('bbbbbbbb', 0), 16)).toBe(false);
+ expect(pose.sample(20, 0.016).params.mouthOpen).toBe(0.6);
+ expect(pose.receive(from('aaaaaaaa', 0.5), 33)).toBe(true);
+ // After the followed page has been silent for a second, the other page takes over.
+ expect(pose.receive(from('bbbbbbbb', 0), 1100)).toBe(true);
+ expect(pose.sample(1110, 0.016).params.mouthOpen).toBe(0);
+ for (const sender of ['UPPER123', 'short', 'x'.repeat(33), 5]) expect(liveMessage({ ...from('aaaaaaaa', 0), sender })).toBeNull();
+ expect(liveMessage({ project: 'p', params: { mouthOpen: 0 }, t: 1 })).toEqual({ project: 'p', params: { mouthOpen: 0 }, t: 1 });
+});