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: manage Eidoverse source stack versions
[._.]/ Adam Eivy84a9edf4f226
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 2f6f2d07f8..b7f35934f2 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -272,7 +272,7 @@ export default function AppDetailView() {case 'documents':return <DocumentsTab appId={appId} repoPath={app.repoPath} />;case 'git':- return <GitTab appId={appId} appName={app.name} repoPath={app.repoPath} />;+ return <GitTab appId={appId} app={app} appName={app.name} repoPath={app.repoPath} />;case 'gsd':return <GsdTab appId={appId} repoPath={app.repoPath} />;case 'issues':diff --git a/client/src/components/apps/tabs/EidoverseSourcePanel.jsx b/client/src/components/apps/tabs/EidoverseSourcePanel.jsxnew file mode 100644index 0000000000..c346f479eb--- /dev/null+++ b/client/src/components/apps/tabs/EidoverseSourcePanel.jsx@@ -0,0 +1,352 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import {+ AlertTriangle,+ CheckCircle2,+ Download,+ GitBranch,+ GitFork,+ RefreshCw,+ Server,+} from 'lucide-react';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';+import Modal from '../../ui/Modal';+import toast from '../../ui/Toast';++const statusTone = {+ current: 'bg-port-success/15 text-port-success',+ attention: 'bg-port-warning/15 text-port-warning',+ error: 'bg-port-error/15 text-port-error',+ unknown: 'bg-gray-500/15 text-gray-400',+};++function sourceStatus(source) {+ if (!source?.present) return { tone: 'error', label: 'Checkout missing' };+ if (!source.remoteFresh) return { tone: 'unknown', label: 'Remote check unavailable' };+ if (source.origin?.isFork && source.forkVsUpstream?.available === false) {+ return { tone: 'unknown', label: 'Upstream check unavailable' };+ }+ if (source.forkVsUpstream?.state === 'diverged') {+ return { tone: 'error', label: 'Fork diverged' };+ }+ const forkBehind = source.forkVsUpstream?.behind || 0;+ const localBehind = source.localVsOrigin?.behind || 0;+ if (forkBehind > 0 && localBehind > 0) {+ return { tone: 'attention', label: 'Fork and checkout behind' };+ }+ if (forkBehind > 0) {+ return { tone: 'attention', label: `Fork ${forkBehind} behind` };+ }+ if (localBehind > 0) {+ return { tone: 'attention', label: `Checkout ${localBehind} behind` };+ }+ if (source.localVsOrigin?.state === 'diverged') {+ return { tone: 'error', label: 'Checkout diverged' };+ }+ if ((source.localVsOrigin?.ahead || 0) > 0) {+ return { tone: 'attention', label: `Checkout ${source.localVsOrigin.ahead} ahead` };+ }+ if (source.origin?.hasOrigin && !source.origin.isUpstream) {+ return { tone: 'attention', label: 'Custom origin' };+ }+ return { tone: 'current', label: 'Current' };+}++const countText = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;++function RepositoryCard({ source }) {+ const status = sourceStatus(source);+ const isWorlds = source.id === 'worlds';+ const originName = source.origin?.fullName || 'configured origin';+ const upstreamName = source.upstream?.fullName || 'canonical upstream';+ const local = source.localVsOrigin;+ const fork = source.forkVsUpstream;++ return (+ <section className="rounded-xl border border-port-border bg-port-bg/50 p-4" data-testid={`eidoverse-source-${source.id}`}>+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div>+ <div className="flex items-center gap-2">+ {isWorlds ? <GitBranch size={17} className="text-port-accent" /> : <Server size={17} className="text-cyan-400" />}+ <h4 className="font-medium text-white">{source.label}</h4>+ </div>+ <p className="mt-1 text-xs text-gray-500">+ {isWorlds ? 'World and application checkout' : 'Sidecar runtime · independent checkout · not a submodule'}+ </p>+ </div>+ <span className={`rounded-full px-2 py-1 text-xs font-medium ${statusTone[status.tone]}`}>+ {status.label}+ </span>+ </div>++ {source.present ? (+ <div className="mt-4 space-y-3 text-sm">+ <div className="flex flex-wrap items-center gap-2 text-gray-400">+ <code className="rounded bg-port-card px-2 py-1 text-xs text-gray-200">+ {source.branch || 'detached'} @ {source.shortHead || 'unknown'}+ </code>+ <span className={source.clean === false ? 'text-port-warning' : 'text-gray-500'}>+ {source.clean === true ? 'clean checkout' : source.clean === false ? 'local changes' : 'worktree unknown'}+ </span>+ </div>++ <div className="flex flex-wrap items-center gap-1.5 text-xs text-gray-400" aria-label={`${source.label} repository topology`}>+ <span className="rounded bg-port-card px-2 py-1">local checkout</span>+ <span aria-hidden="true">→</span>+ <span className="rounded bg-port-card px-2 py-1">+ {originName}{source.origin?.isFork ? ' (fork)' : ''}+ </span>+ {source.origin?.isFork && (+ <>+ <span aria-hidden="true">→</span>+ <span className="rounded bg-port-card px-2 py-1">{upstreamName} (upstream)</span>+ </>+ )}+ </div>++ {local && (local.ahead > 0 || local.behind > 0) && (+ <p className="text-xs text-gray-400">+ Local checkout is {countText(local.behind, 'commit')} behind and {countText(local.ahead, 'commit')} ahead of {originName}.+ </p>+ )}+ {fork?.available && (fork.ahead > 0 || fork.behind > 0) && (+ <p className={`text-xs ${fork.state === 'diverged' ? 'text-port-error' : 'text-gray-400'}`}>+ Fork is {countText(fork.behind, 'commit')} behind and {countText(fork.ahead, 'commit')} ahead of {upstreamName}.+ </p>+ )}+ {source.remoteError && (+ <p className="flex items-start gap-1.5 text-xs text-port-warning">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />+ {source.remoteError}; the displayed remote revision may be stale.+ </p>+ )}+ {fork?.error && (+ <p className="flex items-start gap-1.5 text-xs text-port-warning">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />+ {fork.error}; fork freshness is unknown.+ </p>+ )}+ </div>+ ) : (+ <p className="mt-4 text-sm text-port-error">{source.remoteError || 'Checkout not found'}</p>+ )}+ </section>+ );+}++export default function EidoverseSourcePanel({ appId, onUpdated }) {+ const [status, setStatus] = useState(null);+ const [loading, setLoading] = useState(true);+ const [refreshing, setRefreshing] = useState(false);+ const [syncingFork, setSyncingFork] = useState(false);+ const [updating, setUpdating] = useState(false);+ const [error, setError] = useState(null);+ const [updateIntent, setUpdateIntent] = useState(null);++ const load = useCallback(async ({ initial = false } = {}) => {+ if (initial) setLoading(true);+ else setRefreshing(true);+ setError(null);+ const result = await api.getAppRepositorySources(appId, { silent: true }).catch((reason) => {+ setError(reason.message || 'Could not inspect the Eidoverse repositories');+ return null;+ });+ if (result) setStatus(result);+ setLoading(false);+ setRefreshing(false);+ return result;+ }, [appId]);++ useEffect(() => {+ load({ initial: true });+ }, [load]);++ const sources = status?.sources || [];+ const worlds = sources.find((source) => source.id === 'worlds') || null;+ const video = sources.find((source) => source.id === 'video') || null;+ const forkDiverged = worlds?.forkVsUpstream?.state === 'diverged';+ const forkNeedsSync = worlds?.origin?.isFork+ && (worlds.forkVsUpstream?.behind || 0) > 0+ && !forkDiverged;+ const remoteUnknown = sources.some((source) => (+ !source.remoteFresh+ || (source.origin?.isFork && source.forkVsUpstream?.available === false)+ ));+ const canUpdate = sources.every((source) => source.present) && status?.updatePullsBoth;+ const shouldOfferUpdate = status?.updateAvailable || remoteUnknown;+ const primaryLabel = forkNeedsSync+ ? 'Sync fork & update both'+ : worlds?.origin?.isFork ? 'Update both from fork' : 'Update both';++ const updateSummary = useMemo(() => {+ if (!status) return '';+ if (status.updateAvailable) return 'One managed update will bring the source stack forward.';+ if (remoteUnknown) return 'Remote freshness is unknown; a managed update can retry both repositories.';+ return 'Both checkouts are current.';+ }, [remoteUnknown, status]);++ const handleSyncOnly = async () => {+ setSyncingFork(true);+ const result = await api.syncAppRepositoryFork(appId, { silent: true }).catch((reason) => {+ toast.error(reason.message || 'Could not sync the Eidoverse Worlds fork');+ return null;+ });+ if (result) {+ toast.success(result.alreadyUpToDate ? 'Worlds fork is already current' : 'Worlds fork synced from upstream');+ await load();+ }+ setSyncingFork(false);+ };++ const handleManagedUpdate = async () => {+ const intent = updateIntent;+ setUpdateIntent(null);+ setUpdating(true);++ let forkReady = true;+ if (intent?.syncFork) {+ forkReady = Boolean(await api.syncAppRepositoryFork(appId, { silent: true }).catch((reason) => {+ toast.error(reason.message || 'Could not sync the Eidoverse Worlds fork');+ return null;+ }));+ }++ const result = forkReady+ ? await api.pullAndUpdateApp(appId, { silent: true }).catch((reason) => {+ toast.error(reason.message || 'Could not update Eidoverse');+ return null;+ })+ : null;+ if (result?.success) {+ toast.success('Eidoverse Worlds and Video updated; Eidoverse restarted');+ await load();+ onUpdated?.();+ }+ setUpdating(false);+ };++ return (+ <div className="rounded-xl border border-port-accent/30 bg-port-card p-4 sm:p-5">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <GitFork size={19} className="text-port-accent" />+ <h3 className="font-semibold text-white">Eidoverse source stack</h3>+ </div>+ <p className="mt-1 max-w-3xl text-sm text-gray-400">+ Worlds and Video are separate Git checkouts. Video is the runtime sidecar, not a submodule; PortOS updates both together.+ </p>+ </div>+ <button+ onClick={() => load()}+ disabled={loading || refreshing || syncingFork || updating}+ className="flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"+ >+ <RefreshCw size={15} className={refreshing ? 'animate-spin' : ''} />+ {refreshing ? 'Checking...' : 'Check sources'}+ </button>+ </div>++ {loading && !status ? (+ <div className="py-8 text-center"><BrailleSpinner text="Checking Eidoverse sources" /></div>+ ) : error && !status ? (+ <div className="mt-4 rounded-lg border border-port-error/30 bg-port-error/10 p-3 text-sm text-port-error" role="alert">+ {error}+ </div>+ ) : status ? (+ <>+ {error && (+ <div className="mt-4 rounded-lg border border-port-warning/30 bg-port-warning/10 p-3 text-sm text-port-warning" role="alert">+ {error}; showing the last source check.+ </div>+ )}+ <div className="mt-4 grid grid-cols-1 gap-3 xl:grid-cols-2">+ {worlds && <RepositoryCard source={worlds} />}+ {video && <RepositoryCard source={video} />}+ </div>++ {!status.updatePullsBoth && (+ <div className="mt-3 flex items-start gap-2 rounded-lg border border-port-error/30 bg-port-error/10 p-3 text-sm text-port-error" role="alert">+ <AlertTriangle size={16} className="mt-0.5 shrink-0" />+ This older app registration does not yet include Video in managed updates. Update PortOS and run its pending migrations before updating Eidoverse.+ </div>+ )}++ <div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-port-border pt-4">+ <div className="flex items-center gap-2 text-sm text-gray-400">+ {!status.updateAvailable && !remoteUnknown && <CheckCircle2 size={16} className="text-port-success" />}+ {updateSummary}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {worlds?.origin?.isFork && (+ <button+ onClick={handleSyncOnly}+ disabled={syncingFork || updating || forkDiverged}+ title={forkDiverged+ ? 'Reconcile the fork commits on GitHub before syncing'+ : 'Fast-forward the GitHub fork only; does not touch the checkout or restart Eidoverse'}+ className="flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"+ >+ <GitFork size={15} className={syncingFork ? 'animate-pulse' : ''} />+ {forkDiverged ? 'Fork needs reconciliation' : syncingFork ? 'Syncing fork...' : 'Sync fork only'}+ </button>+ )}+ {shouldOfferUpdate && (+ <button+ onClick={() => setUpdateIntent({ syncFork: forkNeedsSync })}+ disabled={!canUpdate || syncingFork || updating}+ className="flex min-h-[40px] items-center gap-1.5 rounded-lg bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80 disabled:opacity-50"+ >+ <Download size={16} className={updating ? 'animate-bounce' : ''} />+ {updating ? 'Updating both...' : primaryLabel}+ </button>+ )}+ </div>+ </div>+ </>+ ) : null}++ <Modal+ open={Boolean(updateIntent)}+ onClose={() => setUpdateIntent(null)}+ size="md"+ align="none"+ backdropClassName="bg-black/50"+ panelClassName="bg-port-card border border-port-border rounded-xl overflow-hidden"+ ariaLabelledBy="eidoverse-source-update-title"+ >+ <div className="flex items-center justify-between border-b border-port-border p-4">+ <h3 id="eidoverse-source-update-title" className="flex items-center gap-2 font-medium text-white">+ <Download size={18} className="text-port-accent" />+ Update the Eidoverse source stack?+ </h3>+ <button+ onClick={() => setUpdateIntent(null)}+ aria-label="Close"+ className="flex min-h-[44px] min-w-[44px] items-center justify-center text-gray-400 hover:text-white"+ >×</button>+ </div>+ <div className="space-y-3 p-4">+ <p className="text-sm text-gray-300">This managed update will:</p>+ <ul className="ml-4 list-disc space-y-1.5 text-sm text-gray-400">+ {updateIntent?.syncFork && <li>Fast-forward the Worlds fork from canonical upstream without forcing</li>}+ <li>Pull the Worlds checkout from its configured origin</li>+ <li>Pull the independent Eidoverse Video sidecar checkout</li>+ <li>Install frozen Bun dependencies</li>+ <li>Restart Eidoverse Worlds only; PortOS and its CoS agents keep running</li>+ </ul>+ </div>+ <div className="flex justify-end gap-3 border-t border-port-border p-4">+ <button onClick={() => setUpdateIntent(null)} className="px-4 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>+ <button+ onClick={handleManagedUpdate}+ className="flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80"+ >+ <Download size={16} />+ {updateIntent?.syncFork ? 'Sync and update both' : 'Update both'}+ </button>+ </div>+ </Modal>+ </div>+ );+}diff --git a/client/src/components/apps/tabs/EidoverseSourcePanel.test.jsx b/client/src/components/apps/tabs/EidoverseSourcePanel.test.jsxnew file mode 100644index 0000000000..0460f47ef4--- /dev/null+++ b/client/src/components/apps/tabs/EidoverseSourcePanel.test.jsx@@ -0,0 +1,212 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';++vi.mock('../../../services/api', () => ({+ getAppRepositorySources: vi.fn(),+ syncAppRepositoryFork: vi.fn(),+ pullAndUpdateApp: vi.fn(),+}));++import * as api from '../../../services/api';+import EidoverseSourcePanel from './EidoverseSourcePanel';++const source = ({+ id,+ label,+ branch,+ head,+ origin,+ localVsOrigin = { ahead: 0, behind: 0, state: 'current' },+ forkVsUpstream = null,+}) => ({+ id,+ label,+ present: true,+ branch,+ head,+ shortHead: head.slice(0, 7),+ clean: true,+ origin: {+ hasOrigin: true,+ isGithub: true,+ head,+ shortHead: head.slice(0, 7),+ ...origin,+ },+ upstream: {+ fullName: `anima-research/${id === 'worlds' ? 'eidoverse-worlds' : 'eidoverse-video'}`,+ branch,+ },+ localVsOrigin,+ forkVsUpstream,+ remoteFresh: true,+ remoteError: null,+});++const canonicalStatus = () => ({+ kind: 'eidoverse',+ updateAvailable: true,+ updatePullsBoth: true,+ updateRestartsApp: true,+ sources: [+ source({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ branch: 'main',+ head: '1'.repeat(40),+ origin: {+ fullName: 'anima-research/eidoverse-worlds',+ isUpstream: true,+ isFork: false,+ },+ localVsOrigin: { ahead: 0, behind: 1, state: 'behind' },+ }),+ source({+ id: 'video',+ label: 'Eidoverse Video',+ branch: 'prod-serving',+ head: '2'.repeat(40),+ origin: {+ fullName: 'anima-research/eidoverse-video',+ isUpstream: true,+ isFork: false,+ },+ }),+ ],+});++beforeEach(() => {+ vi.clearAllMocks();+ api.getAppRepositorySources.mockResolvedValue(canonicalStatus());+ api.syncAppRepositoryFork.mockResolvedValue({ synced: true, alreadyUpToDate: false });+ api.pullAndUpdateApp.mockResolvedValue({ success: true });+});++afterEach(() => cleanup());++describe('Eidoverse source stack', () => {+ it('explains and versions both independent checkouts', async () => {+ render(<EidoverseSourcePanel appId="app-eidoverse" />);++ expect(await screen.findByText('Eidoverse source stack')).toBeInTheDocument();+ expect(screen.getByText('Sidecar runtime · independent checkout · not a submodule')).toBeInTheDocument();+ expect(screen.getByTestId('eidoverse-source-worlds')).toHaveTextContent('main @ 1111111');+ expect(screen.getByTestId('eidoverse-source-worlds')).toHaveTextContent('Checkout 1 behind');+ expect(screen.getByTestId('eidoverse-source-video')).toHaveTextContent('prod-serving @ 2222222');+ expect(screen.getByTestId('eidoverse-source-video')).toHaveTextContent('Current');+ expect(screen.getByRole('button', { name: 'Update both' })).toBeInTheDocument();+ });++ it('shows local, fork, and upstream as separate version hops and can sync only the fork', async () => {+ const status = canonicalStatus();+ status.sources[0] = source({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ branch: 'main',+ head: '1'.repeat(40),+ origin: {+ fullName: 'example-owner/eidoverse-worlds',+ isUpstream: false,+ isFork: true,+ },+ forkVsUpstream: { available: true, ahead: 0, behind: 2, state: 'behind', error: null },+ });+ api.getAppRepositorySources.mockResolvedValue(status);+ render(<EidoverseSourcePanel appId="app-eidoverse" />);++ const worlds = await screen.findByTestId('eidoverse-source-worlds');+ expect(worlds).toHaveTextContent('example-owner/eidoverse-worlds (fork)');+ expect(worlds).toHaveTextContent('anima-research/eidoverse-worlds (upstream)');+ expect(screen.getByRole('button', { name: 'Sync fork & update both' })).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Sync fork only' }));+ await waitFor(() => expect(api.syncAppRepositoryFork).toHaveBeenCalledWith('app-eidoverse', { silent: true }));+ expect(api.pullAndUpdateApp).not.toHaveBeenCalled();+ });++ it('confirms that a combined update syncs the fork, pulls both repos, and restarts only Eidoverse', async () => {+ const status = canonicalStatus();+ status.sources[0] = source({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ branch: 'main',+ head: '1'.repeat(40),+ origin: {+ fullName: 'example-owner/eidoverse-worlds',+ isUpstream: false,+ isFork: true,+ },+ forkVsUpstream: { available: true, ahead: 0, behind: 2, state: 'behind', error: null },+ });+ api.getAppRepositorySources.mockResolvedValue(status);+ const onUpdated = vi.fn();+ render(<EidoverseSourcePanel appId="app-eidoverse" onUpdated={onUpdated} />);++ fireEvent.click(await screen.findByRole('button', { name: 'Sync fork & update both' }));+ const dialog = await screen.findByRole('dialog');+ expect(dialog).toHaveTextContent('Pull the independent Eidoverse Video sidecar checkout');+ expect(dialog).toHaveTextContent('Restart Eidoverse Worlds only; PortOS and its CoS agents keep running');++ fireEvent.click(screen.getByRole('button', { name: 'Sync and update both' }));+ await waitFor(() => expect(api.pullAndUpdateApp).toHaveBeenCalledWith('app-eidoverse', { silent: true }));+ expect(api.syncAppRepositoryFork).toHaveBeenCalledWith('app-eidoverse', { silent: true });+ expect(api.syncAppRepositoryFork.mock.invocationCallOrder[0])+ .toBeLessThan(api.pullAndUpdateApp.mock.invocationCallOrder[0]);+ await waitFor(() => expect(onUpdated).toHaveBeenCalledOnce());+ });++ it('refuses automatic fork sync after divergence but still permits updating from the fork as-is', async () => {+ const status = canonicalStatus();+ status.sources[0] = source({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ branch: 'main',+ head: '1'.repeat(40),+ origin: {+ fullName: 'example-owner/eidoverse-worlds',+ isUpstream: false,+ isFork: true,+ },+ forkVsUpstream: { available: true, ahead: 1, behind: 2, state: 'diverged', error: null },+ });+ api.getAppRepositorySources.mockResolvedValue(status);+ render(<EidoverseSourcePanel appId="app-eidoverse" />);++ expect(await screen.findByRole('button', { name: 'Fork needs reconciliation' })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'Update both from fork' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Update both' }));++ await waitFor(() => expect(api.pullAndUpdateApp).toHaveBeenCalledOnce());+ expect(api.syncAppRepositoryFork).not.toHaveBeenCalled();+ });++ it('never reports current when the fork-to-upstream comparison failed', async () => {+ const status = canonicalStatus();+ status.updateAvailable = false;+ status.sources[0] = source({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ branch: 'main',+ head: '1'.repeat(40),+ origin: {+ fullName: 'example-owner/eidoverse-worlds',+ isUpstream: false,+ isFork: true,+ },+ forkVsUpstream: {+ available: false,+ ahead: null,+ behind: null,+ state: 'unknown',+ error: 'Could not compare the fork with canonical upstream',+ },+ });+ api.getAppRepositorySources.mockResolvedValue(status);+ render(<EidoverseSourcePanel appId="app-eidoverse" />);++ const worlds = await screen.findByTestId('eidoverse-source-worlds');+ expect(worlds).toHaveTextContent('Upstream check unavailable');+ expect(worlds).toHaveTextContent('fork freshness is unknown');+ expect(screen.getByText('Remote freshness is unknown; a managed update can retry both repositories.')).toBeInTheDocument();+ });+});diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsxindex 9ad953a87f..45549ede34 100644--- a/client/src/components/apps/tabs/GitTab.jsx+++ b/client/src/components/apps/tabs/GitTab.jsx@@ -5,6 +5,7 @@ import Modal from '../../ui/Modal';import BrailleSpinner from '../../BrailleSpinner';import * as api from '../../../services/api';import { formatDateNumeric } from '../../../utils/formatters';+import EidoverseSourcePanel from './EidoverseSourcePanel';function buildReleasePrompt({ repoPath, appName, comparison, baseBranch, devBranch, hasChangelog }) {const commitList = comparison.commits@@ -130,7 +131,7 @@ function ConfirmModal({ open, onClose, titleId, icon, title, tone = 'accent', co);}-export default function GitTab({ appId: _appId, appName, repoPath }) {+export default function GitTab({ appId, app, appName, repoPath }) {const [gitInfo, setGitInfo] = useState(null);const [diff, setDiff] = useState('');const [showDiff, setShowDiff] = useState(false);@@ -481,6 +482,13 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {return (<div className="space-y-6">+ {app?.pm2ProcessNames?.includes('eidoverse-worlds') && (+ <EidoverseSourcePanel+ appId={appId}+ onUpdated={() => loadGitData({ includeRemote: true })}+ />+ )}+{/* Wraps rather than overflows: three actions no longer fit one phone row. */}<div className="flex flex-wrap items-center justify-between gap-2"><h2 className="text-lg font-semibold text-white">Git Status</h2>@@ -501,7 +509,7 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"><Download size={16} className={updating ? 'animate-bounce' : ''} />- {updating ? 'Updating...' : 'Update'}+ {updating ? 'Fetching...' : 'Fetch branches'}</button><buttononClick={() => {diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsxindex 4905014a00..239a59255c 100644--- a/client/src/components/apps/tabs/GitTab.test.jsx+++ b/client/src/components/apps/tabs/GitTab.test.jsx@@ -11,6 +11,9 @@ vi.mock('../../../services/api', () => ({cleanupMergedBranches: vi.fn(),resetToDefaultBranch: vi.fn(),}));+vi.mock('./EidoverseSourcePanel', () => ({+ default: ({ appId }) => <div data-testid="eidoverse-source-panel">{appId}</div>,+}));import * as api from '../../../services/api';import GitTab from './GitTab';@@ -45,6 +48,31 @@ afterEach(() => {vi.clearAllMocks();});+describe('GitTab managed repository sources', () => {+ it('shows the Eidoverse source stack only for the managed Eidoverse process', async () => {+ const { rerender } = render(+ <GitTab+ appId="app-eidoverse"+ app={{ pm2ProcessNames: ['eidoverse-worlds'] }}+ appName="Eidoverse Worlds"+ repoPath="/repo"+ />,+ );++ expect(await screen.findByTestId('eidoverse-source-panel')).toHaveTextContent('app-eidoverse');++ rerender(+ <GitTab+ appId="app-other"+ app={{ pm2ProcessNames: ['example-app'] }}+ appName="Example App"+ repoPath="/repo"+ />,+ );+ expect(screen.queryByTestId('eidoverse-source-panel')).toBeNull();+ });+});+describe('GitTab modal accessibility (issue #1090)', () => {it('opens the diff as a labeled dialog with a labeled close button', async () => {render(<GitTab appId="x" appName="App" repoPath="/repo" />);diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 399217e44f..752f1d7efa 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -4,6 +4,18 @@ import { request, API_BASE } from './apiCore.js';// Appsexport const getApps = (options) => request('/apps', options);export const getApp = (id, options) => request(`/apps/${id}`, options);+// Multi-checkout managed integrations (currently Eidoverse): returns sanitized+// local/fork/upstream revision state without exposing machine-local repo paths.+export const getAppRepositorySources = (id, options = {}) =>+ request(`/apps/${id}/repository-sources`, { silent: true, ...options });+// Fast-forward the integration's configured GitHub fork from canonical+// upstream. The server deliberately refuses divergence and never forces.+export const syncAppRepositoryFork = (id, options = {}) =>+ request(`/apps/${id}/repository-sources/sync-fork`, {+ method: 'POST',+ silent: true,+ ...options,+ });// Reverse lookup (#2991): sprite records whose publishBinding.appId targets this// app. Read-only; the caller owns a .catch fallback, so default to silent.export const getAppSpriteBindings = (id, options) =>@@ -122,7 +134,10 @@ export const openAppFolder = (id) => request(`/apps/${id}/open-folder`, { method// comes back as a real error instead of a silent `xcode://` no-op.export const openAppInXcode = (id) => request(`/apps/${id}/open-xcode`, { method: 'POST' });export const refreshAppConfig = (id) => request(`/apps/${id}/refresh-config`, { method: 'POST' });-export const pullAndUpdateApp = (id) => request(`/apps/${id}/update`, { method: 'POST' });+export const pullAndUpdateApp = (id, options = {}) => request(`/apps/${id}/update`, {+ method: 'POST',+ ...options,+});// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`// when it already renders its own error UI.export const buildApp = (id, options = {}) => request(`/apps/${id}/build`, { method: 'POST', ...options });diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex 39727b7691..bd84134208 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -31,6 +31,21 @@ After installation, the **Worlds GitHub repository** field remains available onin place, so the managed-app path, local working tree, and world data stayuntouched. The companion video checkout remains on its upstream repository.+The managed app's **Git** tab makes that two-repository topology explicit. It+shows the checked-out branch and revision for Worlds and Video, compares each+checkout with its configured origin, and—when Worlds points at an ordinary+GitHub fork—compares that fork with the canonical+`anima-research/eidoverse-worlds` upstream. A failed network comparison is+reported as unknown rather than as current.++**Sync fork only** fast-forwards the configured Worlds fork on GitHub without+changing either local checkout or restarting a process. PortOS never passes+`--force`, so a fork with its own incompatible commits is left untouched for+manual reconciliation. **Update both** pulls Worlds from its configured origin,+pulls the independent Video checkout from its own origin and branch, installs+Worlds' frozen Bun dependencies, and restarts only Eidoverse. Video is therefore+managed as a version-visible sidecar, not pinned as a PortOS submodule.+## Runtime and data ownershipThe managed app uses port `8940` and starts with the Bun executable found or@@ -201,6 +216,11 @@ reported rather than silently applied. Missing state is a fresh V2 install;invalid or newer schema state fails closed and remains pending for repair or aPortOS update.+Migration `325-eidoverse-video-companion.js` backfills the canonical Video+checkout into older Eidoverse managed-app registrations. This lets those+installations use the same two-checkout managed update path after upgrading+PortOS without rewriting their selected Worlds origin or world data.+The offline migration never touches an external checkout or calls an AIprovider. It leaves V2 pending. After restart, a deterministic reconciler runsonly when the separately managed Eidoverse process is already online. Itdiff --git a/scripts/migrations/325-eidoverse-video-companion.js b/scripts/migrations/325-eidoverse-video-companion.jsnew file mode 100644index 0000000000..81e60a3b69--- /dev/null+++ b/scripts/migrations/325-eidoverse-video-companion.js@@ -0,0 +1,48 @@+/**+ * Backfill Eidoverse Video as a managed companion checkout. Fresh installs+ * already register this field; the migration gives installs created by older+ * PortOS versions the same two-repository update behavior after upgrading.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';++const EIDOVERSE_PROCESS_NAME = 'eidoverse-worlds';++export default {+ async up({ rootDir }) {+ const appsPath = join(rootDir, 'data', 'apps.json');+ const raw = await readFile(appsPath, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw == null) return { updated: 0, reason: 'no-apps' };++ const doc = safeJSONParse(raw, null, { logError: false });+ if (!doc || typeof doc.apps !== 'object' || doc.apps === null || Array.isArray(doc.apps)) {+ console.warn('⚠️ migration 325: skipped invalid apps registry; Eidoverse companion management was not changed');+ return { updated: 0, reason: 'invalid-apps' };+ }++ const videoPath = join(rootDir, 'data', 'repos', 'anima-research', 'eidoverse-video');+ let updated = 0;+ const apps = Object.fromEntries(Object.entries(doc.apps).map(([id, app]) => {+ if (!app?.pm2ProcessNames?.includes(EIDOVERSE_PROCESS_NAME)) return [id, app];+ const companions = Array.isArray(app.companionRepoPaths)+ ? app.companionRepoPaths.filter((path) => typeof path === 'string' && path.trim())+ : [];+ if (companions.includes(videoPath)) return [id, app];+ updated += 1;+ return [id, {+ ...app,+ companionRepoPaths: [...new Set([...companions, videoPath])],+ }];+ }));++ if (updated === 0) return { updated: 0, reason: 'already-applied' };+ await atomicWrite(appsPath, { ...doc, apps });+ console.log(`🌐 migration 325: registered Eidoverse Video with ${updated} managed app${updated === 1 ? '' : 's'}`);+ return { updated };+ },+};diff --git a/scripts/migrations/325-eidoverse-video-companion.test.js b/scripts/migrations/325-eidoverse-video-companion.test.jsnew file mode 100644index 0000000000..0f6345d469--- /dev/null+++ b/scripts/migrations/325-eidoverse-video-companion.test.js@@ -0,0 +1,85 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './325-eidoverse-video-companion.js';++let rootDir;+const appsPath = () => join(rootDir, 'data', 'apps.json');+const videoPath = () => join(rootDir, 'data', 'repos', 'anima-research', 'eidoverse-video');+const readApps = async () => JSON.parse(await readFile(appsPath(), 'utf8'));++afterEach(async () => {+ vi.restoreAllMocks();+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+ rootDir = null;+});++describe('migration 325 — Eidoverse Video companion registration', () => {+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-eidoverse-companion-'));+ await mkdir(join(rootDir, 'data'), { recursive: true });+ });++ it('adds the Video checkout to an older Eidoverse managed-app record', async () => {+ await writeFile(appsPath(), JSON.stringify({+ apps: {+ 'app-eidoverse': {+ name: 'Eidoverse Worlds',+ repoPath: '/example/worlds',+ pm2ProcessNames: ['eidoverse-worlds'],+ },+ 'app-other': {+ name: 'Example App',+ companionRepoPaths: ['/example/companion'],+ pm2ProcessNames: ['example-app'],+ },+ },+ preserved: true,+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ const result = await readApps();+ expect(result.apps['app-eidoverse'].companionRepoPaths).toEqual([videoPath()]);+ expect(result.apps['app-other'].companionRepoPaths).toEqual(['/example/companion']);+ expect(result.preserved).toBe(true);+ });++ it('preserves existing companions, deduplicates, and is idempotent', async () => {+ await writeFile(appsPath(), JSON.stringify({+ apps: {+ 'app-eidoverse': {+ pm2ProcessNames: ['eidoverse-worlds'],+ companionRepoPaths: ['/example/helper', '/example/helper'],+ },+ },+ }));++ await migration.up({ rootDir });+ expect((await readApps()).apps['app-eidoverse'].companionRepoPaths)+ .toEqual(['/example/helper', videoPath()]);+ await expect(migration.up({ rootDir })).resolves.toEqual({+ updated: 0,+ reason: 'already-applied',+ });+ });++ it('does nothing when no Eidoverse app is registered', async () => {+ await writeFile(appsPath(), JSON.stringify({ apps: {} }));+ await expect(migration.up({ rootDir })).resolves.toEqual({+ updated: 0,+ reason: 'already-applied',+ });+ });++ it('fails soft without overwriting a missing or invalid registry', async () => {+ await rm(appsPath(), { force: true });+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-apps' });++ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ await writeFile(appsPath(), '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-apps' });+ expect(await readFile(appsPath(), 'utf8')).toBe('{broken');+ expect(warn).toHaveBeenCalledOnce();+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 867a480b51..9b7828fb87 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -273,7 +273,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. || `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |-| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |+| `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely classifies a checkout's `origin` against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. || `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. || `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex dc730eaec5..f5c091d37e 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -1480,6 +1480,28 @@}]},+ {+ "method": "GET",+ "path": "/api/apps/:id/repository-sources",+ "mountPath": "/api/apps",+ "sources": [+ {+ "source": "server/routes/apps/repositorySources.js",+ "line": 23+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/apps/:id/repository-sources/sync-fork",+ "mountPath": "/api/apps",+ "sources": [+ {+ "source": "server/routes/apps/repositorySources.js",+ "line": 27+ }+ ]+ },{"method": "POST","path": "/api/apps/:id/restart",@@ -23731,8 +23753,8 @@],"stats": {"mounts": 146,- "operations": 2141,- "declarations": 2144,- "sourceFiles": 226+ "operations": 2143,+ "declarations": 2146,+ "sourceFiles": 227}}diff --git a/server/lib/gitRemote.js b/server/lib/gitRemote.jsindex 0517e229e6..65bd1cd7d5 100644--- a/server/lib/gitRemote.js+++ b/server/lib/gitRemote.js@@ -104,8 +104,10 @@ export async function readOriginRemoteUrl(cwd = PATHS.root) {** Comparison is case-insensitive (GitHub treats owner/repo names as such).*/-export async function getOriginInfo(cwd = PATHS.root) {- const originUrl = await readOriginRemoteUrl(cwd);+export function classifyOriginRemote(originUrl, {+ upstreamOwner = UPSTREAM_OWNER,+ upstreamRepo = UPSTREAM_REPO,+} = {}) {if (!originUrl) {return {hasOrigin: false,@@ -140,8 +142,8 @@ export async function getOriginInfo(cwd = PATHS.root) {}const isGithub = /(^|\.)github\.com$/i.test(parsed.host);- const ownerMatchesUpstream = parsed.owner.toLowerCase() === UPSTREAM_OWNER.toLowerCase();- const repoMatchesUpstream = parsed.repo.toLowerCase() === UPSTREAM_REPO.toLowerCase();+ const ownerMatchesUpstream = parsed.owner.toLowerCase() === upstreamOwner.toLowerCase();+ const repoMatchesUpstream = parsed.repo.toLowerCase() === upstreamRepo.toLowerCase();const isUpstream = isGithub && ownerMatchesUpstream && repoMatchesUpstream;// Strict fork: same repo name, different owner, on GitHub. A renamed// GitHub repo (different name) doesn't count — `gh repo sync` would fail@@ -160,3 +162,14 @@ export async function getOriginInfo(cwd = PATHS.root) {isFork};}++/**+ * Read and classify one checkout's origin against a named canonical upstream.+ * The default remains atomantic/PortOS for the self-update callers; managed+ * integrations can supply their own owner/repo without reimplementing the+ * credential redaction and strict same-name fork rules.+ */+export async function getOriginInfo(cwd = PATHS.root, upstream = {}) {+ const originUrl = await readOriginRemoteUrl(cwd);+ return classifyOriginRemote(originUrl, upstream);+}diff --git a/server/lib/gitRemote.test.js b/server/lib/gitRemote.test.jsindex ab1e273c40..d01eb772ac 100644--- a/server/lib/gitRemote.test.js+++ b/server/lib/gitRemote.test.js@@ -10,6 +10,7 @@ vi.mock('./fileUtils.js', () => ({import { execGit } from './execGit.js';import {+ classifyOriginRemote,parseGitRemoteUrl,getOriginInfo,readOriginRemoteUrl,@@ -168,6 +169,30 @@ describe('getOriginInfo', () => {expect(info.fullName).toBe('alice/PortOS');});+ it('classifies managed integration forks against their own canonical upstream', async () => {+ execGit.mockResolvedValue({+ stdout: '[email protected]:alice/eidoverse-worlds.git\n',+ stderr: '',+ exitCode: 0,+ });++ const info = await getOriginInfo('/managed/worlds', {+ upstreamOwner: 'anima-research',+ upstreamRepo: 'eidoverse-worlds',+ });++ expect(execGit).toHaveBeenCalledWith(+ ['remote', 'get-url', 'origin'],+ '/managed/worlds',+ { ignoreExitCode: true },+ );+ expect(info).toMatchObject({+ fullName: 'alice/eidoverse-worlds',+ isUpstream: false,+ isFork: true,+ });+ });+it('does NOT classify as fork when the repo name differs (renamed/unrelated)', async () => {// Someone might fork-and-rename, or point origin at an unrelated GitHub// repo. Treating that as a fork would invoke `gh repo sync` and fail.@@ -216,6 +241,21 @@ describe('getOriginInfo', () => {});});+describe('classifyOriginRemote', () => {+ it('keeps credential redaction when classifying a non-PortOS upstream', () => {+ const info = classifyOriginRemote(+ 'https://alice:[email protected]/alice/eidoverse-worlds.git',+ { upstreamOwner: 'anima-research', upstreamRepo: 'eidoverse-worlds' },+ );++ expect(info).toMatchObject({+ originUrl: 'https://***@github.com/alice/eidoverse-worlds.git',+ fullName: 'alice/eidoverse-worlds',+ isFork: true,+ });+ });+});+describe('redactRemoteUrlCredentials', () => {it('strips https://user:token@ prefix', () => {expect(redactRemoteUrlCredentials('https://user:[email protected]/alice/PortOS.git'))diff --git a/server/routes/apps/index.js b/server/routes/apps/index.jsindex 15e1ea7619..8cb0bede21 100644--- a/server/routes/apps/index.js+++ b/server/routes/apps/index.js@@ -16,6 +16,7 @@* launch — open-editor, open-claude, open-folder, open-xcode* documents — planning-doc read/list/commit* agents — recent CoS agent history+ * repositorySources — multi-checkout version and upstream management** Route ordering is safe across sub-routers: every param route is either the* single-segment `/:id` or a deeper `/:id/...`, and the static routes@@ -38,6 +39,7 @@ import launchRoutes from './launch.js';import documentRoutes from './documents.js';import agentRoutes from './agents.js';import spriteBindingRoutes from './spriteBindings.js';+import repositorySourceRoutes from './repositorySources.js';const router = Router();@@ -53,5 +55,6 @@ router.use(launchRoutes);router.use(documentRoutes);router.use(agentRoutes);router.use(spriteBindingRoutes);+router.use(repositorySourceRoutes);export default router;diff --git a/server/routes/apps/index.test.js b/server/routes/apps/index.test.jsindex cea9ac80f7..240fe693f0 100644--- a/server/routes/apps/index.test.js+++ b/server/routes/apps/index.test.js@@ -18,6 +18,7 @@ vi.mock('./launch.js', () => ({ default: passThrough }));vi.mock('./documents.js', () => ({ default: passThrough }));vi.mock('./agents.js', () => ({ default: passThrough }));vi.mock('./spriteBindings.js', () => ({ default: passThrough }));+vi.mock('./repositorySources.js', () => ({ default: passThrough }));vi.mock('../../services/apps.js', async (importOriginal) => ({...(await importOriginal()),getAppById: vi.fn(),diff --git a/server/routes/apps/repositorySources.js b/server/routes/apps/repositorySources.jsnew file mode 100644index 0000000000..3a2d651c8a--- /dev/null+++ b/server/routes/apps/repositorySources.js@@ -0,0 +1,31 @@+/**+ * Managed repository topology and upstream actions for integrations composed+ * from more than one checkout.+ *+ * GET /:id/repository-sources → versions and origin/upstream state+ * POST /:id/repository-sources/sync-fork → fast-forward the Worlds fork only+ *+ * The first integration is Eidoverse. Keeping this on the app-management+ * surface makes the companion runtime visible without pretending it is a git+ * submodule or exposing machine-local checkout paths to the browser.+ */++import { Router } from 'express';+import { asyncHandler } from '../../lib/errorHandler.js';+import {+ getEidoverseRepositorySources,+ syncEidoverseWorldsFork,+} from '../../services/eidoverseRepositories.js';+import { loadApp } from './shared.js';++const router = Router();++router.get('/:id/repository-sources', loadApp, asyncHandler(async (req, res) => {+ res.json(await getEidoverseRepositorySources(req.loadedApp));+}));++router.post('/:id/repository-sources/sync-fork', loadApp, asyncHandler(async (req, res) => {+ res.json(await syncEidoverseWorldsFork(req.loadedApp));+}));++export default router;diff --git a/server/routes/apps/repositorySources.test.js b/server/routes/apps/repositorySources.test.jsnew file mode 100644index 0000000000..6220e85c6e--- /dev/null+++ b/server/routes/apps/repositorySources.test.js@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import repositorySourceRoutes from './repositorySources.js';++vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+}));+vi.mock('../../services/eidoverseRepositories.js', () => ({+ getEidoverseRepositorySources: vi.fn(),+ syncEidoverseWorldsFork: vi.fn(),+}));++import * as appsService from '../../services/apps.js';+import {+ getEidoverseRepositorySources,+ syncEidoverseWorldsFork,+} from '../../services/eidoverseRepositories.js';++describe('managed app repository sources routes', () => {+ let app;+ const managed = {+ id: 'app-eidoverse',+ name: 'Eidoverse Worlds',+ repoPath: '/example/worlds',+ pm2ProcessNames: ['eidoverse-worlds'],+ };++ beforeEach(() => {+ vi.clearAllMocks();+ app = express();+ app.use(express.json());+ app.use('/api/apps', repositorySourceRoutes);+ appsService.getAppById.mockResolvedValue(managed);+ });++ it('returns the repository topology for the loaded app', async () => {+ getEidoverseRepositorySources.mockResolvedValue({+ kind: 'eidoverse',+ updatePullsBoth: true,+ sources: [{ id: 'worlds' }, { id: 'video' }],+ });++ const response = await request(app).get('/api/apps/app-eidoverse/repository-sources');++ expect(response.status).toBe(200);+ expect(getEidoverseRepositorySources).toHaveBeenCalledWith(managed);+ expect(response.body.sources).toHaveLength(2);+ });++ it('syncs only the configured Worlds fork', async () => {+ syncEidoverseWorldsFork.mockResolvedValue({+ synced: true,+ fullName: 'example-owner/eidoverse-worlds',+ source: 'anima-research/eidoverse-worlds',+ branch: 'main',+ });++ const response = await request(app)+ .post('/api/apps/app-eidoverse/repository-sources/sync-fork');++ expect(response.status).toBe(200);+ expect(syncEidoverseWorldsFork).toHaveBeenCalledWith(managed);+ expect(response.body).toMatchObject({ synced: true, branch: 'main' });+ });++ it('404s before inspecting repository sources for an unknown app', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/missing/repository-sources');++ expect(response.status).toBe(404);+ expect(getEidoverseRepositorySources).not.toHaveBeenCalled();+ });+});diff --git a/server/services/eidoverseRepositories.js b/server/services/eidoverseRepositories.jsnew file mode 100644index 0000000000..7ac4699e48--- /dev/null+++ b/server/services/eidoverseRepositories.js@@ -0,0 +1,287 @@+import { join } from 'path';+import { ServerError } from '../lib/errorHandler.js';+import { pathExists, safeJSONParse } from '../lib/fileUtils.js';+import { getOriginInfo } from '../lib/gitRemote.js';+import { parseGitHubUrl } from '../lib/githubRepoUrl.js';+import {+ DEFAULT_EIDOVERSE_WORLDS_REPO,+ EIDOVERSE_PROCESS_NAME,+ EIDOVERSE_VIDEO_REPO,+ getEidoversePaths,+} from './eidoverse.js';+import { execGitSafe, fetchOrigin, resolveForgeForRepo } from './git.js';+import { execGh } from './github.js';++const WORLDS_UPSTREAM_BRANCH = 'main';+const GH_TIMEOUT_MS = 60_000;++const repoIdentity = (url) => {+ const parsed = parseGitHubUrl(url);+ return {+ owner: parsed.owner,+ repo: parsed.repo,+ fullName: `${parsed.owner}/${parsed.repo}`,+ };+};++const WORLDS_UPSTREAM = repoIdentity(DEFAULT_EIDOVERSE_WORLDS_REPO);+const VIDEO_UPSTREAM = repoIdentity(EIDOVERSE_VIDEO_REPO);++const isEidoverseApp = (app) => Boolean(app?.pm2ProcessNames?.includes(EIDOVERSE_PROCESS_NAME));++function assertEidoverseApp(app) {+ if (isEidoverseApp(app)) return;+ throw new ServerError('Repository source management is available only for the managed Eidoverse Worlds app.', {+ status: 400,+ code: 'EIDOVERSE_APP_REQUIRED',+ });+}++const comparisonState = (ahead, behind) => {+ if (ahead > 0 && behind > 0) return 'diverged';+ if (behind > 0) return 'behind';+ if (ahead > 0) return 'ahead';+ return 'current';+};++function parseRevisionCounts(result) {+ if (result.exitCode !== 0) return null;+ const [aheadText, behindText] = result.stdout.trim().split(/\s+/);+ const ahead = Number.parseInt(aheadText, 10);+ const behind = Number.parseInt(behindText, 10);+ if (!Number.isInteger(ahead) || !Number.isInteger(behind)) return null;+ return { ahead, behind, state: comparisonState(ahead, behind) };+}++async function inspectCheckout({ id, label, repoPath, upstream, upstreamBranch }) {+ const present = typeof repoPath === 'string'+ && repoPath.trim().length > 0+ && await pathExists(join(repoPath, '.git'));+ if (!present) {+ return {+ id,+ label,+ present: false,+ branch: null,+ head: null,+ shortHead: null,+ clean: null,+ origin: null,+ upstream: { fullName: upstream.fullName, branch: upstreamBranch || null },+ localVsOrigin: null,+ remoteFresh: false,+ remoteError: 'Checkout not found',+ };+ }++ const [branchResult, headResult, worktreeResult, origin] = await Promise.all([+ execGitSafe(['rev-parse', '--abbrev-ref', 'HEAD'], repoPath, { ignoreExitCode: true }),+ execGitSafe(['rev-parse', 'HEAD'], repoPath, { ignoreExitCode: true }),+ execGitSafe(['status', '--porcelain'], repoPath, { ignoreExitCode: true }),+ getOriginInfo(repoPath, { upstreamOwner: upstream.owner, upstreamRepo: upstream.repo }),+ ]);+ const branchName = branchResult.exitCode === 0 ? branchResult.stdout.trim() : null;+ const branch = branchName && branchName !== 'HEAD' ? branchName : null;+ const head = headResult.exitCode === 0 ? headResult.stdout.trim() : null;+ const clean = worktreeResult.exitCode === 0 ? worktreeResult.stdout.trim().length === 0 : null;++ const fetchResult = origin.hasOrigin+ ? await fetchOrigin(repoPath).then(+ () => ({ fresh: true, error: null }),+ () => ({ fresh: false, error: 'Could not refresh the remote repository' }),+ )+ : { fresh: false, error: 'No origin remote configured' };++ const originRef = branch ? `refs/remotes/origin/${branch}` : null;+ const [originHeadResult, countsResult] = originRef+ ? await Promise.all([+ execGitSafe(['rev-parse', '--verify', originRef], repoPath, { ignoreExitCode: true }),+ execGitSafe(['rev-list', '--left-right', '--count', `HEAD...${originRef}`], repoPath, { ignoreExitCode: true }),+ ])+ : [null, null];+ const originHead = originHeadResult?.exitCode === 0 ? originHeadResult.stdout.trim() : null;+ const localVsOrigin = countsResult ? parseRevisionCounts(countsResult) : null;++ return {+ id,+ label,+ present: true,+ branch,+ head,+ shortHead: head?.slice(0, 7) || null,+ clean,+ origin: {+ hasOrigin: origin.hasOrigin,+ fullName: origin.fullName,+ url: origin.originUrl,+ isGithub: origin.isGithub,+ isUpstream: origin.isUpstream,+ isFork: origin.isFork,+ head: originHead,+ shortHead: originHead?.slice(0, 7) || null,+ },+ upstream: {+ fullName: upstream.fullName,+ branch: upstreamBranch || branch,+ },+ localVsOrigin,+ remoteFresh: fetchResult.fresh,+ remoteError: fetchResult.error,+ };+}++async function compareForkWithUpstream(checkout) {+ if (!checkout?.origin?.isFork || !checkout.origin.fullName) return null;+ const branch = checkout.upstream.branch || WORLDS_UPSTREAM_BRANCH;+ const basehead = encodeURIComponent(+ `${WORLDS_UPSTREAM.owner}:${branch}...${checkout.origin.fullName.split('/')[0]}:${branch}`,+ );+ const forge = await resolveForgeForRepo(checkout.repoPath).catch(() => null);+ const raw = await execGh([+ 'api',+ `repos/${WORLDS_UPSTREAM.fullName}/compare/${basehead}`,+ '--jq',+ '{status: .status, ahead: .ahead_by, behind: .behind_by}',+ ], GH_TIMEOUT_MS, {+ cwd: checkout.repoPath,+ env: forge?.env || process.env,+ }).catch(() => null);+ const parsed = safeJSONParse(raw, null);+ if (!parsed+ || !Number.isInteger(parsed.ahead)+ || !Number.isInteger(parsed.behind)) {+ return {+ available: false,+ ahead: null,+ behind: null,+ state: 'unknown',+ error: 'Could not compare the fork with canonical upstream',+ };+ }+ return {+ available: true,+ ahead: parsed.ahead,+ behind: parsed.behind,+ state: comparisonState(parsed.ahead, parsed.behind),+ error: null,+ };+}++/**+ * Report the two checkouts that make up one Eidoverse installation. No local+ * paths are returned: the app-management UI needs versions and topology, not+ * machine identity. Network failures stay distinct from a confirmed current+ * repository so a stale ref is never presented as "up to date".+ */+export async function getEidoverseRepositorySources(app) {+ assertEidoverseApp(app);+ const registeredCompanions = Array.isArray(app.companionRepoPaths)+ ? app.companionRepoPaths.filter((path) => typeof path === 'string' && path.trim())+ : [];+ const videoPath = getEidoversePaths().video;++ const [worldsBase, video] = await Promise.all([+ inspectCheckout({+ id: 'worlds',+ label: 'Eidoverse Worlds',+ repoPath: app.repoPath,+ upstream: WORLDS_UPSTREAM,+ upstreamBranch: WORLDS_UPSTREAM_BRANCH,+ }),+ inspectCheckout({+ id: 'video',+ label: 'Eidoverse Video',+ repoPath: videoPath,+ upstream: VIDEO_UPSTREAM,+ upstreamBranch: null,+ }),+ ]);+ // Kept server-only above; callers receive no absolute checkout path.+ const worlds = {+ ...worldsBase,+ forkVsUpstream: await compareForkWithUpstream({ ...worldsBase, repoPath: app.repoPath }),+ };++ const updateAvailable = [worlds, video].some((source) => source.localVsOrigin?.behind > 0)+ || (worlds.forkVsUpstream?.behind || 0) > 0;++ return {+ kind: 'eidoverse',+ checkedAt: new Date().toISOString(),+ updateAvailable,+ updatePullsBoth: registeredCompanions.includes(videoPath),+ updateRestartsApp: true,+ sources: [worlds, video],+ };+}++/**+ * Fast-forward the configured Worlds fork from canonical upstream. This is a+ * remote-only action: it never touches the checkout and deliberately omits+ * `--force`, so GitHub refuses instead of discarding fork commits.+ */+export async function syncEidoverseWorldsFork(app) {+ assertEidoverseApp(app);+ const origin = await getOriginInfo(app.repoPath, {+ upstreamOwner: WORLDS_UPSTREAM.owner,+ upstreamRepo: WORLDS_UPSTREAM.repo,+ });+ if (!origin.hasOrigin) {+ throw new ServerError('The Eidoverse Worlds checkout has no Git origin.', {+ status: 400,+ code: 'NO_ORIGIN',+ });+ }+ if (!origin.isGithub) {+ throw new ServerError('Eidoverse fork sync is available only for GitHub origins.', {+ status: 400,+ code: 'NOT_GITHUB',+ });+ }+ if (origin.isUpstream) {+ throw new ServerError(`The Worlds origin is already ${WORLDS_UPSTREAM.fullName}.`, {+ status: 400,+ code: 'ALREADY_UPSTREAM',+ });+ }+ if (!origin.isFork) {+ throw new ServerError(+ `The Worlds origin is not a same-name fork of ${WORLDS_UPSTREAM.fullName}.`,+ { status: 400, code: 'NOT_A_FORK' },+ );+ }++ const forge = await resolveForgeForRepo(app.repoPath).catch(() => null);+ const output = await execGh([+ 'repo',+ 'sync',+ origin.fullName,+ '--source',+ WORLDS_UPSTREAM.fullName,+ '--branch',+ WORLDS_UPSTREAM_BRANCH,+ ], GH_TIMEOUT_MS, {+ cwd: app.repoPath,+ env: forge?.env || process.env,+ }).catch((error) => {+ if (/fast forward|diverge|non-fast/i.test(error.message || '')) {+ throw new ServerError(+ `The ${origin.fullName} fork has commits that cannot be fast-forwarded from ${WORLDS_UPSTREAM.fullName}. Reconcile those commits on GitHub before syncing.`,+ { status: 409, code: 'FORK_DIVERGED' },+ );+ }+ throw new ServerError(`Could not sync the Eidoverse Worlds fork: ${error.message}`, {+ status: 502,+ code: 'FORK_SYNC_FAILED',+ });+ });++ return {+ synced: true,+ alreadyUpToDate: /up to date/i.test(output),+ fullName: origin.fullName,+ source: WORLDS_UPSTREAM.fullName,+ branch: WORLDS_UPSTREAM_BRANCH,+ message: output.trim(),+ };+}diff --git a/server/services/eidoverseRepositories.test.js b/server/services/eidoverseRepositories.test.jsnew file mode 100644index 0000000000..52e7e10f73--- /dev/null+++ b/server/services/eidoverseRepositories.test.js@@ -0,0 +1,252 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mock = vi.hoisted(() => ({+ pathExists: vi.fn(),+ execGit: vi.fn(),+ getOriginInfo: vi.fn(),+ fetchOrigin: vi.fn(),+ resolveForgeForRepo: vi.fn(),+ execGh: vi.fn(),+}));++vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ pathExists: mock.pathExists,+}));+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: mock.getOriginInfo }));+vi.mock('./git.js', () => ({+ execGitSafe: mock.execGit,+ fetchOrigin: mock.fetchOrigin,+ resolveForgeForRepo: mock.resolveForgeForRepo,+}));+vi.mock('./github.js', () => ({ execGh: mock.execGh }));+vi.mock('./eidoverse.js', () => ({+ DEFAULT_EIDOVERSE_WORLDS_REPO: 'https://github.com/anima-research/eidoverse-worlds',+ EIDOVERSE_PROCESS_NAME: 'eidoverse-worlds',+ EIDOVERSE_VIDEO_REPO: 'https://github.com/anima-research/eidoverse-video',+ getEidoversePaths: () => ({ video: '/example/video' }),+}));++import {+ getEidoverseRepositorySources,+ syncEidoverseWorldsFork,+} from './eidoverseRepositories.js';++const WORLDS = '/example/worlds';+const VIDEO = '/example/video';+const managedApp = {+ id: 'app-eidoverse',+ name: 'Eidoverse Worlds',+ repoPath: WORLDS,+ companionRepoPaths: [VIDEO],+ pm2ProcessNames: ['eidoverse-worlds'],+};+const HEADS = {+ [WORLDS]: '1'.repeat(40),+ [VIDEO]: '2'.repeat(40),+};+const BRANCHES = {+ [WORLDS]: 'main',+ [VIDEO]: 'prod-serving',+};++const canonicalOrigin = (repo) => ({+ hasOrigin: true,+ originUrl: `https://github.com/anima-research/${repo}.git`,+ fullName: `anima-research/${repo}`,+ isGithub: true,+ isUpstream: true,+ isFork: false,+});++describe('Eidoverse repository source management', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.pathExists.mockResolvedValue(true);+ mock.fetchOrigin.mockResolvedValue(true);+ mock.resolveForgeForRepo.mockResolvedValue({ env: { GH_TOKEN: 'test-token' } });+ mock.getOriginInfo.mockImplementation(async (repoPath) => (+ repoPath === WORLDS+ ? canonicalOrigin('eidoverse-worlds')+ : canonicalOrigin('eidoverse-video')+ ));+ mock.execGit.mockImplementation(async (args, repoPath) => {+ if (args[0] === 'status') return { stdout: '', stderr: '', exitCode: 0 };+ if (args[0] === 'rev-list') {+ return {+ stdout: repoPath === WORLDS ? '0\t1\n' : '0\t0\n',+ stderr: '',+ exitCode: 0,+ };+ }+ if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {+ return { stdout: `${BRANCHES[repoPath]}\n`, stderr: '', exitCode: 0 };+ }+ if (args[0] === 'rev-parse' && args[1] === '--verify') {+ return { stdout: `${repoPath === WORLDS ? '3'.repeat(40) : HEADS[repoPath]}\n`, stderr: '', exitCode: 0 };+ }+ if (args[0] === 'rev-parse' && args[1] === 'HEAD') {+ return { stdout: `${HEADS[repoPath]}\n`, stderr: '', exitCode: 0 };+ }+ return { stdout: '', stderr: '', exitCode: 1 };+ });+ });++ it('reports Worlds and the independently versioned Video companion without leaking checkout paths', async () => {+ const result = await getEidoverseRepositorySources(managedApp);++ expect(result).toMatchObject({+ kind: 'eidoverse',+ updateAvailable: true,+ updatePullsBoth: true,+ updateRestartsApp: true,+ sources: [+ {+ id: 'worlds',+ branch: 'main',+ shortHead: '1111111',+ localVsOrigin: { ahead: 0, behind: 1, state: 'behind' },+ origin: { fullName: 'anima-research/eidoverse-worlds', isUpstream: true },+ },+ {+ id: 'video',+ branch: 'prod-serving',+ shortHead: '2222222',+ localVsOrigin: { ahead: 0, behind: 0, state: 'current' },+ origin: { fullName: 'anima-research/eidoverse-video', isUpstream: true },+ },+ ],+ });+ expect(JSON.stringify(result)).not.toContain('/example/');+ });++ it('uses the canonical Video path even when another companion is registered first', async () => {+ const result = await getEidoverseRepositorySources({+ ...managedApp,+ companionRepoPaths: ['/example/other-helper', VIDEO],+ });++ expect(mock.execGit).toHaveBeenCalledWith(+ ['rev-parse', '--abbrev-ref', 'HEAD'],+ VIDEO,+ { ignoreExitCode: true },+ );+ expect(result.updatePullsBoth).toBe(true);+ expect(result.sources[1]).toMatchObject({ id: 'video', shortHead: '2222222' });+ });++ it('reports a detached checkout without comparing it to origin/HEAD', async () => {+ const normalExecGit = mock.execGit.getMockImplementation();+ mock.execGit.mockImplementation((args, repoPath) => {+ if (repoPath === WORLDS && args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {+ return Promise.resolve({ stdout: 'HEAD\n', stderr: '', exitCode: 0 });+ }+ return normalExecGit(args, repoPath);+ });++ const result = await getEidoverseRepositorySources(managedApp);++ expect(result.sources[0]).toMatchObject({ branch: null, localVsOrigin: null });+ expect(mock.execGit).not.toHaveBeenCalledWith(+ ['rev-parse', '--verify', 'refs/remotes/origin/HEAD'],+ WORLDS,+ { ignoreExitCode: true },+ );+ });++ it('distinguishes the local-to-fork gap from the fork-to-upstream gap', async () => {+ mock.getOriginInfo.mockImplementation(async (repoPath) => (+ repoPath === WORLDS+ ? {+ hasOrigin: true,+ originUrl: '[email protected]:example-owner/eidoverse-worlds.git',+ fullName: 'example-owner/eidoverse-worlds',+ isGithub: true,+ isUpstream: false,+ isFork: true,+ }+ : canonicalOrigin('eidoverse-video')+ ));+ mock.execGh.mockResolvedValue('{"status":"diverged","ahead":2,"behind":3}');++ const result = await getEidoverseRepositorySources(managedApp);+ const worlds = result.sources[0];++ expect(worlds.localVsOrigin).toMatchObject({ ahead: 0, behind: 1 });+ expect(worlds.forkVsUpstream).toEqual({+ available: true,+ ahead: 2,+ behind: 3,+ state: 'diverged',+ error: null,+ });+ expect(mock.execGh).toHaveBeenCalledWith(+ expect.arrayContaining([+ 'repos/anima-research/eidoverse-worlds/compare/anima-research%3Amain...example-owner%3Amain',+ ]),+ 60000,+ expect.objectContaining({ cwd: WORLDS }),+ );+ });++ it('keeps a failed remote refresh distinct from a confirmed current checkout', async () => {+ mock.fetchOrigin.mockRejectedValue(new Error('offline'));++ const result = await getEidoverseRepositorySources(managedApp);++ expect(result.sources[0]).toMatchObject({+ remoteFresh: false,+ remoteError: 'Could not refresh the remote repository',+ });+ });++ it('fast-forwards the Worlds fork without ever passing --force', async () => {+ mock.getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ fullName: 'example-owner/eidoverse-worlds',+ isGithub: true,+ isUpstream: false,+ isFork: true,+ });+ mock.execGh.mockResolvedValue('Synced the main branch');++ const result = await syncEidoverseWorldsFork(managedApp);++ const args = mock.execGh.mock.calls[0][0];+ expect(args).toEqual([+ 'repo', 'sync', 'example-owner/eidoverse-worlds',+ '--source', 'anima-research/eidoverse-worlds',+ '--branch', 'main',+ ]);+ expect(args).not.toContain('--force');+ expect(result).toMatchObject({+ synced: true,+ fullName: 'example-owner/eidoverse-worlds',+ source: 'anima-research/eidoverse-worlds',+ });+ });++ it('fails closed when GitHub says the fork cannot be fast-forwarded', async () => {+ mock.getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ fullName: 'example-owner/eidoverse-worlds',+ isGithub: true,+ isUpstream: false,+ isFork: true,+ });+ mock.execGh.mockRejectedValue(new Error('destination would not be a fast forward'));++ await expect(syncEidoverseWorldsFork(managedApp)).rejects.toMatchObject({+ status: 409,+ code: 'FORK_DIVERGED',+ });+ });++ it('refuses the Eidoverse-only contract for an unrelated managed app', async () => {+ await expect(getEidoverseRepositorySources({+ ...managedApp,+ pm2ProcessNames: ['example-app'],+ })).rejects.toMatchObject({ status: 400, code: 'EIDOVERSE_APP_REQUIRED' });+ expect(mock.fetchOrigin).not.toHaveBeenCalled();+ });+});