Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: update Laya runtime status without polling (#8536)

[._.]/ Adam Eivy1152191c3e2a
diff --git a/client/src/components/models/LayaMlxPanel.jsx b/client/src/components/models/LayaMlxPanel.jsx
index 4bc5c29137..08026c176f 100644
--- a/client/src/components/models/LayaMlxPanel.jsx
+++ b/client/src/components/models/LayaMlxPanel.jsx
@@ -1,9 +1,12 @@
-import { useCallback, useRef, useState } from 'react';
+import { useState } from 'react';
import { getLayaStatus, installLaya, scoreLaya, updateInstanceFeature } from '../../services/api';
import { publishInstanceFeatures, useInstanceFeatures } from '../../hooks/useInstanceFeatures';
-import { useAutoRefetch } from '../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../hooks/useSocketResource';
import { formatCount, formatPercent } from '../../utils/formatters';
+const STATUS_EVENTS = ['laya:status'];
+const readStatus = () => getLayaStatus({ silent: true });
+
const ERRORS = {
'laya-unsupported': 'Laya-MLX requires Apple Silicon and macOS 14 or newer. Jev remains available on other platforms.',
'laya-not-ready': 'Install or repair Laya-MLX before scoring.',
@@ -20,8 +23,6 @@ const errorLabel = code => Object.hasOwn(ERRORS, code) ? ERRORS[code] : 'Laya co
export default function LayaMlxPanel() {
const { features, error: featureError } = useInstanceFeatures();
const feature = features?.find(item => item.id === 'laya-mlx');
- const statusGeneration = useRef(0);
- const [status, setStatus] = useState(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [premise, setPremise] = useState('');
@@ -29,13 +30,7 @@ export default function LayaMlxPanel() {
const [optionsText, setOptionsText] = useState('');
const [margin, setMargin] = useState('0.15');
const [result, setResult] = useState(null);
- const load = useCallback(() => {
- const requested = ++statusGeneration.current;
- return getLayaStatus({ silent: true }).then(value => {
- if (statusGeneration.current === requested) setStatus(value);
- });
- }, []);
- const { error: statusError, refetch } = useAutoRefetch(load, 5000, { enabled: !busy });
+ const { data: status, error: statusError, refetch, updateData: setStatus } = useSocketResource(readStatus, { events: STATUS_EVENTS });
const options = optionsText.split('\n').map(value => value.trim()).filter(Boolean);
const valid = premise.trim() && instructions.trim() && options.length >= 2 && options.length <= 12
&& new Set(options).size === options.length && options.every(option => option.length <= 200)
@@ -50,8 +45,9 @@ export default function LayaMlxPanel() {
const install = () => run(() => installLaya({ silent: true }).then(value => {
if (!value.ok) setError(errorLabel(value.code));
else {
- statusGeneration.current += 1;
setStatus(previous => ({ ...previous, installing: true, installError: null }));
+ // Installation can finish before its acceptance response arrives.
+ refetch();
}
}));
const score = () => run(() => {
diff --git a/client/src/components/models/LayaMlxPanel.test.jsx b/client/src/components/models/LayaMlxPanel.test.jsx
index ba879c5e4c..eb9f94f0d7 100644
--- a/client/src/components/models/LayaMlxPanel.test.jsx
+++ b/client/src/components/models/LayaMlxPanel.test.jsx
@@ -1,9 +1,15 @@
-import { beforeEach, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
const mocks = vi.hoisted(() => ({ status: vi.fn(), install: vi.fn(), score: vi.fn(), toggle: vi.fn(), publish: vi.fn(), enabled: true }));
vi.mock('../../services/api', () => ({ getLayaStatus: mocks.status, installLaya: mocks.install, scoreLaya: mocks.score, updateInstanceFeature: mocks.toggle }));
vi.mock('../../hooks/useInstanceFeatures', () => ({ publishInstanceFeatures: mocks.publish, useInstanceFeatures: () => ({ features: [{ id: 'laya-mlx', enabled: mocks.enabled }] }) }));
+vi.mock('../../services/socket', async () => {
+ const { EventEmitter } = await import('node:events');
+ return { default: new EventEmitter() };
+});
+import socket from '../../services/socket';
import LayaMlxPanel from './LayaMlxPanel';
+afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
beforeEach(() => {
vi.clearAllMocks(); mocks.enabled = true;
mocks.status.mockResolvedValue({ supported: true, ready: true });
@@ -40,3 +46,49 @@ it('explains unsupported hardware without offering installation or scoring', asy
expect(screen.getByRole('button', { name: 'Install Laya-MLX' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Enable experiments' })).toBeDisabled();
});
+
+it('updates from status events without polling and reconciles once on reconnect and tab show', async () => {
+ vi.useFakeTimers();
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ const view = render(<LayaMlxPanel />);
+ await act(async () => {});
+ expect(screen.getByText(/Runtime: installed/)).toBeInTheDocument();
+ expect(mocks.status).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(20000); });
+ expect(mocks.status).toHaveBeenCalledTimes(1);
+ mocks.status.mockResolvedValue({ supported: true, installing: true, stage: 'model' });
+ await act(async () => { socket.emit('laya:status', {}); });
+ expect(screen.getByText('Runtime: installing (model). Experiments: enabled.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Installing…' })).toBeDisabled();
+ mocks.status.mockResolvedValue({ supported: true, installError: 'laya-install-model-failed' });
+ await act(async () => { socket.emit('laya:status', {}); });
+ expect(screen.getByRole('alert')).toHaveTextContent('pinned model download failed');
+ mocks.status.mockResolvedValue({ supported: true, ready: true });
+ await act(async () => { socket.emit('connect'); });
+ expect(mocks.status).toHaveBeenCalledTimes(4);
+ expect(screen.getByText(/Runtime: installed/)).toBeInTheDocument();
+ visibility.mockReturnValue('hidden');
+ act(() => document.dispatchEvent(new Event('visibilitychange')));
+ await act(async () => { socket.emit('laya:status', {}); socket.emit('connect'); });
+ expect(mocks.status).toHaveBeenCalledTimes(4);
+ visibility.mockReturnValue('visible');
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(mocks.status).toHaveBeenCalledTimes(5);
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(mocks.status).toHaveBeenCalledTimes(5);
+ view.unmount();
+ await act(async () => { socket.emit('laya:status', {}); socket.emit('connect'); });
+ expect(mocks.status).toHaveBeenCalledTimes(5);
+});
+it('reconciles completion that arrives before the install acceptance response', async () => {
+ let accept;
+ mocks.install.mockReturnValue(new Promise(resolve => { accept = resolve; }));
+ render(<LayaMlxPanel />);
+ await screen.findByText(/Runtime: installed/);
+ fireEvent.click(screen.getByRole('button', { name: 'Repair Laya-MLX' }));
+ await act(async () => { socket.emit('laya:status', {}); });
+ await act(async () => { accept({ ok: true, installing: true }); });
+ expect(screen.getByText(/Runtime: installed/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Repair Laya-MLX' })).toBeEnabled();
+ expect(mocks.status).toHaveBeenCalledTimes(3);
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 05ffac30af..51086864b1 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -57,6 +57,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
additionalProperties: false,
},
},
+ 'laya:status': {
+ direction: 'server-to-client',
+ summary: 'Invalidate Laya runtime status after install progress, completion, failure or scoring transitions; no experiment content.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
'usage-backfill:updated': {
direction: 'server-to-client',
summary: 'Invalidate historical usage backfill status after progress or a durable terminal transition.',
diff --git a/server/services/layaMlx.js b/server/services/layaMlx.js
index 74c919dd96..f9329e93d7 100644
--- a/server/services/layaMlx.js
+++ b/server/services/layaMlx.js
@@ -1,4 +1,5 @@
/** Explicit, experimental Laya execution. No boot hooks, automatic routing or prompt persistence. */
+import { notifyLayaStatus } from './layaMlxEvents.js';
import { existsSync } from 'node:fs';
import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises';
import { join } from 'node:path';
@@ -41,6 +42,7 @@ export async function getLayaStatus() {
async function performInstall() {
const { detectVenvBasePythonSync } = await import('../lib/pythonSetup.js');
stage = 'python';
+ notifyLayaStatus();
const base = detectVenvBasePythonSync();
if (!base) throw new Error('python');
await execFileAsync(base, ['-c', 'import sys,platform; assert sys.version_info >= (3,11) and platform.machine() == "arm64" and int(platform.mac_ver()[0].split(".")[0]) >= 14'],
@@ -48,14 +50,17 @@ async function performInstall() {
await mkdir(root(), { recursive: true });
await unlink(marker()).catch(error => { if (error.code !== 'ENOENT') throw error; });
stage = 'runtime';
+ notifyLayaStatus();
await execFileAsync(base, ['-m', 'venv', join(root(), 'venv')], { env: environment(), timeout: 120000, maxBuffer: 4096 });
await execFileAsync(python(), ['-m', 'pip', 'install', '--force-reinstall', '--disable-pip-version-check',
`https://github.com/mizorewww/laya-mlx/archive/${LAYA_MLX.runtimeRevision}.zip`],
{ env: environment(false), timeout: 600000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' });
stage = 'model';
+ notifyLayaStatus();
await execFileAsync(python(), [script(), 'download', model(), LAYA_MLX.repository, LAYA_MLX.revision],
{ env: environment(false), timeout: 1200000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' });
stage = 'verify';
+ notifyLayaStatus();
await execFileAsync(python(), [script(), 'verify', model()],
{ env: environment(), timeout: 120000, maxBuffer: 4096, killSignal: 'SIGKILL' });
await writeFile(`${marker()}.tmp`, JSON.stringify(LAYA_MLX));
@@ -68,7 +73,8 @@ export async function installLaya() {
if (!installation) {
installError = null;
installation = performInstall().catch(() => { installError = `laya-install-${stage}-failed`; })
- .finally(() => { installation = null; stage = null; });
+ .finally(() => { installation = null; stage = null; notifyLayaStatus(); });
+ notifyLayaStatus();
}
return { ok: true, installing: true };
}
@@ -82,6 +88,7 @@ export async function scoreLaya(input, signal) {
// Reserve before the first asynchronous readiness check: overlapping requests
// must not each load a separate copy of the model into unified memory.
scoring = true;
+ notifyLayaStatus();
const started = Date.now();
return (async () => {
const status = await getLayaStatus();
@@ -99,5 +106,5 @@ export async function scoreLaya(input, signal) {
const result = normalizeLayaResult(raw, parsed.data.options, parsed.data.minMargin);
return result ? { ...result, elapsedMs: Date.now() - started } : failure('laya-response-invalid');
})().catch(() => failure(signal?.aborted ? 'laya-cancelled' : 'laya-scoring-failed'))
- .finally(() => { scoring = false; });
+ .finally(() => { scoring = false; notifyLayaStatus(); });
}
diff --git a/server/services/layaMlx.test.js b/server/services/layaMlx.test.js
index 6334a09315..b788f347f7 100644
--- a/server/services/layaMlx.test.js
+++ b/server/services/layaMlx.test.js
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { promisify } from 'node:util';
const mocks = vi.hoisted(() => ({ exec: vi.fn(), enabled: vi.fn(), supported: vi.fn(), exists: vi.fn(), read: vi.fn() }));
vi.mock('../lib/childProcess.js', () => ({ execFile: Object.assign(() => {}, { [promisify.custom]: mocks.exec }) }));
@@ -7,13 +7,17 @@ vi.mock('../lib/platform.js', () => ({ isAppleSilicon: mocks.supported }));
vi.mock('./instanceFeatures.js', () => ({ isInstanceFeatureEnabled: mocks.enabled }));
vi.mock('node:fs', () => ({ existsSync: mocks.exists }));
vi.mock('node:fs/promises', () => ({ readFile: mocks.read, mkdir: vi.fn().mockResolvedValue(), writeFile: vi.fn().mockResolvedValue(), rename: vi.fn().mockResolvedValue(), unlink: vi.fn().mockResolvedValue() }));
+import { layaMlxEvents } from './layaMlxEvents.js';
import { LAYA_MLX } from '../lib/layaMlx.js';
import { getLayaStatus, installLaya, scoreLaya } from './layaMlx.js';
const input = { premise: 'The invoice was paid twice.', instructions: 'Choose a department.', options: ['billing', 'sales'], minMargin: 0.15 };
const output = { answers: { decision: { type: 'choice', choice: 'billing', probabilities: { billing: 0.9, sales: 0.1 }, confidence: 0.53 } } };
let stdin;
+const notifications = vi.fn();
+afterEach(() => layaMlxEvents.removeAllListeners());
beforeEach(() => {
vi.clearAllMocks();
+ layaMlxEvents.on('updated', notifications);
mocks.enabled.mockResolvedValue(true);
mocks.supported.mockReturnValue(true);
mocks.exists.mockReturnValue(true);
@@ -27,12 +31,14 @@ describe('Laya manual experiment workflow', () => {
mocks.supported.mockReturnValue(false);
expect(await installLaya()).toEqual({ ok: false, code: 'laya-unsupported' });
expect(mocks.exec).not.toHaveBeenCalled();
+ expect(notifications).not.toHaveBeenCalled();
});
it('gates disabled experiments before spawning and validates requests', async () => {
mocks.enabled.mockResolvedValue(false);
expect(await scoreLaya(input)).toMatchObject({ code: 'laya-disabled' });
expect(await scoreLaya({ ...input, options: ['same', 'same'] })).toMatchObject({ code: 'laya-request-invalid' });
expect(mocks.exec).not.toHaveBeenCalled();
+ expect(notifications).not.toHaveBeenCalled();
});
it('scores offline through stdin without leaking credentials or confusing confidence with entailment', async () => {
vi.stubEnv('GH_TOKEN', 'test-secret');
@@ -67,7 +73,10 @@ describe('Laya manual experiment workflow', () => {
expect(await scoreLaya(input)).toMatchObject({ code: 'laya-busy' });
expect(await installLaya()).toMatchObject({ code: 'laya-busy' });
reject(new Error('private traceback'));
+ expect(notifications).toHaveBeenCalledTimes(1);
expect(await first).toEqual({ ok: false, code: 'laya-scoring-failed' });
+ expect(notifications).toHaveBeenCalledTimes(2);
+ expect(await getLayaStatus()).toMatchObject({ scoring: false });
expect(await scoreLaya(input)).toMatchObject({ ok: true });
});
});
@@ -75,9 +84,14 @@ describe('Laya manual experiment workflow', () => {
it('installs only on request, pins runtime and weights, and reports bounded setup failures', async () => {
expect(await installLaya()).toEqual({ ok: true, installing: true });
await vi.waitFor(async () => expect((await getLayaStatus()).installing).toBe(false));
+ expect(notifications).toHaveBeenLastCalledWith({});
+ expect(notifications).toHaveBeenCalledTimes(6);
expect(mocks.exec.mock.calls.some(([, args]) => args.includes(`https://github.com/mizorewww/laya-mlx/archive/${LAYA_MLX.runtimeRevision}.zip`))).toBe(true);
expect(mocks.exec.mock.calls.some(([, args]) => args.includes(LAYA_MLX.revision) && args.includes(LAYA_MLX.repository))).toBe(true);
+ notifications.mockClear();
mocks.exec.mockRejectedValueOnce(new Error('private Python diagnostic'));
await installLaya();
await vi.waitFor(async () => expect(await getLayaStatus()).toMatchObject({ installing: false, installError: 'laya-install-python-failed' }));
+ expect(notifications).toHaveBeenCalledTimes(3);
+ expect(notifications).toHaveBeenLastCalledWith({});
});
diff --git a/server/services/layaMlxEvents.js b/server/services/layaMlxEvents.js
new file mode 100644
index 0000000000..5087df5492
--- /dev/null
+++ b/server/services/layaMlxEvents.js
@@ -0,0 +1,5 @@
+import { EventEmitter } from 'node:events';
+
+// Invalidate status without broadcasting experiment inputs or results.
+export const layaMlxEvents = new EventEmitter();
+export const notifyLayaStatus = () => layaMlxEvents.emit('updated', {});
diff --git a/server/services/socket.js b/server/services/socket.js
index a636e776eb..d797d60f96 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -37,6 +37,7 @@ import { videoGenEvents } from './videoGen/events.js';
import { audioGenEvents } from './audioGen/events.js';
import { aiStatusEvents } from './aiStatusEvents.js';
import { usageBackfillEvents } from './usageBackfillEvents.js';
+import { layaMlxEvents } from './layaMlxEvents.js';
import { providerQuotaEvents } from './providerQuotaEvents.js';
import { wireProactiveTriggers } from './voice/proactiveTriggers.js';
import { callStateEvents } from './voice/callSession.js';
@@ -247,6 +248,7 @@ function setupEventForwarding() {
modelLifecycleEvents.on('threejs-model:changed', data => ioInstance?.emit('threejs-model:changed', data));
meatspaceEvents.on('death-clock:changed', data => ioInstance?.emit('meatspace:death-clock:changed', data));
usageBackfillEvents.on('updated', () => ioInstance?.emit('usage-backfill:updated', {}));
+ layaMlxEvents.on('updated', () => ioInstance?.emit('laya:status', {}));
providerQuotaEvents.on('updated', () => ioInstance?.emit('provider-quota:updated', {}));
setupCosEventForwarding();
setupErrorEventForwarding();
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 8c67064226..a8db988684 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -8,6 +8,7 @@ import { fableLoomRunEvents } from './fableLoom/runEvents.js';
import { trainingEvents } from './loraTraining/events.js';
import { authEvents } from './auth.js';
import { usageBackfillEvents } from './usageBackfillEvents.js';
+import { layaMlxEvents } from './layaMlxEvents.js';
import { providerQuotaEvents } from './providerQuotaEvents.js';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -155,6 +156,7 @@ describe('socket.js — initSocket', () => {
authEvents.removeAllListeners('sessions:revoked-all');
meatspaceEvents.removeAllListeners();
modelLifecycleEvents.removeAllListeners();
+ layaMlxEvents.removeAllListeners();
providerQuotaEvents.removeAllListeners();
usageBackfillEvents.removeAllListeners();
});
@@ -203,6 +205,12 @@ describe('socket.js — initSocket', () => {
expect(io.emitted).toEqual([['usage-backfill:updated', {}]]);
});
+ it('forwards Laya status without experiment content', () => {
+ io.emitted.length = 0;
+ layaMlxEvents.emit('updated', { premise: 'Example private experiment' });
+ expect(io.emitted).toEqual([['laya:status', {}]]);
+ });
+
it('forwards quota completion without leaking source data', () => {
io.emitted.length = 0;
providerQuotaEvents.emit('updated', { privateContent: 'example account detail' });