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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add a fail-closed Blender rigging runtime resolver and readiness probe (#5752)
Adam Eivyacbce124cfcf
diff --git a/client/src/components/settings/InstanceFeaturesTab.jsx b/client/src/components/settings/InstanceFeaturesTab.jsxindex c986621854..650bb1619f 100644--- a/client/src/components/settings/InstanceFeaturesTab.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.jsx@@ -3,6 +3,7 @@ import { Link } from 'react-router';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';+import RiggingRuntimeCard from './RiggingRuntimeCard';import { useInstanceFeatures, publishInstanceFeatures } from '../../hooks/useInstanceFeatures.js';import { isGitHubRepoUrl, parseGitHubUrl } from '../../lib/repoUrl.js';import { getPrimaryLaunchUrl } from '../../services/appUrls.js';@@ -152,6 +153,10 @@ export function InstanceFeaturesTab() {{features.map((feature) => {const hint = sourceHint(feature);const isEidoverse = feature.id === 'eidoverse';+ // Rigging's "configured" state is a machine-local runtime rather than a+ // config file, so its row carries the probe's answer (installed/absent, the+ // resolved interpreter, the module version, the install command).+ const isRigging = feature.id === 'rigging';const setup = isEidoverse ? feature.setup : null;const needsInstall = isEidoverse && setup?.installed !== true;const installing = savingId === feature.id;@@ -184,7 +189,11 @@ export function InstanceFeaturesTab() {? 'Active on this instance': (isEidoverse ? 'Installed but disabled on this instance' : 'Not used on this instance'))}</p>- {hint && <p className="text-xs text-gray-500 mt-1">{hint}</p>}+ {hint && !isRigging && <p className="text-xs text-gray-500 mt-1">{hint}</p>}+ {/* Rigging's own card states the runtime's status precisely; the+ generic "no <label> instance is configured" hint would talk about+ an integration this feature does not have. */}+ {isRigging && <RiggingRuntimeCard />}{isEidoverse && (<div className="mt-3 space-y-1 text-xs text-gray-400">{needsInstall && <p>diff --git a/client/src/components/settings/RiggingRuntimeCard.jsx b/client/src/components/settings/RiggingRuntimeCard.jsxnew file mode 100644index 0000000000..32e1cac4ab--- /dev/null+++ b/client/src/components/settings/RiggingRuntimeCard.jsx@@ -0,0 +1,104 @@+import { useCallback, useEffect, useState } from 'react';+import BrailleSpinner from '../BrailleSpinner';+import { copyToClipboard } from '../../lib/clipboard.js';+import { riggingReasonLabel } from '../../lib/riggingReasons.js';+import { getRiggingReadiness } from '../../services/api';++// The rigging runtime's honest status, rendered inside the rigging row of+// Settings > Features. It fetches `GET /api/rigging/readiness` from HERE rather than+// riding the shared feature list, because the probe imports Blender's Python module —+// the feature list is read on every page load by the sidebar and the ⌘K palette, and+// this answer is only worth collecting on the tab that shows it.+//+// There is deliberately NO install button in this phase: the runtime is provisioned by+// one command the user runs themselves, so the card prints that command (copyable)+// instead of inventing a second install/progress affordance beside the 3D targets+// page's.+export function RiggingRuntimeCard() {+ const [readiness, setReadiness] = useState(null);+ const [error, setError] = useState(null);+ const [checking, setChecking] = useState(false);++ const load = useCallback(async ({ refresh = false } = {}) => {+ setChecking(true);+ // Silent: an unreadable probe is reported inline on the card, not as a toast —+ // this tab renders on every Settings visit and a toast would fire unprompted.+ const result = await getRiggingReadiness({ refresh, silent: true }).catch((err) => err);+ if (result instanceof Error) setError(result);+ else {+ setError(null);+ setReadiness(result);+ }+ setChecking(false);+ }, []);++ useEffect(() => { load(); }, [load]);++ const handleCopy = () => copyToClipboard(readiness?.installCommand, 'Install command copied');++ if (error) {+ return (+ <div className="mt-3 text-xs text-port-error">+ <p>{error.message || 'Could not read the rigging runtime status'}</p>+ <button+ type="button"+ onClick={() => load({ refresh: true })}+ className="inline-flex items-center justify-center min-h-[44px] px-3 mt-2 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors"+ >+ Retry+ </button>+ </div>+ );+ }++ if (!readiness) return <div className="mt-3"><BrailleSpinner text="Checking the rigging runtime" /></div>;++ return (+ <div className="mt-3 space-y-2 text-xs text-gray-400">+ <p className={readiness.ready ? 'text-port-success' : 'text-port-warning'}>+ {readiness.ready ? 'Runtime installed' : riggingReasonLabel(readiness.reason)}+ </p>+ <p>{readiness.detail}</p>+ <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1">+ <div className="min-w-0">+ <dt className="text-gray-500">Interpreter</dt>+ <dd className="break-all text-gray-300">{readiness.interpreter || 'Not resolved'}</dd>+ </div>+ <div className="min-w-0">+ <dt className="text-gray-500">{readiness.module} version</dt>+ <dd className="break-all text-gray-300">+ {readiness.moduleVersion || `Not reported (pinned to ${readiness.modulePin})`}+ </dd>+ </div>+ </dl>+ {readiness.installCommand && (+ <div>+ <p className="text-gray-500 mb-1" id="rigging-install-command-label">Install command</p>+ <code+ aria-labelledby="rigging-install-command-label"+ className="block w-full overflow-x-auto whitespace-pre bg-port-bg border border-port-border rounded-lg px-3 py-2 text-gray-300"+ >+ {readiness.installCommand}+ </code>+ <button+ type="button"+ onClick={handleCopy}+ className="inline-flex items-center justify-center min-h-[44px] px-3 mt-2 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors"+ >+ Copy command+ </button>+ </div>+ )}+ <button+ type="button"+ onClick={() => load({ refresh: true })}+ disabled={checking}+ className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-border hover:bg-port-border/70 disabled:opacity-50 text-white rounded transition-colors"+ >+ {checking ? 'Rechecking…' : 'Recheck runtime'}+ </button>+ </div>+ );+}++export default RiggingRuntimeCard;diff --git a/client/src/components/settings/RiggingRuntimeCard.test.jsx b/client/src/components/settings/RiggingRuntimeCard.test.jsxnew file mode 100644index 0000000000..871ab596fa--- /dev/null+++ b/client/src/components/settings/RiggingRuntimeCard.test.jsx@@ -0,0 +1,79 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const mock = vi.hoisted(() => ({ getRiggingReadiness: vi.fn() }));+vi.mock('../../services/api', () => mock);++const copyToClipboard = vi.hoisted(() => vi.fn());+vi.mock('../../lib/clipboard.js', () => ({ copyToClipboard }));++import RiggingRuntimeCard from './RiggingRuntimeCard';++const READY = {+ ready: true,+ reason: null,+ detail: 'bpy 4.2.0 imports from /opt/conda/envs/rigging/bin/python.',+ interpreter: '/opt/conda/envs/rigging/bin/python',+ module: 'bpy',+ moduleVersion: '4.2.0',+ modulePin: 'bpy==4.2.0',+ installCommand: null,+};++const HALF_INSTALLED = {+ ready: false,+ reason: 'module-unimportable',+ detail: '/opt/conda/envs/rigging/bin/python exists, but importing bpy failed: ImportError: bad magic number.',+ interpreter: '/opt/conda/envs/rigging/bin/python',+ module: 'bpy',+ moduleVersion: null,+ modulePin: 'bpy==4.2.0',+ installCommand: 'conda create -y -n rigging python=3.11 && conda run -n rigging pip install "bpy==4.2.0"',+};++describe('RiggingRuntimeCard', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.getRiggingReadiness.mockResolvedValue(READY);+ });++ it('reports a ready runtime with its interpreter and module version, and offers no remedy', async () => {+ render(<RiggingRuntimeCard />);+ expect(await screen.findByText('Runtime installed')).toBeInTheDocument();+ expect(screen.getByText(READY.interpreter)).toBeInTheDocument();+ expect(screen.getByText('4.2.0')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Copy command' })).not.toBeInTheDocument();+ });++ // The failure this lane exists to name: an env that resolves but cannot import.+ // Rendering it as ready would be the silent-success bug.+ it('names a half-installed runtime and prints the pinned install command', async () => {+ mock.getRiggingReadiness.mockResolvedValue(HALF_INSTALLED);+ render(<RiggingRuntimeCard />);++ expect(await screen.findByText('The rigging runtime is only half installed')).toBeInTheDocument();+ expect(screen.getByText(HALF_INSTALLED.detail)).toBeInTheDocument();+ // The version must read as unknown, never as an empty-but-fine value.+ expect(screen.getByText('Not reported (pinned to bpy==4.2.0)')).toBeInTheDocument();+ expect(screen.getByText(HALF_INSTALLED.installCommand)).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Copy command' }));+ expect(copyToClipboard).toHaveBeenCalledWith(HALF_INSTALLED.installCommand, 'Install command copied');+ });++ it('probes on mount without a refresh, and forces one only on an explicit recheck', async () => {+ render(<RiggingRuntimeCard />);+ await screen.findByText('Runtime installed');+ expect(mock.getRiggingReadiness).toHaveBeenCalledWith({ refresh: false, silent: true });++ fireEvent.click(screen.getByRole('button', { name: 'Recheck runtime' }));+ await waitFor(() => expect(mock.getRiggingReadiness).toHaveBeenCalledWith({ refresh: true, silent: true }));+ });++ it('reports a failed read inline rather than blanking the card', async () => {+ mock.getRiggingReadiness.mockRejectedValue(new Error('readiness unavailable'));+ render(<RiggingRuntimeCard />);+ expect(await screen.findByText('readiness unavailable')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 4489445902..96028b85a0 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -218,3 +218,4 @@ grep -i "what you want to do" client/src/lib/README.md| `universeMarkdownFilename.js` | `slugifyUniverseName` / `universeMarkdownFilename` — client-side safe filename helpers for Universe Markdown world-bible downloads, kept in step with the server attachment name. || `universeMarkdownFilename.cases.js` | Shared client/server filename contract cases used to keep the browser download name and server attachment name in lockstep. || `qrCode.js` | Deterministic SVG QR code generator for scoped mobile session join links (#5383). |+| `riggingReasons.js` | Client mirror of the character-rigging readiness reason labels in `server/services/rigging/readiness.js`: `RIGGING_UNAVAILABLE_REASONS` (reason code -> user-facing label), `RIGGING_REASON_FALLBACK`, and `riggingReasonLabel(code, fallback?)`. Render these anywhere a `GET /api/rigging/readiness` reason is shown; never re-declare the codes. Parity + code coverage enforced by `server/services/rigging/unavailableReasons.parity.test.js`. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 00293b14a6..161b98a5ee 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -187,3 +187,4 @@ export * from './webglSupport.js';export * from './wrSceneCursor.js';export * from './writingGuide.js';export * from './qrCode.js';+export * from './riggingReasons.js';diff --git a/client/src/lib/riggingReasons.js b/client/src/lib/riggingReasons.jsnew file mode 100644index 0000000000..8ad6a73bf9--- /dev/null+++ b/client/src/lib/riggingReasons.js@@ -0,0 +1,41 @@+/**+ * Client mirror of the character-rigging readiness reason labels in+ * `server/services/rigging/readiness.js`. The server returns stable kebab-case reason+ * codes (`unsupported-platform`, `module-unimportable`, …) whenever rigging is not+ * ready; this is the label side the UI renders.+ *+ * The client can't import the server module (it reaches `node:fs` / `child_process`+ * through the runtime probe), so this is a hand-maintained mirror — drift is asserted+ * by `server/services/rigging/unavailableReasons.parity.test.js`, which also checks the+ * key set still equals the codes `riggingUnavailableReason()` returns. If you change+ * one side, change the other.+ *+ * Names are prefixed (`RIGGING_…`) rather than reusing the image-to-3D lane's generic+ * `UNAVAILABLE_REASONS`, because both modules are flat `export *` members of the same+ * `client/src/lib` barrel and a shared identifier there is a collision.+ */++export const RIGGING_UNAVAILABLE_REASONS = Object.freeze({+ 'unsupported-platform': 'Rigging needs macOS on Apple Silicon, or Linux',+ 'runtime-not-installed': 'The Blender rigging runtime is not installed yet',+ // The failure this phase exists to name: the env resolved, the module did not import.+ // Reporting it as ready would trade a named blocker for a render-time crash.+ 'module-unimportable': 'The rigging runtime is only half installed',+ // "We could not look" is not "there is nothing there" — never report an absent+ // runtime we failed to probe (AGENTS.md sentinel rule).+ 'runtime-probe-failed': 'Could not check the rigging runtime on this host',+});++/** Label for a reason code the map doesn't know (or a null/absent code). */+export const RIGGING_REASON_FALLBACK = 'Rigging is unavailable on this host';++/**+ * User-facing label for a reason code. Own-property lookup only, so a code that+ * happens to name an Object.prototype key can't render as a function/object.+ * @param {string|null} [reason]+ * @param {string} [fallback]+ * @returns {string}+ */+export function riggingReasonLabel(reason, fallback = RIGGING_REASON_FALLBACK) {+ return Object.hasOwn(RIGGING_UNAVAILABLE_REASONS, reason ?? '') ? RIGGING_UNAVAILABLE_REASONS[reason] : fallback;+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 4aa6e61edb..f18917880e 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -149,3 +149,4 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `uiInteract.js` | Execute voice `ui_click` / `ui_fill` / `ui_select` against live DOM. || `domIndex.js` | DOM indexer for voice accessibility mode. || `staleBuildToast.jsx` | Sticky toast shown when server's build id differs from client's. |+| `apiRigging.js` | Character rigging (`GET /rigging/readiness`): whether this install's Blender runtime is provisioned, the resolved interpreter, the module version, and the install command when it is not. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 077729f47a..d7c8ba13c8 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -87,6 +87,7 @@ export * from './apiAuth.js';export * from './apiPrivacy.js';export * from './apiQuotaBurn.js';export * from './apiRapidReader.js';+export * from './apiRigging.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiRigging.js b/client/src/services/apiRigging.jsnew file mode 100644index 0000000000..591a1d4205--- /dev/null+++ b/client/src/services/apiRigging.js@@ -0,0 +1,8 @@+import { request } from './apiCore.js';++// Character rigging: the read-only readiness answer for this install's Blender+// runtime. `refresh` forces a re-probe past the server's short-lived memo — use it+// only for an explicit recheck, never on mount.++export const getRiggingReadiness = ({ refresh = false, ...options } = {}) =>+ request(`/rigging/readiness${refresh ? '?refresh=1' : ''}`, options);diff --git a/server/index.js b/server/index.jsindex fd1e8fa0e8..10da561e29 100644--- a/server/index.js+++ b/server/index.js@@ -130,6 +130,7 @@ import spriteRoutes from './routes/sprites.js';import moodBoardRoutes from './routes/moodBoard.js';import threejsModelsRoutes from './routes/threejsModels.js';import imageTo3dRoutes from './routes/imageTo3d.js';+import riggingRoutes from './routes/rigging.js';import privacyRoutes from './routes/privacy.js';import writersRoomRoutes from './routes/writersRoom.js';import universeBuilderRoutes from './routes/universeBuilder/index.js';@@ -385,6 +386,7 @@ app.use('/api/sprites', spriteRoutes);app.use('/api/mood-boards', moodBoardRoutes);app.use('/api/threejs-models', threejsModelsRoutes);app.use('/api/image-to-3d', imageTo3dRoutes);+app.use('/api/rigging', riggingRoutes);app.use('/api/privacy', privacyRoutes);app.use('/api/writers-room', writersRoomRoutes);app.use('/api/universe-builder', universeBuilderRoutes);diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 0d61132141..14a07b9dc9 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -108,6 +108,7 @@"/api/rapid-reader","/api/remote-desktop","/api/review",+ "/api/rigging","/api/rounds","/api/runs","/api/scaffold",@@ -13988,6 +13989,14 @@"server/routes/review.js"]},+ {+ "method": "GET",+ "path": "/api/rigging/readiness",+ "mountPath": "/api/rigging",+ "sources": [+ "server/routes/rigging.js"+ ]+ },{"method": "GET","path": "/api/rounds",@@ -17414,9 +17423,9 @@}],"stats": {- "mounts": 145,- "operations": 2157,- "declarations": 2165,- "sourceFiles": 228+ "mounts": 146,+ "operations": 2158,+ "declarations": 2166,+ "sourceFiles": 229}}diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex 89123376a3..0b18b73131 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -64,6 +64,15 @@ export const INSTANCE_FEATURES = Object.freeze([// installs on that behavior until the user explicitly changes the flag.defaultEnabled: true,}),+ Object.freeze({+ id: 'rigging',+ label: 'Character rigging',+ description: 'Blender-backed rigging for generated 3D characters. Needs a provisioned Blender Python runtime on this machine.',+ // Off until a runtime is actually present: the detector in+ // services/instanceFeatures.js turns it on only when the probe says the Blender+ // module imports, so a fresh install never advertises a capability it cannot run.+ defaultEnabled: false,+ }),Object.freeze({id: 'facetime',label: 'FaceTime Audio',diff --git a/server/routes/rigging.js b/server/routes/rigging.jsnew file mode 100644index 0000000000..b3c7b6deb1--- /dev/null+++ b/server/routes/rigging.js@@ -0,0 +1,28 @@+import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { getRiggingReadiness } from '../services/rigging/readiness.js';++const router = Router();++// The only input this lane accepts: force a re-probe instead of reading the short-lived+// memo. Present so the Settings card's "Recheck" reflects an install the user just ran.+const readinessQuerySchema = z.object({+ refresh: z.enum(['1', 'true']).optional(),+});++/**+ * Whether this host can run character rigging, and — when it cannot — WHY, by a stable+ * reason code the client mirrors to a label (`client/src/lib/riggingReasons.js`).+ *+ * Read-only and on-demand: the Blender import probe runs from here (and from the+ * instance-feature detector), never from `server/index.js` boot, so a fresh install+ * pays nothing at startup for a feature nobody has asked for.+ */+router.get('/readiness', asyncHandler(async (req, res) => {+ const { refresh } = validateRequest(readinessQuerySchema, req.query);+ res.json(await getRiggingReadiness({ refresh: Boolean(refresh) }));+}));++export default router;diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.jsindex 5bf297eb9e..a6e03a6fa6 100644--- a/server/services/instanceFeatures.js+++ b/server/services/instanceFeatures.js@@ -40,6 +40,21 @@ const DETECTORS = {const { hasConfiguredInstances } = await import('./jira.js');return hasConfiguredInstances();},+ // The rigging runtime is a machine-local install, not a config file — so "configured"+ // here means the Blender module actually imports. The probe memoizes its answer, so+ // this does not spawn an interpreter on every page load's feature read.+ rigging: async () => {+ const { getRiggingReadiness } = await import('./rigging/readiness.js');+ // FAIL CLOSED, unlike the config-file detectors above. Those fail open because an+ // unreadable config file still means the integration is probably set up; here a+ // probe that could not answer means the runtime may simply not exist, and+ // advertising rigging on such a host trades a named blocker for a spawn error.+ const readiness = await getRiggingReadiness().catch((error) => {+ console.error(`❌ Rigging readiness detection failed: ${error.message}`);+ return null;+ });+ return readiness?.ready === true;+ },facetime: async () => {if (process.platform !== 'darwin') return false;const { checkSetup } = await import('./voice/facetimeBridge.js');diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex fccd5a89d8..2fcc1ac249 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -11,6 +11,8 @@ const mock = vi.hoisted(() => ({portosOrigin: { isGithub: true, isUpstream: false, owner: 'example-owner' },assertEidoverseInstalled: vi.fn(),setEidoverseWorldsOrigin: vi.fn(),+ riggingReady: false,+ riggingThrows: false,}));const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));@@ -33,6 +35,16 @@ vi.mock('./jira.js', () => ({hasConfiguredInstances: vi.fn(async () => mock.jiraConfigured),}));+// The rigging detector probes a machine-local runtime rather than a config file, so+// the real module would spawn a Blender import on a machine that happens to have the+// env provisioned. Mocked here to keep the suite deterministic on any host.+vi.mock('./rigging/readiness.js', () => ({+ getRiggingReadiness: vi.fn(async () => {+ if (mock.riggingThrows) throw new Error('probe exploded');+ return { ready: mock.riggingReady, reason: mock.riggingReady ? null : 'runtime-not-installed' };+ }),+}));+vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: vi.fn(async () => mock.portosOrigin),}));@@ -69,6 +81,8 @@ describe('instance features', () => {mock.jiraConfigured = false;mock.datadogThrows = false;mock.eidoverseInstalled = false;+ mock.riggingReady = false;+ mock.riggingThrows = false;mock.portosOrigin = { isGithub: true, isUpstream: false, owner: 'example-owner' };mock.assertEidoverseInstalled.mockReset().mockResolvedValue({ installed: true });mock.setEidoverseWorldsOrigin.mockReset().mockResolvedValue({ appId: 'app-eidoverse' });@@ -243,6 +257,38 @@ describe('instance features', () => {});});+ // Rigging inverts the fail-open policy above, on purpose. Its detector probes a+ // machine-local RUNTIME, not a config file: "we could not tell" there means the+ // Blender module may simply not exist, and enabling the feature on such a host+ // trades a named blocker for a spawn error the first time a user clicks.+ it('enables rigging only when the runtime probe says it is ready', async () => {+ mock.riggingReady = true;+ expect((await detectFeatureConfiguration()).rigging).toBe(true);+ expect(byId((await getInstanceFeatures()).features, 'rigging')).toMatchObject({+ enabled: true,+ source: 'auto',+ });+ expect(await isInstanceFeatureEnabled('rigging')).toBe(true);+ });++ it('keeps rigging off on an install with no runtime', async () => {+ expect((await detectFeatureConfiguration()).rigging).toBe(false);+ expect(byId((await getInstanceFeatures()).features, 'rigging')).toMatchObject({+ enabled: false,+ source: 'auto',+ });+ });++ it('fails CLOSED when the rigging probe cannot answer', async () => {+ mock.riggingThrows = true;+ expect((await detectFeatureConfiguration()).rigging).toBe(false);+ expect(byId((await getInstanceFeatures()).features, 'rigging')).toMatchObject({+ enabled: false,+ source: 'auto',+ });+ expect(await isInstanceFeatureEnabled('rigging')).toBe(false);+ });+// A feature with NO detector reads null for a different reason — nothing was// ever probed — so it must keep taking its shipped default, not fail open.it('reports no detection for a feature with no detector', async () => {@@ -259,7 +305,7 @@ describe('instance features', () => {const { features } = await getInstanceFeatures();expect(Object.fromEntries(features.map((f) => [f.id, f.enabled])))- .toEqual({ post: true, datadog: true, jira: false, eidoverse: false, gsd: true, openclaw: true, health: true, facetime: false });+ .toEqual({ post: true, datadog: true, jira: false, eidoverse: false, gsd: true, openclaw: true, health: true, rigging: false, facetime: false });});it('rejects an unknown feature id', async () => {diff --git a/server/services/rigging/readiness.js b/server/services/rigging/readiness.jsnew file mode 100644index 0000000000..8f2d825e0c--- /dev/null+++ b/server/services/rigging/readiness.js@@ -0,0 +1,180 @@+/**+ * Character rigging — the honest readiness answer.+ *+ * Shipped BEFORE any rigging behavior so the capability is reportable and fail-closed+ * from day one: a host with no Blender runtime says so by name, instead of surfacing a+ * mysterious spawn error the first time a user clicks a rigging action.+ *+ * Shape and vocabulary mirror the image-to-3D lane (`imageTo3d/targets.js`'s reason+ * codes and `imageTo3d/degradedInstall.js`'s "remedy plus culprit" split): stable+ * kebab-case codes here, user-facing labels mirrored verbatim to+ * `client/src/lib/riggingReasons.js`, with the drift AND the code-coverage gap both+ * pinned by `unavailableReasons.parity.test.js` next to this file.+ *+ * `riggingUnavailableReason` is a PURE reducer over an already-collected host picture,+ * so every branch — including the two that matter most, a half-provisioned env and an+ * unsupported host — is unit-testable with no real install.+ */++import {+ RIGGING_INSTALL_COMMAND,+ RIGGING_MODULE_REQUIREMENT,+ RIGGING_RUNTIME,+ isRiggingPlatformSupported,+ probeBlenderModule,+ resolveRiggingPython,+} from './runtime.js';++/**+ * Every reason code `riggingUnavailableReason` can return, mapped to its user-facing+ * label. MIRRORED verbatim to `client/src/lib/riggingReasons.js` — the client cannot+ * import this module (it reaches `node:fs`/`child_process` through the probe), so the+ * parity test asserts the two never drift and that the key set still EQUALS the codes+ * the reducer actually returns.+ *+ * Labels are per-CODE prose, never interpolated: the machine-specific half (which+ * platform, which interpreter, which import error) travels in `detail`.+ */+export const RIGGING_UNAVAILABLE_REASONS = Object.freeze({+ 'unsupported-platform': 'Rigging needs macOS on Apple Silicon, or Linux',+ 'runtime-not-installed': 'The Blender rigging runtime is not installed yet',+ // The failure this phase exists to name: the env resolved, the module did not import.+ // Reporting it as ready would trade a named blocker for a render-time crash.+ 'module-unimportable': 'The rigging runtime is only half installed',+ // "We could not look" is not "there is nothing there" — never report an absent+ // runtime we failed to probe (AGENTS.md sentinel rule).+ 'runtime-probe-failed': 'Could not check the rigging runtime on this host',+});++/** Label for a reason code the map doesn't know (or a null/absent code). */+export const RIGGING_REASON_FALLBACK = 'Rigging is unavailable on this host';++/**+ * User-facing label for a reason code. Own-property lookup only, so a code that+ * happens to name an Object.prototype key can't render as a function/object.+ * @param {string|null} [reason]+ * @param {string} [fallback]+ * @returns {string}+ */+export function riggingReasonLabel(reason, fallback = RIGGING_REASON_FALLBACK) {+ return Object.hasOwn(RIGGING_UNAVAILABLE_REASONS, reason ?? '') ? RIGGING_UNAVAILABLE_REASONS[reason] : fallback;+}++/**+ * Why rigging can't run — or `null` when it can. Pure: the host picture is passed in,+ * never probed here.+ *+ * Order is the point. The platform gate comes first because it is final (no install+ * fixes it); the interpreter gate before the module gate because "no env" and "env+ * present, module broken" are different remedies; and anything the probe could not+ * answer falls to `runtime-probe-failed` rather than to a confident "not installed".+ *+ * @param {{supportedPlatform?: boolean, python?: string|null,+ * probe?: {status?: string}|null}} [host]+ * @returns {string|null}+ */+export function riggingUnavailableReason({ supportedPlatform, python, probe } = {}) {+ if (!supportedPlatform) return 'unsupported-platform';+ if (!python) return 'runtime-not-installed';+ if (probe?.status === 'ok') return null;+ if (probe?.status === 'unimportable') return 'module-unimportable';+ return 'runtime-probe-failed';+}++// The machine-specific half of the answer. Split from the labels above for the same+// reason `degradedInstall.js` splits remedy from culprits: the label is mirrored to the+// client and must stay free of values only the server knows.+const detailFor = (reason, { platform, python, probe }) => {+ switch (reason) {+ case null:+ return `${RIGGING_RUNTIME.module} ${probe?.version || '(version unreported)'} imports from ${python}.`;+ case 'unsupported-platform':+ return `Rigging runs on macOS (Apple Silicon) and Linux; this host reports "${platform}".`;+ case 'runtime-not-installed':+ return `No "${RIGGING_RUNTIME.condaEnv}" conda environment was found. Run the install command to create it.`;+ case 'module-unimportable':+ return `${python} exists, but importing ${RIGGING_RUNTIME.module} failed`+ + `${probe?.error ? `: ${probe.error}` : '.'}`+ + ` Re-run the install command to reprovision ${RIGGING_MODULE_REQUIREMENT}.`;+ default:+ return `${python} could not be run, so the state of ${RIGGING_RUNTIME.module} in the `+ + `"${RIGGING_RUNTIME.condaEnv}" environment is unknown.`;+ }+};++/**+ * Assemble the readiness payload from an already-collected host picture. Pure.+ *+ * `installCommand` is omitted for `unsupported-platform` on purpose — offering a remedy+ * that cannot work is worse than offering none.+ *+ * The payload carries the reason CODE, never its label: the client renders labels from+ * its own pinned mirror (`client/src/lib/riggingReasons.js`), the way the image-to-3D+ * lane's `/targets` response does. `riggingReasonLabel` above is for server-side prose.+ *+ * @param {{supportedPlatform: boolean, platform: string, python: string|null,+ * probe: {status?: string, version?: string|null, error?: string|null}|null}} host+ * @returns {{ready: boolean, reason: string|null, detail: string,+ * interpreter: string|null, module: string, moduleVersion: string|null,+ * modulePin: string, installCommand: string|null}}+ */+export function describeRiggingReadiness({ supportedPlatform, platform, python, probe }) {+ const reason = riggingUnavailableReason({ supportedPlatform, python, probe });+ return {+ ready: reason === null,+ reason,+ detail: detailFor(reason, { platform, python, probe }),+ interpreter: python || null,+ module: RIGGING_RUNTIME.module,+ moduleVersion: probe?.status === 'ok' ? (probe.version || null) : null,+ modulePin: RIGGING_MODULE_REQUIREMENT,+ installCommand: reason === null || reason === 'unsupported-platform' ? null : RIGGING_INSTALL_COMMAND,+ };+}++/**+ * Collect the host picture and describe it. The one impure export here — it resolves a+ * path and (only when there is an interpreter to run) spawns the import probe.+ *+ * Runs ON REQUEST, never from boot: a fresh install must not pay a Blender import at+ * startup for a feature the user has not asked for.+ *+ * @param {{exists?: Function, env?: NodeJS.ProcessEnv, execFileImpl?: Function,+ * platform?: string, arch?: string}} [opts]+ * @returns {Promise<object>}+ */+export async function probeRiggingReadiness({ exists, env, execFileImpl, platform = process.platform, arch } = {}) {+ const supportedPlatform = isRiggingPlatformSupported({ platform, arch });+ if (!supportedPlatform) {+ return describeRiggingReadiness({ supportedPlatform, platform, python: null, probe: null });+ }+ const python = resolveRiggingPython({ exists, env });+ const probe = python ? await probeBlenderModule({ python, execFileImpl }) : null;+ return describeRiggingReadiness({ supportedPlatform, platform, python, probe });+}++// A real `import bpy` costs seconds, and the readiness answer is read by BOTH the+// Settings card and the instance-feature detector (which runs on every+// `GET /api/settings/features`, i.e. every page load). Memoize it for a short window so+// navigation never waits on a repeated Blender import; the Settings card's explicit+// recheck passes `refresh` to bypass it.+const CACHE_TTL_MS = 60_000;+let cached = null;++/** Drop the memoized readiness answer. Test-only seam. */+export const __resetRiggingReadinessCache = () => { cached = null; };++/**+ * The cached readiness answer. `probe`/`now` are injectable for the same reason the+ * rest of this lane is: the cache contract is testable without a real Blender import.+ * @param {{refresh?: boolean, now?: () => number, probe?: () => Promise<object>}} [opts]+ * @returns {Promise<object>}+ */+export async function getRiggingReadiness({ refresh = false, now = Date.now, probe = probeRiggingReadiness } = {}) {+ const at = now();+ if (!refresh && cached && at - cached.at < CACHE_TTL_MS) return cached.value;+ const value = await probe();+ cached = { at, value };+ console.log(`🦴 Rigging readiness: ${value.ready ? 'ready' : value.reason}`);+ return value;+}diff --git a/server/services/rigging/readiness.test.js b/server/services/rigging/readiness.test.jsnew file mode 100644index 0000000000..47b7f564ac--- /dev/null+++ b/server/services/rigging/readiness.test.js@@ -0,0 +1,161 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import {+ RIGGING_INSTALL_COMMAND,+ RIGGING_MODULE_REQUIREMENT,+ RIGGING_RUNTIME,+} from './runtime.js';+import {+ __resetRiggingReadinessCache,+ describeRiggingReadiness,+ getRiggingReadiness,+ probeRiggingReadiness,+ riggingUnavailableReason,+} from './readiness.js';++const FAKE_ROOT = '/opt/conda';+const FAKE_PYTHON = `${FAKE_ROOT}/envs/${RIGGING_RUNTIME.condaEnv}/bin/python`;+const ENV = { CONDA_ROOT: FAKE_ROOT };+const READY_HOST = { supportedPlatform: true, platform: 'linux', python: FAKE_PYTHON, probe: { status: 'ok', version: '4.2.0' } };++describe('riggingUnavailableReason', () => {+ it('is null only when the module actually imported', () => {+ expect(riggingUnavailableReason(READY_HOST)).toBeNull();+ });++ it('reports an unsupported host before anything else, even with a runtime present', () => {+ expect(riggingUnavailableReason({ ...READY_HOST, supportedPlatform: false })).toBe('unsupported-platform');+ });++ it('separates "no env" from "env present, module broken"', () => {+ expect(riggingUnavailableReason({ supportedPlatform: true, python: null })).toBe('runtime-not-installed');+ expect(riggingUnavailableReason({ ...READY_HOST, probe: { status: 'unimportable', error: 'ImportError' } }))+ .toBe('module-unimportable');+ });++ it('never reads a failed probe as an absent runtime', () => {+ expect(riggingUnavailableReason({ ...READY_HOST, probe: { status: 'probe-failed' } })).toBe('runtime-probe-failed');+ expect(riggingUnavailableReason({ ...READY_HOST, probe: null })).toBe('runtime-probe-failed');+ });++ it('defaults to a named blocker rather than ready when handed nothing', () => {+ expect(riggingUnavailableReason()).toBe('unsupported-platform');+ });+});++describe('describeRiggingReadiness', () => {+ it('reports the interpreter and module version when ready, with no remedy to offer', () => {+ expect(describeRiggingReadiness(READY_HOST)).toMatchObject({+ ready: true,+ reason: null,+ interpreter: FAKE_PYTHON,+ module: RIGGING_RUNTIME.module,+ moduleVersion: '4.2.0',+ modulePin: RIGGING_MODULE_REQUIREMENT,+ installCommand: null,+ });+ });++ it('names the half-provisioned env, keeps the version blank, and offers the repair', () => {+ const result = describeRiggingReadiness({+ ...READY_HOST,+ probe: { status: 'unimportable', error: 'ImportError: bad magic number' },+ });+ expect(result.ready).toBe(false);+ expect(result.reason).toBe('module-unimportable');+ // The interpreter IS there — reporting the version as anything but unknown would+ // be the silent-ready failure this lane exists to prevent.+ expect(result.moduleVersion).toBeNull();+ expect(result.interpreter).toBe(FAKE_PYTHON);+ expect(result.detail).toContain('bad magic number');+ expect(result.installCommand).toBe(RIGGING_INSTALL_COMMAND);+ });++ it('says why an unsupported host is unsupported, and offers no command that cannot work', () => {+ const result = describeRiggingReadiness({+ supportedPlatform: false, platform: 'win32', python: null, probe: null,+ });+ expect(result).toMatchObject({ ready: false, reason: 'unsupported-platform', installCommand: null });+ expect(result.detail).toContain('win32');+ expect(result.detail).toMatch(/Apple Silicon/);+ });++ it('points an uninstalled host at the pinned install command', () => {+ const result = describeRiggingReadiness({+ supportedPlatform: true, platform: 'linux', python: null, probe: null,+ });+ expect(result).toMatchObject({ reason: 'runtime-not-installed', interpreter: null, moduleVersion: null });+ expect(result.installCommand).toBe(RIGGING_INSTALL_COMMAND);+ });++ it('says the state is unknown — not absent — when the probe could not run', () => {+ const result = describeRiggingReadiness({ ...READY_HOST, probe: { status: 'probe-failed' } });+ expect(result.reason).toBe('runtime-probe-failed');+ expect(result.detail).toContain('unknown');+ });+});++describe('probeRiggingReadiness', () => {+ it('short-circuits an unsupported host without touching the filesystem', async () => {+ let looked = false;+ const result = await probeRiggingReadiness({+ platform: 'win32',+ arch: 'x64',+ exists: () => { looked = true; return true; },+ });+ expect(result.reason).toBe('unsupported-platform');+ expect(looked).toBe(false);+ });++ it('resolves and probes a provisioned env end to end', async () => {+ const result = await probeRiggingReadiness({+ platform: 'linux',+ env: ENV,+ exists: (p) => p === FAKE_PYTHON,+ execFileImpl: (_file, _args, _opts, cb) => cb(null, '{"ok": true, "version": "4.2.0"}'),+ });+ expect(result).toMatchObject({ ready: true, interpreter: FAKE_PYTHON, moduleVersion: '4.2.0' });+ });++ it('does not spawn a probe when there is no interpreter to probe', async () => {+ let spawned = false;+ const result = await probeRiggingReadiness({+ platform: 'linux',+ env: ENV,+ exists: () => false,+ execFileImpl: () => { spawned = true; },+ });+ expect(result.reason).toBe('runtime-not-installed');+ expect(spawned).toBe(false);+ });+});++describe('getRiggingReadiness caching', () => {+ beforeEach(() => {+ __resetRiggingReadinessCache();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ // A real `import bpy` costs seconds, so the call count below is the contract that+ // keeps it off the per-page-load feature-detection path.+ const countingProbe = () => vi.fn(async () => ({ ready: false, reason: 'runtime-not-installed' }));++ it('reuses the answer inside the TTL and re-probes after it, so navigation never waits on a repeated Blender import', async () => {+ const probe = countingProbe();+ const first = await getRiggingReadiness({ now: () => 1_000, probe });+ const cachedHit = await getRiggingReadiness({ now: () => 2_000, probe });+ expect(cachedHit).toBe(first);+ expect(probe).toHaveBeenCalledTimes(1);++ const afterTtl = await getRiggingReadiness({ now: () => 121_000, probe });+ expect(afterTtl).not.toBe(first);+ expect(probe).toHaveBeenCalledTimes(2);+ });++ it('bypasses the cache on an explicit refresh', async () => {+ const probe = countingProbe();+ const first = await getRiggingReadiness({ now: () => 1_000, probe });+ const refreshed = await getRiggingReadiness({ refresh: true, now: () => 1_500, probe });+ expect(refreshed).not.toBe(first);+ expect(probe).toHaveBeenCalledTimes(2);+ });+});diff --git a/server/services/rigging/runtime.js b/server/services/rigging/runtime.jsnew file mode 100644index 0000000000..6190926e76--- /dev/null+++ b/server/services/rigging/runtime.js@@ -0,0 +1,132 @@+/**+ * Character rigging — Blender-module runtime resolution and probe.+ *+ * The rigging lane needs Blender's Python module (`bpy`) importable from a dedicated+ * interpreter. It gets its own conda environment for the same reason the image-to-3D+ * CUDA lanes each get one (`trellis2`, `pixal3d`): `bpy` pins an exact CPython minor+ * and drags a large native tree with it, so sharing an env with another heavy lane+ * would let one lane's upgrade silently break the other.+ *+ * Everything here is PURE or INJECTABLE — `exists`, `env` and `execFileImpl` are all+ * parameters — so the resolver and the probe classifier are unit-testable on a host+ * with no Blender install at all. Only the caller that passes no overrides touches the+ * real machine, and it does so on request (never from `server/index.js` boot).+ *+ * The probe deliberately does a REAL `import`, not `importlib.util.find_spec` the way+ * `imageTo3d/laneRunner.js#probePythonModules` does. A half-provisioned env — the+ * interpreter created, the wheel half-unpacked or built against the wrong CPython — has+ * a resolvable spec and an unimportable module. That is exactly the failure this lane+ * must NAME rather than report as ready, so it is worth the seconds a real import costs+ * (the readiness caller memoizes the answer so it is not paid per request).+ */++import { existsSync } from 'node:fs';+import { execFile } from '../../lib/childProcess.js';+import { resolveCondaEnvPython } from '../../lib/condaEnv.js';+import { isAppleSilicon } from '../../lib/platform.js';++/**+ * The install descriptor. `moduleVersion` is a hard PIN, not a floor: `bpy` wheels are+ * published per Blender release against one CPython minor, and an unpinned install+ * resolves to whichever pairing PyPI happens to serve — which is how an env ends up+ * with an interpreter that cannot import the module it just installed.+ */+export const RIGGING_RUNTIME = Object.freeze({+ condaEnv: 'rigging',+ module: 'bpy',+ moduleVersion: '4.2.0',+ pythonVersion: '3.11',+});++/** `bpy==4.2.0` — the pinned requirement, assembled once from the descriptor. */+export const RIGGING_MODULE_REQUIREMENT = `${RIGGING_RUNTIME.module}==${RIGGING_RUNTIME.moduleVersion}`;++/**+ * The one command that provisions the env. Surfaced verbatim in the Settings card so+ * the remedy the UI prints and the remedy this module resolves against cannot drift.+ */+export const RIGGING_INSTALL_COMMAND = `conda create -y -n ${RIGGING_RUNTIME.condaEnv} `+ + `python=${RIGGING_RUNTIME.pythonVersion} && `+ + `conda run -n ${RIGGING_RUNTIME.condaEnv} pip install "${RIGGING_MODULE_REQUIREMENT}"`;++/**+ * Can this host run the rigging runtime at all? macOS on Apple Silicon and Linux are+ * the supported pairings; an Intel Mac and Windows are not (the conda-env resolver in+ * `condaEnv.js` only knows POSIX `bin/python` layouts, and the lane's downstream+ * tooling follows). Pure — platform/arch are injectable.+ *+ * @param {{platform?: string, arch?: string, probe?: () => boolean}} [opts]+ * @returns {boolean}+ */+export function isRiggingPlatformSupported({ platform = process.platform, arch, probe } = {}) {+ if (platform === 'linux') return true;+ return isAppleSilicon({ platform, arch, probe });+}++/**+ * The rigging env's interpreter, or `null` when the env has not been created.+ * `exists`/`env` are injectable exactly as `resolveCondaEnvPython` makes them, so this+ * resolves deterministically in tests with no conda on the machine.+ *+ * @param {{exists?: (p: string) => boolean, env?: NodeJS.ProcessEnv}} [opts]+ * @returns {string|null}+ */+export function resolveRiggingPython({ exists = existsSync, env } = {}) {+ return resolveCondaEnvPython(RIGGING_RUNTIME.condaEnv, { exists, env });+}++/**+ * The probe one-liner. It catches the import failure ITSELF and still exits 0, printing+ * `{"ok": false, …}`. That is what lets the classifier below tell "python ran and the+ * module would not import" apart from "the interpreter could not be run at all" — two+ * states a non-zero exit would collapse into one (AGENTS.md sentinel rule).+ */+export const BLENDER_MODULE_PROBE_SOURCE = [+ 'import json',+ 'try:',+ ` import ${RIGGING_RUNTIME.module} as _m`,+ ' _v = getattr(getattr(_m, "app", None), "version_string", None)',+ ' print(json.dumps({"ok": True, "version": _v if isinstance(_v, str) else None}))',+ 'except BaseException as exc:',+ ' print(json.dumps({"ok": False, "error": "%s: %s" % (type(exc).__name__, exc)}))',+].join('\n');++/** Keep a runtime error message short enough to render in a card line. */+const MAX_ERROR_CHARS = 300;++const parseProbeJson = (stdout) => {+ try {+ const parsed = JSON.parse(String(stdout).trim() || 'null');+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;+ } catch {+ return null;+ }+};++/**+ * Classify one probe run.+ *+ * Child-process boundary outside the request lifecycle, so every failure path RESOLVES+ * — and, as in `probePythonModules`, the JSON parse happens after the callback settles:+ * a throw inside an `execFile` callback escapes the enclosing promise and reaches the+ * event loop, crashing the process instead of degrading the probe.+ *+ * @param {{python: string|null, execFileImpl?: Function, timeoutMs?: number}} [opts]+ * @returns {Promise<{status: 'ok'|'unimportable'|'probe-failed', version?: string|null, error?: string|null}>}+ */+export async function probeBlenderModule({ python, execFileImpl = execFile, timeoutMs = 60000 } = {}) {+ if (!python) return { status: 'probe-failed', error: null };+ const stdout = await new Promise((resolve) => {+ execFileImpl(python, ['-c', BLENDER_MODULE_PROBE_SOURCE], { timeout: timeoutMs },+ (err, out) => resolve(err ? null : String(out ?? '')));+ }).catch(() => null);+ if (stdout === null) return { status: 'probe-failed', error: null };++ const parsed = parseProbeJson(stdout);+ if (!parsed) return { status: 'probe-failed', error: null };+ if (parsed.ok !== true) {+ const error = typeof parsed.error === 'string' ? parsed.error.slice(0, MAX_ERROR_CHARS) : null;+ return { status: 'unimportable', error };+ }+ return { status: 'ok', version: typeof parsed.version === 'string' ? parsed.version : null };+}diff --git a/server/services/rigging/runtime.test.js b/server/services/rigging/runtime.test.jsnew file mode 100644index 0000000000..3d556cb3bf--- /dev/null+++ b/server/services/rigging/runtime.test.js@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';+import {+ BLENDER_MODULE_PROBE_SOURCE,+ RIGGING_INSTALL_COMMAND,+ RIGGING_MODULE_REQUIREMENT,+ RIGGING_RUNTIME,+ isRiggingPlatformSupported,+ probeBlenderModule,+ resolveRiggingPython,+} from './runtime.js';++// A conda root that exists only in this test's `exists` predicate — no real install is+// consulted, so the resolver's behavior is the same on any developer's machine and CI.+const FAKE_ROOT = '/opt/conda';+const FAKE_PYTHON = `${FAKE_ROOT}/envs/${RIGGING_RUNTIME.condaEnv}/bin/python`;+const ENV = { CONDA_ROOT: FAKE_ROOT };++describe('rigging runtime — install descriptor', () => {+ it('pins the Blender module to an exact version in the install command', () => {+ expect(RIGGING_MODULE_REQUIREMENT).toBe(`${RIGGING_RUNTIME.module}==${RIGGING_RUNTIME.moduleVersion}`);+ expect(RIGGING_INSTALL_COMMAND).toContain(`"${RIGGING_MODULE_REQUIREMENT}"`);+ expect(RIGGING_INSTALL_COMMAND).toContain(`python=${RIGGING_RUNTIME.pythonVersion}`);+ expect(RIGGING_INSTALL_COMMAND).toContain(`-n ${RIGGING_RUNTIME.condaEnv}`);+ });+});++describe('isRiggingPlatformSupported', () => {+ it('supports Linux and Apple Silicon macOS', () => {+ expect(isRiggingPlatformSupported({ platform: 'linux' })).toBe(true);+ expect(isRiggingPlatformSupported({ platform: 'darwin', arch: 'arm64' })).toBe(true);+ // An x64 darwin process may still be arm64 hardware under Rosetta.+ expect(isRiggingPlatformSupported({ platform: 'darwin', arch: 'x64', probe: () => true })).toBe(true);+ });++ it('rejects Intel macOS and every non-POSIX host by name', () => {+ expect(isRiggingPlatformSupported({ platform: 'darwin', arch: 'x64', probe: () => false })).toBe(false);+ expect(isRiggingPlatformSupported({ platform: 'win32', arch: 'x64' })).toBe(false);+ expect(isRiggingPlatformSupported({ platform: 'freebsd', arch: 'x64' })).toBe(false);+ });+});++describe('resolveRiggingPython', () => {+ it('resolves the named env from an injected filesystem', () => {+ expect(resolveRiggingPython({ exists: (p) => p === FAKE_PYTHON, env: ENV })).toBe(FAKE_PYTHON);+ });++ it('returns null when the env has not been created', () => {+ expect(resolveRiggingPython({ exists: () => false, env: ENV })).toBeNull();+ });++ it('uses its own env name, not another heavy lane’s', () => {+ const seen = [];+ resolveRiggingPython({ exists: (p) => { seen.push(p); return false; }, env: ENV });+ expect(seen.every((p) => p.includes(`/envs/${RIGGING_RUNTIME.condaEnv}/`))).toBe(true);+ });+});++// Every case drives the classifier through an injected `execFile` — no interpreter is+// spawned, so the half-provisioned case is covered on a host with no Blender at all.+const execFileReturning = (err, stdout) => (_file, _args, _opts, cb) => cb(err, stdout);++describe('probeBlenderModule', () => {+ it('reports the module version when the import succeeds', async () => {+ const result = await probeBlenderModule({+ python: FAKE_PYTHON,+ execFileImpl: execFileReturning(null, '{"ok": true, "version": "4.2.0"}\n'),+ });+ expect(result).toEqual({ status: 'ok', version: '4.2.0' });+ });++ it('stays ok, with a null version, when the module reports none', async () => {+ const result = await probeBlenderModule({+ python: FAKE_PYTHON,+ execFileImpl: execFileReturning(null, '{"ok": true, "version": null}'),+ });+ expect(result).toEqual({ status: 'ok', version: null });+ });++ // The half-provisioned env: the interpreter runs, the module does not import. The+ // probe one-liner catches that itself and still exits 0, which is what keeps it+ // distinct from "we could not run the interpreter".+ it('names an import failure rather than reporting the runtime absent', async () => {+ const result = await probeBlenderModule({+ python: FAKE_PYTHON,+ execFileImpl: execFileReturning(null, '{"ok": false, "error": "ImportError: bad magic number"}'),+ });+ expect(result).toEqual({ status: 'unimportable', error: 'ImportError: bad magic number' });+ });++ it('truncates a runaway error message', async () => {+ const result = await probeBlenderModule({+ python: FAKE_PYTHON,+ execFileImpl: execFileReturning(null, JSON.stringify({ ok: false, error: 'x'.repeat(5000) })),+ });+ expect(result.error).toHaveLength(300);+ });++ it('reports probe-failed — never "absent" — when the interpreter cannot be run', async () => {+ const spawnFailed = await probeBlenderModule({+ python: FAKE_PYTHON,+ execFileImpl: execFileReturning(new Error('ENOENT'), ''),+ });+ expect(spawnFailed).toEqual({ status: 'probe-failed', error: null });+ });++ it('reports probe-failed on unparseable or non-object output', async () => {+ for (const stdout of ['', 'not json', '[1,2]', 'null']) {+ const result = await probeBlenderModule({ python: FAKE_PYTHON, execFileImpl: execFileReturning(null, stdout) });+ expect(result, `stdout ${JSON.stringify(stdout)}`).toEqual({ status: 'probe-failed', error: null });+ }+ });++ it('reports probe-failed with no interpreter, without spawning anything', async () => {+ let spawned = false;+ const result = await probeBlenderModule({+ python: null,+ execFileImpl: () => { spawned = true; },+ });+ expect(result).toEqual({ status: 'probe-failed', error: null });+ expect(spawned).toBe(false);+ });++ it('does a real import, not a spec lookup, so a half-built env cannot read as ready', () => {+ expect(BLENDER_MODULE_PROBE_SOURCE).toContain(`import ${RIGGING_RUNTIME.module}`);+ expect(BLENDER_MODULE_PROBE_SOURCE).not.toContain('find_spec');+ // It must swallow the failure itself; a raised ImportError would exit non-zero and+ // become indistinguishable from a broken interpreter.+ expect(BLENDER_MODULE_PROBE_SOURCE).toContain('except BaseException');+ });+});diff --git a/server/services/rigging/unavailableReasons.parity.test.js b/server/services/rigging/unavailableReasons.parity.test.jsnew file mode 100644index 0000000000..e30be13051--- /dev/null+++ b/server/services/rigging/unavailableReasons.parity.test.js@@ -0,0 +1,89 @@+/**+ * Cross-package parity for the character-rigging readiness reason labels.+ *+ * `server/services/rigging/readiness.js` owns the reason CODES (what+ * `riggingUnavailableReason()` returns) and their labels; `client/src/lib/+ * riggingReasons.js` is a hand-maintained mirror (the client can't import the server+ * module — it reaches `node:fs`/`child_process` through the runtime probe). This suite+ * imports BOTH and asserts they stay identical, mirroring the image-to-3D lane's+ * `imageTo3d/unavailableReasons.parity.test.js`.+ *+ * It also closes the same gap that motivated the shared map there: the source guard+ * below asserts the label key set still EQUALS the codes the reducer actually returns,+ * so adding a code without a label — which would otherwise render as the generic+ * "Rigging is unavailable on this host" fallback with a fully green suite — fails here.+ */++import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, it, expect } from 'vitest';+import {+ RIGGING_UNAVAILABLE_REASONS as SERVER_REASONS,+ RIGGING_REASON_FALLBACK as SERVER_FALLBACK,+ riggingReasonLabel as serverLabel,+} from './readiness.js';+import {+ RIGGING_UNAVAILABLE_REASONS as CLIENT_REASONS,+ RIGGING_REASON_FALLBACK as CLIENT_FALLBACK,+ riggingReasonLabel as clientLabel,+} from '../../../client/src/lib/riggingReasons.js';++// Reason codes are kebab-case (asserted below), and every OTHER single-quoted literal+// in `riggingUnavailableReason()` is a dash-free probe-status token (`'ok'`,+// `'unimportable'`) — so "quoted, has a dash" identifies the codes exactly. Comments+// are stripped first so a code named in prose can't count as a return.+const KEBAB_CODE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/;++function reasonCodesInSource() {+ const src = readFileSync(fileURLToPath(new URL('./readiness.js', import.meta.url)), 'utf8');+ const start = src.indexOf('export function riggingUnavailableReason(');+ expect(start, 'riggingUnavailableReason() not found in readiness.js').toBeGreaterThan(-1);+ // Bounded by the function's own column-0 closing brace, so a later declaration being+ // renamed, reordered, or inserted before the next export can't widen the window.+ const end = src.indexOf('\n}\n', start);+ expect(end, 'no column-0 closing brace found — cannot bound the reducer body').toBeGreaterThan(start);+ const body = src.slice(start, end)+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/\/\/[^\n]*/g, '');+ return [...body.matchAll(/'([a-z][a-z0-9-]*)'/g)].map((m) => m[1]).filter((s) => KEBAB_CODE.test(s));+}++describe('rigging readiness reasons — server↔client parity', () => {+ it('exposes the same codes in the same order with the same labels', () => {+ expect(Object.entries(CLIENT_REASONS)).toEqual(Object.entries(SERVER_REASONS));+ });++ it('shares the unknown-code fallback label', () => {+ expect(CLIENT_FALLBACK).toBe(SERVER_FALLBACK);+ });++ it('labels every code identically across server and client', () => {+ const probes = [...Object.keys(SERVER_REASONS), 'not-a-real-code', '', null, undefined, '__proto__', 'constructor'];+ for (const code of probes) {+ expect(clientLabel(code), `label for ${String(code)} drifted`).toBe(serverLabel(code));+ }+ });+});++describe('rigging readiness reasons — code coverage', () => {+ // The source guard identifies codes by their kebab shape, so the shape is part of the+ // contract: a dash-free code would slip past it unlabelled.+ it('keeps every code kebab-case', () => {+ for (const code of Object.keys(SERVER_REASONS)) {+ expect(code, `${code} must be kebab-case for the source guard to see it`).toMatch(KEBAB_CODE);+ }+ });++ it('labels exactly the codes riggingUnavailableReason() can return', () => {+ const codes = reasonCodesInSource();+ expect(codes.length).toBeGreaterThan(0);+ expect([...new Set(codes)].sort()).toEqual(Object.keys(SERVER_REASONS).sort());+ });++ it('falls back for an unknown or absent code rather than rendering the raw code', () => {+ expect(serverLabel(null)).toBe(SERVER_FALLBACK);+ expect(serverLabel('brand-new-code')).toBe(SERVER_FALLBACK);+ expect(serverLabel('brand-new-code', 'custom')).toBe('custom');+ expect(serverLabel('unsupported-platform', 'custom')).toBe(SERVER_REASONS['unsupported-platform']);+ });+});