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
Add opt-in Eidoverse Worlds managed app (#5419)
[._.]/ Adam Eivy746d6607e7e2
diff --git a/client/src/components/settings/InstanceFeaturesTab.jsx b/client/src/components/settings/InstanceFeaturesTab.jsxindex 85e1a71aec..a55f29b622 100644--- a/client/src/components/settings/InstanceFeaturesTab.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.jsx@@ -1,9 +1,12 @@import { useState } from 'react';+import { Link } from 'react-router';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';import { useInstanceFeatures, publishInstanceFeatures } from '../../hooks/useInstanceFeatures.js';-import { updateInstanceFeature } from '../../services/api';+import { isGitHubRepoUrl } from '../../lib/githubRepoUrl.js';+import { getPrimaryLaunchUrl } from '../../services/appUrls.js';+import { installEidoverseFeature, updateInstanceFeature } from '../../services/api';// How the current value was decided, so a user who never touched the toggle can// see that the install picked it up from a configured integration rather than@@ -18,6 +21,8 @@ const sourceHint = (feature) => {export function InstanceFeaturesTab() {const { features, error, reload } = useInstanceFeatures();const [savingId, setSavingId] = useState(null);+ const [eidoverseRepoUrl, setEidoverseRepoUrl] = useState(null);+ const [recheckingEidoverse, setRecheckingEidoverse] = useState(false);// The toggle is announced on the shared INSTANCE_FEATURES_CHANGED channel, so// the sidebar, the ⌘K palette, and the dashboard widgets that already listen@@ -36,6 +41,31 @@ export function InstanceFeaturesTab() {setSavingId(null);};+ const handleEidoverseInstall = async (feature) => {+ if (savingId) return;+ const worldsRepoUrl = eidoverseRepoUrl ?? feature?.setup?.worldsRepoUrl;+ if (!worldsRepoUrl) return;+ setSavingId(feature.id);+ const result = await installEidoverseFeature(worldsRepoUrl, { silent: true }).catch((err) => {+ toast.error(err.message || 'Could not install Eidoverse Worlds');+ return null;+ });++ if (result) {+ publishInstanceFeatures(result.features, { featureId: feature.id, enabled: true });+ toast.success('Eidoverse Worlds is installed and ready to start');+ }+ setSavingId(null);+ };++ const handleEidoverseRecheck = () => {+ if (recheckingEidoverse) return;+ setRecheckingEidoverse(true);+ reload()+ .catch((err) => toast.error(err.message || 'Could not recheck Eidoverse requirements'))+ .finally(() => setRecheckingEidoverse(false));+ };+if (error) {return (<div className="space-y-3 max-w-3xl">@@ -65,26 +95,121 @@ export function InstanceFeaturesTab() {<div className="space-y-3">{features.map((feature) => {const hint = sourceHint(feature);+ const isEidoverse = feature.id === 'eidoverse';+ const setup = isEidoverse ? feature.setup : null;+ const needsInstall = isEidoverse && setup?.installed !== true;+ const installing = savingId === feature.id;+ const selectedRepoUrl = eidoverseRepoUrl ?? setup?.worldsRepoUrl ?? '';+ const repoIsValid = isGitHubRepoUrl(selectedRepoUrl);+ const canInstall = repoIsValid && setup?.bunAvailable === true && setup?.registryAvailable !== false;+ const launchUrl = setup?.appId && setup?.uiPort+ ? getPrimaryLaunchUrl({ id: setup.appId, uiPort: setup.uiPort })+ : null;return (<divkey={feature.id}- className="flex items-start justify-between gap-4 bg-port-card border border-port-border rounded-lg p-4"+ className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 bg-port-card border border-port-border rounded-lg p-4"><div className="min-w-0"><h3 className="text-sm font-semibold text-white">{feature.label}</h3><p className="text-sm text-gray-400 mt-1">{feature.description}</p><p className={`text-xs mt-2 ${feature.enabled ? 'text-port-success' : 'text-gray-500'}`}>- {feature.enabled ? 'Active on this instance' : 'Not used on this instance'}+ {needsInstall+ ? (setup?.partial ? 'Installation needs to be resumed' : 'Not installed')+ : (feature.enabled+ ? '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>}+ {needsInstall && (+ <div className="mt-3 space-y-1 text-xs text-gray-400">+ <p>+ PortOS will clone your selected Worlds repository and the upstream video runtime as separate AGPL-3.0 repositories, install their Bun dependencies, and register Worlds under Apps. It will not start the server automatically.+ </p>+ <label className="block pt-2" htmlFor="eidoverse-worlds-repo">+ <span className="block text-gray-300 mb-1">Worlds GitHub repository</span>+ <input+ id="eidoverse-worlds-repo"+ type="url"+ required+ value={selectedRepoUrl}+ onChange={(event) => setEidoverseRepoUrl(event.target.value)}+ disabled={savingId !== null}+ aria-invalid={!repoIsValid}+ aria-describedby={!repoIsValid ? 'eidoverse-worlds-repo-error' : undefined}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden disabled:opacity-50"+ placeholder="https://github.com/your-account/eidoverse-worlds"+ />+ </label>+ {!repoIsValid && (+ <p id="eidoverse-worlds-repo-error" role="alert" className="text-port-error">+ {selectedRepoUrl === ''+ ? 'Enter a GitHub repository URL.'+ : 'Enter a valid GitHub repository URL.'}+ </p>+ )}+ <p>Use your own fork if you want PortOS agents to prepare changes and PRs against it.</p>+ {setup?.bunAvailable === false && (+ <p className="text-port-warning">+ Bun is required. <a className="underline hover:text-white" href="https://bun.sh" target="_blank" rel="noreferrer">Install Bun</a>, then retry.+ </p>+ )}+ {setup?.registryAvailable === false && (+ <p className="text-port-error">The managed-app registry could not be read. Repair that before installing to avoid a duplicate app record.</p>+ )}+ {(setup?.bunAvailable === false || setup?.registryAvailable === false) && (+ <button+ type="button"+ onClick={handleEidoverseRecheck}+ disabled={recheckingEidoverse}+ className="inline-flex items-center justify-center min-h-[44px] px-3 mt-2 text-sm bg-port-border hover:bg-port-border/70 disabled:opacity-50 text-white rounded transition-colors"+ >+ {recheckingEidoverse ? 'Rechecking…' : 'Recheck requirements'}+ </button>+ )}+ </div>+ )}+ {setup?.installed && (+ <div className="flex flex-wrap items-center gap-3 mt-3 text-xs">+ {setup.worldsRepoUrl && (+ <a className="text-port-accent hover:text-white transition-colors" href={setup.worldsRepoUrl} target="_blank" rel="noreferrer">+ Worlds repository+ </a>+ )}+ {setup.appId && (+ <Link className="text-port-accent hover:text-white transition-colors" to={`/apps/${setup.appId}`}>+ Manage app+ </Link>+ )}+ {feature.enabled && setup.runtimeStatus === 'online' && launchUrl && (+ <a className="text-port-accent hover:text-white transition-colors" href={launchUrl} target="_blank" rel="noreferrer">+ Open world+ </a>+ )}+ {feature.enabled && setup.runtimeStatus !== 'online' && (+ <span className="text-gray-500">Start it from the managed app to enter the world.</span>+ )}+ </div>+ )}</div>- <ToggleSwitch- enabled={feature.enabled}- onChange={() => handleToggle(feature)}- disabled={savingId !== null}- ariaLabel={`${feature.enabled ? 'Disable' : 'Enable'} ${feature.label} on this instance`}- className="mt-1"- />+ {needsInstall ? (+ <button+ type="button"+ onClick={() => handleEidoverseInstall(feature)}+ disabled={savingId !== null || !canInstall}+ className="shrink-0 inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded transition-colors"+ >+ {installing ? 'Installing…' : (setup?.partial ? 'Resume install' : 'Install & enable')}+ </button>+ ) : (+ <ToggleSwitch+ enabled={feature.enabled}+ onChange={() => handleToggle(feature)}+ disabled={savingId !== null}+ ariaLabel={`${feature.enabled ? 'Disable' : 'Enable'} ${feature.label} on this instance`}+ className="mt-1"+ />+ )}</div>);})}diff --git a/client/src/components/settings/InstanceFeaturesTab.test.jsx b/client/src/components/settings/InstanceFeaturesTab.test.jsxindex 232f3d2cf5..05fcee345b 100644--- a/client/src/components/settings/InstanceFeaturesTab.test.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.test.jsx@@ -1,9 +1,11 @@import { describe, expect, it, beforeEach, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';const mock = vi.hoisted(() => ({getInstanceFeatures: vi.fn(),updateInstanceFeature: vi.fn(),+ installEidoverseFeature: vi.fn(),}));vi.mock('../../services/api', () => mock);@@ -29,6 +31,24 @@ const JIRA_FEATURE = {configured: true,};+const EIDOVERSE_FEATURE = {+ id: 'eidoverse',+ label: 'Eidoverse Worlds',+ description: 'An optional shared 3D world for you and your agents.',+ enabled: false,+ source: 'default',+ setup: {+ installed: false,+ partial: false,+ bunAvailable: true,+ registryAvailable: true,+ appId: null,+ uiPort: 8940,+ runtimeStatus: 'not_registered',+ worldsRepoUrl: 'https://github.com/anima-research/eidoverse-worlds',+ },+};+describe('InstanceFeaturesTab', () => {beforeEach(() => {vi.clearAllMocks();@@ -37,6 +57,14 @@ describe('InstanceFeaturesTab', () => {__resetInstanceFeatureCache();mock.getInstanceFeatures.mockResolvedValue({ features: [POST_FEATURE] });mock.updateInstanceFeature.mockResolvedValue({ features: [{ ...POST_FEATURE, enabled: false, source: 'explicit' }] });+ mock.installEidoverseFeature.mockResolvedValue({+ features: [{+ ...EIDOVERSE_FEATURE,+ enabled: true,+ source: 'explicit',+ setup: { ...EIDOVERSE_FEATURE.setup, installed: true, appId: 'app-eidoverse', runtimeStatus: 'not_started' },+ }],+ });});it('shows the instance-local feature switch', async () => {@@ -74,6 +102,84 @@ describe('InstanceFeaturesTab', () => {expect(await screen.findByText(/no JIRA instance is configured yet/i)).toBeInTheDocument();});+ it('makes Eidoverse installation an explicit opt-in action', async () => {+ mock.getInstanceFeatures.mockResolvedValue({ features: [EIDOVERSE_FEATURE] });+ render(<MemoryRouter><InstanceFeaturesTab /></MemoryRouter>);++ fireEvent.click(await screen.findByRole('button', { name: 'Install & enable' }));++ await waitFor(() => expect(mock.installEidoverseFeature).toHaveBeenCalledWith(+ 'https://github.com/anima-research/eidoverse-worlds',+ { silent: true },+ ));+ expect(await screen.findByRole('link', { name: 'Manage app' })).toHaveAttribute('href', '/apps/app-eidoverse');+ expect(screen.getByText(/start it from the managed app/i)).toBeInTheDocument();+ });++ it('installs a user-selected Worlds fork', async () => {+ mock.getInstanceFeatures.mockResolvedValue({ features: [EIDOVERSE_FEATURE] });+ render(<MemoryRouter><InstanceFeaturesTab /></MemoryRouter>);++ const repoInput = await screen.findByRole('textbox', { name: 'Worlds GitHub repository' });+ fireEvent.change(repoInput, { target: { value: 'https://github.com/example-owner/eidoverse-worlds' } });+ fireEvent.click(screen.getByRole('button', { name: 'Install & enable' }));++ await waitFor(() => expect(mock.installEidoverseFeature).toHaveBeenCalledWith(+ 'https://github.com/example-owner/eidoverse-worlds',+ { silent: true },+ ));+ });++ it('keeps installation disabled for an invalid repository URL', async () => {+ mock.getInstanceFeatures.mockResolvedValue({ features: [EIDOVERSE_FEATURE] });+ render(<MemoryRouter><InstanceFeaturesTab /></MemoryRouter>);++ fireEvent.change(await screen.findByRole('textbox', { name: 'Worlds GitHub repository' }), {+ target: { value: 'https://example.com/not-github' },+ });++ expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid GitHub repository URL');+ expect(screen.getByRole('button', { name: 'Install & enable' })).toBeDisabled();+ expect(mock.installEidoverseFeature).not.toHaveBeenCalled();+ });++ it('explains that the Worlds repository is required when the field is cleared', async () => {+ mock.getInstanceFeatures.mockResolvedValue({ features: [EIDOVERSE_FEATURE] });+ render(<MemoryRouter><InstanceFeaturesTab /></MemoryRouter>);++ const repoInput = await screen.findByRole('textbox', { name: 'Worlds GitHub repository' });+ fireEvent.change(repoInput, { target: { value: '' } });++ expect(repoInput).toHaveAttribute('aria-invalid', 'true');+ expect(repoInput).toHaveAttribute('aria-describedby', 'eidoverse-worlds-repo-error');+ expect(screen.getByRole('alert')).toHaveTextContent('Enter a GitHub repository URL');+ expect(screen.getByRole('button', { name: 'Install & enable' })).toBeDisabled();+ });++ it('explains the Bun prerequisite before installation', async () => {+ mock.getInstanceFeatures.mockResolvedValue({+ features: [{ ...EIDOVERSE_FEATURE, setup: { ...EIDOVERSE_FEATURE.setup, bunAvailable: false } }],+ });+ render(<InstanceFeaturesTab />);++ expect(await screen.findByRole('button', { name: 'Install & enable' })).toBeDisabled();+ expect(screen.getByRole('link', { name: 'Install Bun' })).toHaveAttribute('href', 'https://bun.sh');+ });++ it('rechecks Eidoverse requirements after Bun is installed', async () => {+ const missingBun = { ...EIDOVERSE_FEATURE, setup: { ...EIDOVERSE_FEATURE.setup, bunAvailable: false } };+ mock.getInstanceFeatures+ .mockResolvedValueOnce({ features: [missingBun] })+ .mockResolvedValueOnce({ features: [EIDOVERSE_FEATURE] });+ render(<InstanceFeaturesTab />);++ expect(await screen.findByRole('button', { name: 'Install & enable' })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'Recheck requirements' }));++ await waitFor(() => expect(screen.getByRole('button', { name: 'Install & enable' })).toBeEnabled());+ expect(mock.getInstanceFeatures).toHaveBeenCalledTimes(2);+ });+// The sidebar and ⌘K read the same module cache; a retry that updated only// this tab would leave them in the fail-open state until a full reload.it('broadcasts a successful retry to the other consumers', async () => {diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex d5cd8db183..266b3460ca 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -73,6 +73,11 @@ export const updateInstanceFeature = (featureId, enabled, options = {}) => requebody: JSON.stringify({ enabled }),...options,});+export const installEidoverseFeature = (worldsRepoUrl, options = {}) => request('/settings/features/eidoverse/install', {+ method: 'POST',+ body: JSON.stringify({ worldsRepoUrl }),+ ...options,+});export const updateSettings = (data, options) => request('/settings', {method: 'PUT',body: JSON.stringify(data),diff --git a/docs/README.md b/docs/README.mdindex 353dc8579a..08e012ecdd 100644--- a/docs/README.md+++ b/docs/README.md@@ -44,7 +44,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)-Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)+Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 3e177dfa2c..4f36c7b97b 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -59,6 +59,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- Writers Room draft bodies — `data/writers-room/works/{workId}/drafts/{draftId}.md`. Keep `.md` file-backed; store metadata/index rows in DB.- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.+- Eidoverse world logs — `data/eidoverse/worlds`. The external Eidoverse runtime owns these append-only world files; PortOS only selects their location through `.env.portos`. They are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. The separately licensed git checkouts live under the existing re-cloneable `data/repos/` backup class.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdnew file mode 100644index 0000000000..1f313676c9--- /dev/null+++ b/docs/features/eidoverse.md@@ -0,0 +1,63 @@+# Eidoverse Worlds integration++Eidoverse Worlds is an optional, disabled-by-default PortOS feature. It is not+vendored into PortOS and is not a git submodule. Choosing **Install & enable**+under **Settings → Features** is the explicit consent boundary that downloads,+installs, and enables the runtime; the ordinary feature toggle never installs it.++## What PortOS installs++The installer keeps the two AGPL-3.0 projects as independent git checkouts. The+Worlds repository is selected per PortOS instance; the canonical upstream is+the default, while an instance owner can enter their own fork before installing:++- `data/repos/{owner}/{repo}` — the selected Worlds repository and the checkout+ PortOS registers under **Apps**. Ordinary GitHub forks retain the+ `eidoverse-worlds` repository name.+- `data/repos/anima-research/eidoverse-video` — the upstream video/runtime+ checkout used by Worlds. A fork is not required unless changes to that+ repository itself become necessary.++PortOS runs `bun install --frozen-lockfile` in the Worlds root and client, then+writes an ignored `.env.portos` file that points Worlds at the video runtime and+at its durable world store. PortOS does not copy either project's source into+the PortOS repository, combine the codebases, or relicense them; each checkout+retains its own upstream license and git history.++## Runtime and data ownership++The managed app uses port `8940` and starts with:++```text+bun --env-file=.env.portos server/server.ts+```++Installation does not start the server. Start, stop, logs, updates, and launch+links remain visible on the normal managed-app screen. Managed updates pull both+the selected Worlds checkout and its companion video runtime before using Bun's+frozen lockfile rather than npm.++Durable Eidoverse world logs live at `data/eidoverse/worlds`. This is+machine-local `file-primary` data: PortOS backups include it, but PortOS does+not federate it to peers. The git checkouts remain under `data/repos`, which is+the existing re-cloneable repository backup class.++Disabling the feature does not delete repositories, unregister the app, stop a+running process, or remove world history. It only records that this PortOS+instance is not actively using the integration. Destructive uninstall remains+an explicit manual operation.++## Network boundary++This integration is intended for the same private, single-user Tailscale trust+boundary as PortOS. Eidoverse binds its server to the host network and permits+an empty join token; do not expose this configuration to the public internet.+An instance that needs a broader trust model should configure Eidoverse access+control in that project before starting it.++## PortOS bridge boundary++This slice establishes installation and runtime management only. Persistent+Mind presence, agent identity, and dynamic PortOS buildings/assets should be+implemented as explicit adapters across the two projects' public protocols.+They must remain opt-in and must not cause provider calls at PortOS boot.diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 0f9236a260..e3beefba57 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -19191,7 +19191,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 136+ "line": 138}]},@@ -19202,7 +19202,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 178+ "line": 192}]},@@ -19213,7 +19213,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 155+ "line": 157}]},@@ -19224,7 +19224,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 172+ "line": 186}]},@@ -19235,7 +19235,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 160+ "line": 162}]},@@ -19246,7 +19246,18 @@"sources": [{"source": "server/routes/settings.js",- "line": 165+ "line": 179+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/settings/features/eidoverse/install",+ "mountPath": "/api/settings",+ "sources": [+ {+ "source": "server/routes/settings.js",+ "line": 169}]},@@ -19257,7 +19268,7 @@"sources": [{"source": "server/routes/settings.js",- "line": 149+ "line": 151}]},@@ -23477,8 +23488,8 @@],"stats": {"mounts": 145,- "operations": 2118,- "declarations": 2121,+ "operations": 2119,+ "declarations": 2122,"sourceFiles": 225}}diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex d8be5e1484..89123376a3 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -36,6 +36,12 @@ export const INSTANCE_FEATURES = Object.freeze([description: 'Sprint boards, ticket triage, and JIRA reports for apps wired to a JIRA instance.',defaultEnabled: false,}),+ Object.freeze({+ id: 'eidoverse',+ label: 'Eidoverse Worlds',+ description: 'An optional shared 3D world for you and your agents, installed as a separately managed app.',+ defaultEnabled: false,+ }),Object.freeze({id: 'gsd',label: 'GSD',diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2ec5665d26..a9bccd4699 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -255,6 +255,7 @@ export const nativeLaunchSchema = z.object({export const appSchema = z.object({name: z.string().min(1).max(100),repoPath: z.string().min(1),+ companionRepoPaths: z.array(z.string().min(1)).max(8).optional(),type: z.string().optional().default('express'),uiPort: z.number().int().min(1).max(65535).nullable().optional(),devUiPort: z.number().int().min(1).max(65535).nullable().optional(),diff --git a/server/routes/settings.js b/server/routes/settings.jsindex b08902528d..d5d702a0d9 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,9 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { assertMediaRoutingConfig } from '../services/federatedMedia/routingPolicy.js';-import { getInstanceFeatures, updateInstanceFeature } from '../services/instanceFeatures.js';+import { getInstanceFeatures, updateEidoverseWorldsRepo, updateInstanceFeature } from '../services/instanceFeatures.js';+import { installEidoverse } from '../services/eidoverse.js';+import { isGitHubRepoUrl } from '../lib/githubRepoUrl.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';@@ -161,6 +163,18 @@ router.get('/features', asyncHandler(async (_req, res) => {res.json(await getInstanceFeatures());}));+// POST /api/settings/features/eidoverse/install+// Explicit consent boundary: no Eidoverse checkout or dependency install occurs+// until the user presses Install in Settings > Features.+router.post('/features/eidoverse/install', asyncHandler(async (req, res) => {+ const { worldsRepoUrl } = validateRequest(z.object({+ worldsRepoUrl: z.string().trim().max(500).refine(isGitHubRepoUrl, 'Must be a GitHub repository URL'),+ }).strict(), req.body || {});+ const normalizedRepoUrl = await updateEidoverseWorldsRepo(worldsRepoUrl);+ await installEidoverse({ worldsRepoUrl: normalizedRepoUrl });+ res.status(201).json(await updateInstanceFeature('eidoverse', true));+}));+// PUT /api/settings/features/:featureIdrouter.put('/features/:featureId', asyncHandler(async (req, res) => {const featureId = validateRequest(instanceFeatureIdSchema, req.params.featureId);diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex 41ef8fe2c7..d348af37eb 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -44,10 +44,18 @@ vi.mock('../services/datadog.js', () => ({vi.mock('../services/jira.js', () => ({hasConfiguredInstances: vi.fn(async () => false),}));+vi.mock('../services/eidoverse.js', () => ({+ DEFAULT_EIDOVERSE_WORLDS_REPO: 'https://github.com/anima-research/eidoverse-worlds',+ normalizeEidoverseWorldsRepo: vi.fn((url) => url),+ getEidoverseStatus: vi.fn(async () => ({ installed: false, bunAvailable: true, registryAvailable: true })),+ assertEidoverseInstalled: vi.fn(async () => ({ installed: true })),+ installEidoverse: vi.fn(async () => ({ installed: true })),+}));import settingsRoutes from './settings.js';import { hasConfiguredInstances as hasConfiguredDatadogInstances } from '../services/datadog.js';import { hasConfiguredInstances as hasConfiguredJiraInstances } from '../services/jira.js';+import { installEidoverse } from '../services/eidoverse.js';const buildApp = () => {const app = express();@@ -115,6 +123,11 @@ describe('Settings routes — instance feature participation', () => {// detector responses so this default is independent of this host's setup.expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'datadog', enabled: false, source: 'auto' }));expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'jira', enabled: false, source: 'auto' }));+ expect(res.body.features).toContainEqual(expect.objectContaining({+ id: 'eidoverse',+ enabled: false,+ setup: expect.objectContaining({ installed: false }),+ }));// GSD remains enabled by default so existing app planning tabs stay// available unless the install explicitly opts out.expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'gsd', enabled: true }));@@ -163,6 +176,40 @@ describe('Settings routes — instance feature participation', () => {expect(store).toEqual({ theme: 'dark', instanceFeatures: { post: { enabled: false } } });});+ it('installs and explicitly enables Eidoverse from its consent endpoint', async () => {+ const worldsRepoUrl = 'https://github.com/example-owner/eidoverse-worlds';+ const res = await request(buildApp())+ .post('/api/settings/features/eidoverse/install')+ .send({ worldsRepoUrl });++ expect(res.status).toBe(201);+ expect(installEidoverse).toHaveBeenCalledWith({ worldsRepoUrl });+ expect(store.instanceFeatures.eidoverse.enabled).toBe(true);+ expect(store.instanceFeatures.eidoverse.worldsRepoUrl).toBe(worldsRepoUrl);+ expect(res.body.features).toContainEqual(expect.objectContaining({ id: 'eidoverse', enabled: true }));+ });++ it('rejects a non-GitHub Worlds repository', async () => {+ const res = await request(buildApp())+ .post('/api/settings/features/eidoverse/install')+ .send({ worldsRepoUrl: 'https://example.com/untrusted.git' });++ expect(res.status).toBe(400);+ expect(installEidoverse).not.toHaveBeenCalled();+ });++ it('rejects unexpected install payload fields', async () => {+ const res = await request(buildApp())+ .post('/api/settings/features/eidoverse/install')+ .send({+ worldsRepoUrl: 'https://github.com/example-owner/eidoverse-worlds',+ repository: 'unexpected',+ });++ expect(res.status).toBe(400);+ expect(installEidoverse).not.toHaveBeenCalled();+ });+it('rejects unknown feature ids and malformed enabled values', async () => {const unknown = await request(buildApp()).put('/api/settings/features/not-registered')diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex fde3bd0722..9b36b0db61 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -22,8 +22,9 @@ const updatingApps = new Set();/*** Run a full update cycle for an app:* 1. git pull --rebase --autostash- * 2. npm install in each subdir that has package.json (root, client, server)- * 3. npm run setup if the root package.json has a setup script+ * 2. install dependencies in each package directory (Bun apps use their+ * frozen lockfile; existing apps retain npm install)+ * 3. run setup with the same package manager when the script exists* 4. Restart PM2 processes** @param {object} app - The app object (must have repoPath, pm2ProcessNames, pm2Home)@@ -47,6 +48,8 @@ export async function updateApp(app, emit) {async function _doUpdate(app, emit) {const dir = app.repoPath;const steps = [];+ const packageManager = app.type === 'bun' ? 'bun' : 'npm';+ const installArgs = packageManager === 'bun' ? ['install', '--frozen-lockfile'] : ['install'];emit('git-pull', 'running', 'Pulling latest changes...');const pullResult = await gitService.pull(dir);@@ -54,13 +57,26 @@ async function _doUpdate(app, emit) {emit('git-pull', 'done', pullMsg);steps.push({ step: 'git-pull', success: true, message: pullMsg });+ const companionRepoPaths = Array.isArray(app.companionRepoPaths)+ ? [...new Set(app.companionRepoPaths)].filter((path) => path && path !== dir)+ : [];+ for (let index = 0; index < companionRepoPaths.length; index += 1) {+ const companionPath = companionRepoPaths[index];+ const stepId = `git-pull:companion-${index + 1}`;+ emit(stepId, 'running', `Pulling companion repository ${index + 1}/${companionRepoPaths.length}...`);+ const companionPull = await gitService.pull(companionPath);+ const companionMessage = companionPull.output?.trim() || 'Up to date';+ emit(stepId, 'done', companionMessage);+ steps.push({ step: stepId, success: true, message: companionMessage });+ }+for (const sub of ['', 'client', 'server', 'admin']) {const subDir = sub ? join(dir, sub) : dir;if (existsSync(join(subDir, 'package.json'))) {const label = sub || 'root';- const stepId = `npm-install:${label}`;+ const stepId = `${packageManager}-install:${label}`;emit(stepId, 'running', `Installing ${label} dependencies...`);- await runCommand('npm', ['install'], subDir);+ await runCommand(packageManager, installArgs, subDir);emit(stepId, 'done', `${label} dependencies installed`);steps.push({ step: stepId, success: true });}@@ -71,7 +87,7 @@ async function _doUpdate(app, emit) {const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));if (pkg.scripts?.setup) {emit('setup', 'running', 'Running setup...');- await runCommand('npm', ['run', 'setup'], dir);+ await runCommand(packageManager, ['run', 'setup'], dir);emit('setup', 'done', 'Setup complete');steps.push({ step: 'setup', success: true });}diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.jsnew file mode 100644index 0000000000..d43443894c--- /dev/null+++ b/server/services/appUpdater.test.js@@ -0,0 +1,57 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const mock = vi.hoisted(() => ({+ pull: vi.fn(),+ spawn: vi.fn(),+ restart: vi.fn(),+}));++vi.mock('./git.js', () => ({ pull: mock.pull }));+vi.mock('./pm2.js', () => ({ restartApp: mock.restart }));+vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawnOrThrow: mock.spawn }));++import { updateApp } from './appUpdater.js';++describe('managed app updates', () => {+ let repo;++ beforeEach(async () => {+ vi.clearAllMocks();+ repo = await mkdtemp(join(tmpdir(), 'portos-app-updater-'));+ await mkdir(join(repo, 'client'));+ await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { setup: 'example-setup' } }));+ await writeFile(join(repo, 'client', 'package.json'), JSON.stringify({}));+ mock.pull.mockResolvedValue({ output: 'Already up to date' });+ mock.spawn.mockResolvedValue({ stdout: '', stderr: '' });+ mock.restart.mockResolvedValue({ success: true });+ });++ afterEach(async () => {+ await rm(repo, { recursive: true, force: true });+ });++ it('uses Bun and its frozen lockfile for Bun-managed apps', async () => {+ const emit = vi.fn();+ const companionRepo = join(repo, '..', 'eidoverse-video');+ const result = await updateApp({+ name: 'Eidoverse Worlds',+ type: 'bun',+ repoPath: repo,+ companionRepoPaths: [companionRepo],+ pm2ProcessNames: ['eidoverse-worlds'],+ }, emit);++ expect(result.success).toBe(true);+ expect(mock.pull).toHaveBeenNthCalledWith(1, repo);+ expect(mock.pull).toHaveBeenNthCalledWith(2, companionRepo);+ expect(mock.spawn).toHaveBeenCalledWith('bun', ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: repo }));+ expect(mock.spawn).toHaveBeenCalledWith('bun', ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: join(repo, 'client') }));+ expect(mock.spawn).toHaveBeenCalledWith('bun', ['run', 'setup'], expect.objectContaining({ cwd: repo }));+ expect(mock.spawn).not.toHaveBeenCalledWith('npm', expect.anything(), expect.anything());+ expect(emit).toHaveBeenCalledWith('git-pull:companion-1', 'done', 'Already up to date');+ expect(emit).toHaveBeenCalledWith('bun-install:root', 'done', 'root dependencies installed');+ });+});diff --git a/server/services/apps.js b/server/services/apps.jsindex 1f729e995d..6b46de7a3c 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -399,6 +399,7 @@ export async function createApp(appData) {name: appData.name,description: appData.description || '',repoPath: appData.repoPath,+ companionRepoPaths: Array.isArray(appData.companionRepoPaths) ? [...appData.companionRepoPaths] : [],type: appData.type || 'unknown',uiPort: appData.uiPort || null,devUiPort: appData.devUiPort || null,diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 214a781930..5b955da4d7 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -66,6 +66,7 @@ export const CATEGORIES = {'creative-commissions': { label: 'Creative Commissions', description: 'Commission records (file mirror of the Postgres store)', archivable: true, deletable: false },'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true, purgeScope: 'category' },'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },+ 'eidoverse': { label: 'Eidoverse Worlds', description: 'Machine-local world history owned by the optional Eidoverse runtime — backed up and not federated', archivable: true, deletable: false },'fableloom': { label: 'FableLoom', description: 'Branching-narrative records (file mirror of the Postgres store)', archivable: true, deletable: false },// Another machine's conditioning images, staged for one federated render and// swept on a TTL (#4348). Not archivable for the same reason it is excludeddiff --git a/server/services/eidoverse.js b/server/services/eidoverse.jsnew file mode 100644index 0000000000..7d194f52ef--- /dev/null+++ b/server/services/eidoverse.js@@ -0,0 +1,205 @@+import { join } from 'path';+import { ServerError } from '../lib/errorHandler.js';+import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';+import { commandExists } from '../lib/commandExists.js';+import { atomicWrite, ensureDir, pathExists, PATHS } from '../lib/fileUtils.js';+import { parseGitHubUrl } from '../lib/githubRepoUrl.js';+import { cloneRepo } from './githubCloner.js';+import { createApp, getAllApps, notifyAppsChanged, updateApp } from './apps.js';+import { getAppStatusStrict } from './pm2.js';++export const DEFAULT_EIDOVERSE_WORLDS_REPO = 'https://github.com/anima-research/eidoverse-worlds';+export const EIDOVERSE_VIDEO_REPO = 'https://github.com/anima-research/eidoverse-video';+export const EIDOVERSE_PORT = 8940;+export const EIDOVERSE_PROCESS_NAME = 'eidoverse-worlds';++export function normalizeEidoverseWorldsRepo(worldsRepoUrl) {+ const parsed = parseGitHubUrl(worldsRepoUrl);+ if (!parsed) {+ throw new ServerError('Choose a valid GitHub repository for Eidoverse Worlds.', {+ status: 400,+ code: 'EIDOVERSE_REPO_INVALID',+ });+ }+ return `https://github.com/${parsed.owner}/${parsed.repo}`;+}++export function getEidoversePaths(worldsRepoUrl = DEFAULT_EIDOVERSE_WORLDS_REPO) {+ const normalizedRepoUrl = normalizeEidoverseWorldsRepo(worldsRepoUrl);+ const { owner, repo } = parseGitHubUrl(normalizedRepoUrl);+ const worlds = join(PATHS.repos, owner, repo);+ return Object.freeze({+ worlds,+ video: join(PATHS.repos, 'anima-research', 'eidoverse-video'),+ worldData: join(PATHS.data, 'eidoverse', 'worlds'),+ envFile: join(worlds, '.env.portos'),+ });+}++const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;++const managedAppFields = (paths) => ({+ name: 'Eidoverse Worlds',+ description: 'Private 3D world for a PortOS human and their agents. Installed separately under its own AGPL-3.0 license.',+ repoPath: paths.worlds,+ companionRepoPaths: [paths.video],+ type: 'bun',+ uiPort: EIDOVERSE_PORT,+ apiPort: EIDOVERSE_PORT,+ startCommands: ['bun --env-file=.env.portos server/server.ts'],+ pm2ProcessNames: [EIDOVERSE_PROCESS_NAME],+ envFile: '.env.portos',+ workTracker: 'auto',+ archived: false,+});++const envFileContents = (paths) => [+ '# Generated by PortOS. Machine-local runtime paths; do not commit this file.',+ `PORT=${EIDOVERSE_PORT}`,+ `EIDOVERSE_DIR=${JSON.stringify(paths.video)}`,+ `WORLDS_DIR=${JSON.stringify(paths.worldData)}`,+ '',+].join('\n');++const findManagedApp = (apps, paths) => apps.find((app) => app.repoPath === paths.worlds) || null;++async function registerManagedApp(paths) {+ const apps = await getAllApps();+ const existing = findManagedApp(apps, paths);+ const fields = managedAppFields(paths);+ const app = existing+ ? await updateApp(existing.id, fields)+ : await createApp(fields);+ notifyAppsChanged(existing ? 'update' : 'create', app.id);+ return app;+}++async function installDependencies(directory) {+ await bufferedSpawnOrThrow('bun', ['install', '--frozen-lockfile'], {+ cwd: directory,+ timeoutMs: INSTALL_TIMEOUT_MS,+ });+}++let installInFlight = null;++async function performInstall(worldsRepoUrl) {+ if (!await commandExists('bun')) {+ throw new ServerError('Eidoverse Worlds requires Bun. Install Bun, then retry.', {+ status: 412,+ code: 'EIDOVERSE_BUN_REQUIRED',+ });+ }++ const paths = getEidoversePaths(worldsRepoUrl);+ await Promise.all([+ cloneRepo(worldsRepoUrl),+ cloneRepo(EIDOVERSE_VIDEO_REPO),+ ]);++ await Promise.all([+ installDependencies(paths.worlds),+ installDependencies(join(paths.worlds, 'client')),+ ]);++ await ensureDir(paths.worldData);+ await atomicWrite(paths.envFile, envFileContents(paths));+ await registerManagedApp(paths);++ console.log('🌐 Eidoverse Worlds installed as a managed app');+ return getEidoverseStatus({ worldsRepoUrl });+}++/**+ * Install or resume the optional Eidoverse runtime. The two upstream projects+ * remain independent git checkouts; PortOS writes only an ignored env file and+ * a managed-app record. A process-local promise collapses double-clicks into+ * one clone/install operation.+ */+export async function installEidoverse({ worldsRepoUrl = DEFAULT_EIDOVERSE_WORLDS_REPO } = {}) {+ const normalizedRepoUrl = normalizeEidoverseWorldsRepo(worldsRepoUrl);+ if (installInFlight) return installInFlight;+ installInFlight = performInstall(normalizedRepoUrl).finally(() => {+ installInFlight = null;+ });+ return installInFlight;+}++/**+ * Read setup and runtime state without mutating either external repository.+ * `registryAvailable: false` is kept distinct from a confirmed unregistered+ * app so a damaged apps registry never invites a duplicate installation.+ */+export async function getEidoverseStatus({ worldsRepoUrl = DEFAULT_EIDOVERSE_WORLDS_REPO } = {}) {+ const normalizedRepoUrl = normalizeEidoverseWorldsRepo(worldsRepoUrl);+ const paths = getEidoversePaths(normalizedRepoUrl);+ const [+ bunAvailable,+ worldsRepo,+ videoRepo,+ rootDependencies,+ clientDependencies,+ configured,+ worldDataReady,+ registry,+ ] = await Promise.all([+ commandExists('bun'),+ pathExists(join(paths.worlds, '.git')),+ pathExists(join(paths.video, '.git')),+ pathExists(join(paths.worlds, 'node_modules')),+ pathExists(join(paths.worlds, 'client', 'node_modules')),+ pathExists(paths.envFile),+ pathExists(paths.worldData),+ getAllApps().then(+ (apps) => ({ apps, error: null }),+ (error) => ({ apps: null, error: error.message }),+ ),+ ]);++ const app = registry.apps ? findManagedApp(registry.apps, paths) : null;+ const runtime = app+ ? await getAppStatusStrict(EIDOVERSE_PROCESS_NAME, app.pm2Home).catch(() => null)+ : null;+ const appRegistered = registry.apps === null ? null : Boolean(app);+ const installed = worldsRepo+ && videoRepo+ && rootDependencies+ && clientDependencies+ && configured+ && worldDataReady+ && appRegistered === true;++ return {+ worldsRepoUrl: normalizedRepoUrl,+ installed,+ partial: !installed && [worldsRepo, videoRepo, rootDependencies, clientDependencies, configured, worldDataReady, appRegistered].some(Boolean),+ bunAvailable,+ worldsRepo,+ videoRepo,+ rootDependencies,+ clientDependencies,+ configured,+ worldDataReady,+ registryAvailable: registry.apps !== null,+ registryError: registry.error ? 'Managed-app registry unavailable' : null,+ appRegistered,+ appId: app?.id || null,+ uiPort: EIDOVERSE_PORT,+ runtimeStatus: app+ ? (runtime === null ? 'unknown' : (runtime.status === 'not_found' ? 'not_started' : runtime.status))+ : 'not_registered',+ };+}++export async function assertEidoverseInstalled(options) {+ const status = await getEidoverseStatus(options);+ if (status.installed) return status;+ throw new ServerError('Install Eidoverse Worlds before enabling the feature.', {+ status: 409,+ code: 'EIDOVERSE_NOT_INSTALLED',+ });+}++export const __resetEidoverseInstallForTests = () => {+ installInFlight = null;+};diff --git a/server/services/eidoverse.test.js b/server/services/eidoverse.test.jsnew file mode 100644index 0000000000..85c14b63ad--- /dev/null+++ b/server/services/eidoverse.test.js@@ -0,0 +1,153 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { join } from 'path';++const mock = vi.hoisted(() => ({+ existing: new Set(),+ bunAvailable: true,+ apps: [],+ registryError: null,+ cloneRepo: vi.fn(),+ spawn: vi.fn(),+ atomicWrite: vi.fn(),+ ensureDir: vi.fn(),+ createApp: vi.fn(),+ updateApp: vi.fn(),+ notifyAppsChanged: vi.fn(),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { repos: '/example/data/repos', data: '/example/data' },+ pathExists: vi.fn(async (path) => mock.existing.has(path)),+ ensureDir: mock.ensureDir,+ atomicWrite: mock.atomicWrite,+}));++vi.mock('../lib/commandExists.js', () => ({+ commandExists: vi.fn(async () => mock.bunAvailable),+}));++vi.mock('../lib/bufferedSpawn.js', () => ({+ bufferedSpawnOrThrow: mock.spawn,+}));++vi.mock('./githubCloner.js', () => ({+ cloneRepo: mock.cloneRepo,+}));++vi.mock('./apps.js', () => ({+ getAllApps: vi.fn(async () => {+ if (mock.registryError) throw mock.registryError;+ return structuredClone(mock.apps);+ }),+ createApp: mock.createApp,+ updateApp: mock.updateApp,+ notifyAppsChanged: mock.notifyAppsChanged,+}));++vi.mock('./pm2.js', () => ({+ getAppStatusStrict: vi.fn(async () => ({ status: 'not_found' })),+}));++import {+ __resetEidoverseInstallForTests,+ DEFAULT_EIDOVERSE_WORLDS_REPO,+ EIDOVERSE_VIDEO_REPO,+ getEidoversePaths,+ getEidoverseStatus,+ installEidoverse,+ normalizeEidoverseWorldsRepo,+} from './eidoverse.js';++const SELECTED_WORLDS_REPO = 'https://github.com/example-owner/eidoverse-worlds';+const selectedPaths = getEidoversePaths(SELECTED_WORLDS_REPO);++describe('Eidoverse managed-app installer', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.existing.clear();+ mock.bunAvailable = true;+ mock.apps = [];+ mock.registryError = null;+ __resetEidoverseInstallForTests();++ mock.cloneRepo.mockImplementation(async (url) => {+ mock.existing.add(url === SELECTED_WORLDS_REPO+ ? join(selectedPaths.worlds, '.git')+ : join(selectedPaths.video, '.git'));+ });+ mock.spawn.mockImplementation(async (_cmd, _args, { cwd }) => {+ mock.existing.add(join(cwd, 'node_modules'));+ return { stdout: '', stderr: '' };+ });+ mock.ensureDir.mockImplementation(async (path) => {+ mock.existing.add(path);+ });+ mock.atomicWrite.mockImplementation(async (path) => {+ mock.existing.add(path);+ });+ mock.createApp.mockImplementation(async (fields) => {+ const app = { id: 'app-eidoverse', ...fields };+ mock.apps.push(app);+ return app;+ });+ });++ it('clones separate licensed repos, installs Bun dependencies, and registers Worlds', async () => {+ const status = await installEidoverse({ worldsRepoUrl: SELECTED_WORLDS_REPO });++ expect(mock.cloneRepo).toHaveBeenCalledWith(SELECTED_WORLDS_REPO);+ expect(mock.cloneRepo).toHaveBeenCalledWith(EIDOVERSE_VIDEO_REPO);+ expect(mock.spawn).toHaveBeenCalledWith('bun', ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: selectedPaths.worlds }));+ expect(mock.spawn).toHaveBeenCalledWith('bun', ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: join(selectedPaths.worlds, 'client') }));+ expect(mock.atomicWrite).toHaveBeenCalledWith(+ selectedPaths.envFile,+ expect.stringContaining(`EIDOVERSE_DIR=${JSON.stringify(selectedPaths.video)}`),+ );+ expect(mock.createApp).toHaveBeenCalledWith(expect.objectContaining({+ name: 'Eidoverse Worlds',+ type: 'bun',+ repoPath: selectedPaths.worlds,+ companionRepoPaths: [selectedPaths.video],+ startCommands: ['bun --env-file=.env.portos server/server.ts'],+ }));+ expect(status).toMatchObject({+ installed: true,+ worldsRepoUrl: SELECTED_WORLDS_REPO,+ appId: 'app-eidoverse',+ runtimeStatus: 'not_started',+ });+ });++ it('uses the canonical upstream by default and normalizes a selected fork URL', () => {+ expect(getEidoversePaths().worlds).toBe(join('/example/data/repos', 'anima-research', 'eidoverse-worlds'));+ expect(DEFAULT_EIDOVERSE_WORLDS_REPO).toBe('https://github.com/anima-research/eidoverse-worlds');+ expect(normalizeEidoverseWorldsRepo('[email protected]:example-owner/eidoverse-worlds.git'))+ .toBe(SELECTED_WORLDS_REPO);+ });++ it('rejects non-GitHub Worlds repositories before cloning', async () => {+ await expect(installEidoverse({ worldsRepoUrl: 'https://example.com/eidoverse-worlds' }))+ .rejects.toMatchObject({ status: 400, code: 'EIDOVERSE_REPO_INVALID' });+ expect(mock.cloneRepo).not.toHaveBeenCalled();+ });++ it('refuses installation before creating files when Bun is unavailable', async () => {+ mock.bunAvailable = false;++ await expect(installEidoverse({ worldsRepoUrl: SELECTED_WORLDS_REPO }))+ .rejects.toMatchObject({ status: 412, code: 'EIDOVERSE_BUN_REQUIRED' });+ expect(mock.cloneRepo).not.toHaveBeenCalled();+ expect(mock.atomicWrite).not.toHaveBeenCalled();+ });++ it('keeps an unreadable app registry distinct from a confirmed missing registration', async () => {+ mock.registryError = new Error('apps registry unreadable');++ await expect(getEidoverseStatus()).resolves.toMatchObject({+ installed: false,+ registryAvailable: false,+ appRegistered: null,+ registryError: 'Managed-app registry unavailable',+ });+ });+});diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.jsindex 122433ce5b..7ebaf2c6d8 100644--- a/server/services/instanceFeatures.js+++ b/server/services/instanceFeatures.js@@ -1,6 +1,13 @@import { ServerError } from '../lib/errorHandler.js';+import { parseGitHubUrl } from '../lib/githubRepoUrl.js';import { INSTANCE_FEATURES, INSTANCE_FEATURE_IDS } from '../lib/instanceFeatureRegistry.js';import { isPlainObject } from '../lib/objects.js';+import {+ assertEidoverseInstalled,+ DEFAULT_EIDOVERSE_WORLDS_REPO,+ getEidoverseStatus,+ normalizeEidoverseWorldsRepo,+} from './eidoverse.js';import { getSettingsWithStatus, updateSettingsWith } from './settings.js';// Runtime resolution for the feature registry in@@ -110,12 +117,44 @@ export const resolveInstanceFeatures = (settings = {}, { corrupt = false, detect}));+const configuredEidoverseRepo = (settings) => {+ const configured = settings?.instanceFeatures?.eidoverse?.worldsRepoUrl;+ if (typeof configured !== 'string') return DEFAULT_EIDOVERSE_WORLDS_REPO;+ const parsed = parseGitHubUrl(configured);+ return parsed+ ? `https://github.com/${parsed.owner}/${parsed.repo}`+ : DEFAULT_EIDOVERSE_WORLDS_REPO;+};++const attachSetupStatus = async (features, settings) => {+ const eidoverse = await getEidoverseStatus({ worldsRepoUrl: configuredEidoverseRepo(settings) });+ return features.map((feature) => (+ feature.id === 'eidoverse' ? { ...feature, setup: eidoverse } : feature+ ));+};+export async function getInstanceFeatures() {const [{ corrupt, settings }, detected] = await Promise.all([getSettingsWithStatus(),detectFeatureConfiguration(),]);- return { features: resolveInstanceFeatures(settings, { corrupt, detected }) };+ return { features: await attachSetupStatus(resolveInstanceFeatures(settings, { corrupt, detected }), settings) };+}++export async function updateEidoverseWorldsRepo(worldsRepoUrl) {+ const normalizedRepoUrl = normalizeEidoverseWorldsRepo(worldsRepoUrl);+ await updateSettingsWith((current) => {+ const instanceFeatures = isPlainObject(current.instanceFeatures) ? current.instanceFeatures : {};+ const eidoverse = isPlainObject(instanceFeatures.eidoverse) ? instanceFeatures.eidoverse : {};+ return {+ ...current,+ instanceFeatures: {+ ...instanceFeatures,+ eidoverse: { ...eidoverse, worldsRepoUrl: normalizedRepoUrl },+ },+ };+ });+ return normalizedRepoUrl;}// The same precedence ladder as `resolveInstanceFeatures`, but probing only this@@ -136,6 +175,10 @@ export async function updateInstanceFeature(featureId, enabled) {if (!FEATURE_BY_ID.has(featureId)) {throw new ServerError(`Unknown instance feature: ${featureId}`, { status: 404, code: 'NOT_FOUND' });}+ if (featureId === 'eidoverse' && enabled) {+ const { settings } = await getSettingsWithStatus();+ await assertEidoverseInstalled({ worldsRepoUrl: configuredEidoverseRepo(settings) });+ }const settings = await updateSettingsWith((current) => {const instanceFeatures = isPlainObject(current.instanceFeatures) ? current.instanceFeatures : {};@@ -150,5 +193,5 @@ export async function updateInstanceFeature(featureId, enabled) {});const detected = await detectFeatureConfiguration();- return { features: resolveInstanceFeatures(settings, { detected }) };+ return { features: await attachSetupStatus(resolveInstanceFeatures(settings, { detected }), settings) };}diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex f89e824ae5..edea212df4 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -7,6 +7,8 @@ const mock = vi.hoisted(() => ({datadogConfigured: false,jiraConfigured: false,datadogThrows: false,+ eidoverseInstalled: false,+ assertEidoverseInstalled: vi.fn(),}));vi.mock('./settings.js', () => ({@@ -26,6 +28,18 @@ vi.mock('./jira.js', () => ({hasConfiguredInstances: vi.fn(async () => mock.jiraConfigured),}));+vi.mock('./eidoverse.js', () => ({+ DEFAULT_EIDOVERSE_WORLDS_REPO: 'https://github.com/anima-research/eidoverse-worlds',+ normalizeEidoverseWorldsRepo: vi.fn((url) => url),+ getEidoverseStatus: vi.fn(async ({ worldsRepoUrl } = {}) => ({+ installed: mock.eidoverseInstalled,+ worldsRepoUrl,+ bunAvailable: true,+ registryAvailable: true,+ })),+ assertEidoverseInstalled: mock.assertEidoverseInstalled,+}));+import {detectFeatureConfiguration,getInstanceFeatures,@@ -43,6 +57,8 @@ describe('instance features', () => {mock.datadogConfigured = false;mock.jiraConfigured = false;mock.datadogThrows = false;+ mock.eidoverseInstalled = false;+ mock.assertEidoverseInstalled.mockReset().mockResolvedValue({ installed: true });mock.updateSettingsWith.mockReset();mock.updateSettingsWith.mockImplementation(async (mutate) => {mock.settings = await mutate(structuredClone(mock.settings));@@ -55,6 +71,33 @@ describe('instance features', () => {expect(byId((await getInstanceFeatures()).features, 'post')).toMatchObject({ id: 'post', enabled: true });});+ it('keeps Eidoverse opt-in and exposes its install state separately from the flag', async () => {+ expect(byId((await getInstanceFeatures()).features, 'eidoverse')).toMatchObject({+ enabled: false,+ source: 'default',+ setup: {+ installed: false,+ bunAvailable: true,+ worldsRepoUrl: 'https://github.com/anima-research/eidoverse-worlds',+ },+ });+ });++ it('persists a normalized Worlds fork without enabling the feature', async () => {+ const selected = 'https://github.com/example-owner/eidoverse-worlds';+ const { updateEidoverseWorldsRepo } = await import('./instanceFeatures.js');++ await expect(updateEidoverseWorldsRepo(selected)).resolves.toBe(selected);+ expect(mock.settings).toEqual({ instanceFeatures: { eidoverse: { worldsRepoUrl: selected } } });+ });++ it('requires a completed Eidoverse install before enabling it', async () => {+ mock.assertEidoverseInstalled.mockRejectedValueOnce(Object.assign(new Error('not installed'), { status: 409 }));++ await expect(updateInstanceFeature('eidoverse', true)).rejects.toMatchObject({ status: 409 });+ expect(mock.updateSettingsWith).not.toHaveBeenCalled();+ });+it('resolves an explicit disable without changing POST configuration', () => {expect(byId(resolveInstanceFeatures({ instanceFeatures: { post: { enabled: false } } }), 'post')).toMatchObject({id: 'post',@@ -172,7 +215,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, gsd: true, openclaw: true, health: true, facetime: false });+ .toEqual({ post: true, datadog: true, jira: false, eidoverse: false, gsd: true, openclaw: true, health: true, facetime: false });});it('rejects an unknown feature id', async () => {diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.jsindex 0e489b0ea0..88d47d55a4 100644--- a/server/services/sharing/subscriptions.test.js+++ b/server/services/sharing/subscriptions.test.js@@ -208,9 +208,8 @@ describe('sharing/subscriptions', () => {expect((await subs.listSubscriptions({ recordId: u.id }))).toHaveLength(1);await universeBuilder.deleteUniverse(u.id);- // Listener fans out async (readState → unsubscribe → unlink → writeState);- // wait one event-loop tick + a small slack for the I/O chain to settle.- await new Promise((r) => setTimeout(r, 50));- expect(await subs.listSubscriptions({ recordId: u.id })).toEqual([]);+ await vi.waitFor(async () => {+ expect(await subs.listSubscriptions({ recordId: u.id })).toEqual([]);+ }, { timeout: 2_000, interval: 20 });});});diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.jsindex 95c30f70c5..956202d9b0 100644--- a/server/services/voice/fineTuning.test.js+++ b/server/services/voice/fineTuning.test.js@@ -79,10 +79,9 @@ describe('fineTuning', () => {status: 'running',});- for (let i = 0; i < 50; i++) {- if (getFineTuningJobStatus(startRes.jobId).status === 'completed') break;- await new Promise((r) => setTimeout(r, 20));- }+ await vi.waitFor(() => {+ expect(getFineTuningJobStatus(startRes.jobId).status).toBe('completed');+ }, { timeout: 5_000, interval: 20 });const status = getFineTuningJobStatus(startRes.jobId);expect(status.status).toBe('completed');