Skip to content

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

fix: route client port literals through a client-side PORTS mirror (#5712)

Adam Eivy25d6e46da180
diff --git a/client/src/components/NetworkSetupGuide.jsx b/client/src/components/NetworkSetupGuide.jsx
index 065891a804..0ec034cbe7 100644
--- a/client/src/components/NetworkSetupGuide.jsx
+++ b/client/src/components/NetworkSetupGuide.jsx
@@ -10,6 +10,7 @@ import {
RefreshCw,
} from 'lucide-react';
import toast from './ui/Toast';
+import { PORTS } from '../lib/ports.js';
import {
handleSelfRestart,
PORTOS_APP_ID,
@@ -47,7 +48,7 @@ export default function NetworkSetupGuide({ networkExposure, compact = false })
if (!setup || !Array.isArray(setup.steps)) return null;
- const port = networkExposure?.bind?.port || 5555;
+ const port = networkExposure?.bind?.port || PORTS.API;
const visibleSteps = compact
? [setup.nextStep || setup.steps.at(-1)].filter(Boolean)
: setup.steps;
diff --git a/client/src/components/instances/TailnetHelpBanner.jsx b/client/src/components/instances/TailnetHelpBanner.jsx
index 6e5657a631..816965a05a 100644
--- a/client/src/components/instances/TailnetHelpBanner.jsx
+++ b/client/src/components/instances/TailnetHelpBanner.jsx
@@ -8,6 +8,7 @@ import {
} from 'lucide-react';
import Pill from '../ui/Pill';
import NetworkSetupGuide from '../NetworkSetupGuide.jsx';
+import { PORTS } from '../../lib/ports.js';
import { useLocalStorageBool } from '../../hooks/useLocalStorageBool';
export default function TailnetHelpBanner({ tailnetInfo, networkExposure }) {
@@ -67,9 +68,9 @@ export default function TailnetHelpBanner({ tailnetInfo, networkExposure }) {
<p className="font-medium text-gray-300">Peer DNS after this machine is secure</p>
<p className="mt-1">
Use the suggested MagicDNS host on each peer below to switch federation from
- <span className="font-mono text-gray-300"> http://{'<ip>'}:5555 </span>
+ <span className="font-mono text-gray-300"> http://{'<ip>'}:{PORTS.API} </span>
to its browser-trusted
- <span className="font-mono text-gray-300"> https://{'<host>'}.{tailnetInfo?.suffix || '<tailnet>'}.ts.net:5555</span>
+ <span className="font-mono text-gray-300"> https://{'<host>'}.{tailnetInfo?.suffix || '<tailnet>'}.ts.net:{PORTS.API}</span>
{' '}address. “Use IP only” reverts that peer to its IP.
</p>
</div>
diff --git a/client/src/components/providers/FleetProviderSetup.jsx b/client/src/components/providers/FleetProviderSetup.jsx
index 8afca9f19e..bdcb537475 100644
--- a/client/src/components/providers/FleetProviderSetup.jsx
+++ b/client/src/components/providers/FleetProviderSetup.jsx
@@ -6,6 +6,7 @@ import useDrawerTab from '../../hooks/useDrawerTab';
import { FormField } from '../ui/FormField';
import Banner from '../ui/Banner';
import { isLocalEndpoint, isPrivateNetworkEndpoint } from '../../utils/providers';
+import { PORTS } from '../../lib/ports.js';
const FLEET_TABS = [
{ id: 'architecture', label: 'Architecture' },
@@ -229,7 +230,7 @@ export default function FleetProviderSetup({ peers = [], onClose, onCreate }) {
</FormField>
)}
- <FormField label="GPU host endpoint" hint="Use the runtime endpoint, not the PortOS :5555 address.">
+ <FormField label="GPU host endpoint" hint={`Use the runtime endpoint, not the PortOS :${PORTS.API} address.`}>
<input
type="text"
value={endpointInput}
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index fe302282b9..132cd08e6d 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -18,6 +18,7 @@ import BrailleSpinner from '../BrailleSpinner';
import LocalSetupPanel from './LocalSetupPanel';
import useDrawerTab from '../../hooks/useDrawerTab';
import { isLoopbackHost } from '../../lib/loopbackHost.js';
+import { PORTS } from '../../lib/ports.js';
import {
getSettings, updateSettings, getImageGenStatus, generateImage,
registerTool, updateTool, getToolsList,
@@ -603,8 +604,9 @@ export function ImageGenTab() {
if (loading) return <BrailleSpinner text="Loading image gen settings" />;
// The advertised A1111 URL must be the canonical user-facing endpoint
- // (`<tailscale-host>.<tailnet>.ts.net:5555` / `<tailscale-ip>:5555`), not
- // the loopback HTTP mirror at :5553 or a localhost dev URL — those aren't
+ // (`<tailscale-host>.<tailnet>.ts.net:PORTS.API` / `<tailscale-ip>:PORTS.API`),
+ // not the loopback HTTP mirror on PORTS.API_LOCAL or a localhost dev URL —
+ // those aren't
// reachable from other tailnet machines.
const advertisedA1111Url = (() => {
if (typeof window === 'undefined') return null;
@@ -612,11 +614,11 @@ export function ImageGenTab() {
// Local dev / loopback mirror — we can't infer the tailnet hostname
// from the browser; tell the user to look it up.
if (isLoopbackHost(h)) return null;
- // Real tailnet host — use the canonical user-facing port (:5555) and
+ // Real tailnet host — use the canonical user-facing API port and
// match the currently-active scheme so the hint works in both HTTPS-on
// (Tailscale cert provisioned) and HTTP-only PortOS deployments.
const scheme = window.location.protocol === 'http:' ? 'http' : 'https';
- return `${scheme}://${h}:5555`;
+ return `${scheme}://${h}:${PORTS.API}`;
})();
return (
@@ -1283,7 +1285,7 @@ export function ImageGenTab() {
{advertisedA1111Url ? (
<>Other machines should set their SD API URL to <code className="text-gray-300">{advertisedA1111Url}</code></>
) : (
- <>Other machines should set their SD API URL to <code className="text-gray-300">https://&lt;your-tailscale-host&gt;:5555</code> (run <code className="text-gray-300">tailscale status</code> on this machine to see the hostname).</>
+ <>Other machines should set their SD API URL to <code className="text-gray-300">https://&lt;your-tailscale-host&gt;:{PORTS.API}</code> (run <code className="text-gray-300">tailscale status</code> on this machine to see the hostname).</>
)}
</div>
</div>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9e2ab91277..a9f3f677b2 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -138,6 +138,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `assetProvenance.js` | Mirror of `server/lib/assetProvenance.js`. Stamp-time model/LoRA license provenance + rollup for collection/export Attribution. Unknown license displays as "unknown". |
| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
+| `ports.js` | `PORTS` (`API` 5555 / `API_LOCAL` 5553 / `UI` 5554) + `DEFAULT_PEER_PORT` — client mirror of the UI-facing subset of the `PORTS` object in `ecosystem.config.cjs` (the source of truth; `server/lib/ports.js` is the server mirror). The browser bundle can't import either, so use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL. `ports.parity.test.js` fails if the mirror drifts. |
| `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 94ea0a0e68..dea5e7b13b 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -111,6 +111,7 @@ export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './morsePractice.js';
export * from './moodBoardItemSrc.js';
+export * from './ports.js';
export * from './rapidReaderPosition.js';
export * from './registerServiceWorker.js';
export * from './safeStorage.js';
diff --git a/client/src/lib/ports.js b/client/src/lib/ports.js
new file mode 100644
index 0000000000..0c2f493eb2
--- /dev/null
+++ b/client/src/lib/ports.js
@@ -0,0 +1,20 @@
+// Client mirror of the small subset of `PORTS` the UI needs.
+//
+// `ecosystem.config.cjs` (top-level `PORTS` object) is the SOURCE OF TRUTH — see
+// docs/PORTS.md. `server/lib/ports.js` is the server-side mirror. This file
+// exists because the browser bundle can't import either one: the ecosystem
+// config is CommonJS living outside the client Vite root, and the server mirror
+// is server ESM. `ports.parity.test.js` fails if these drift from the config.
+//
+// Decision: mirror rather than fetch from an endpoint — these values are needed
+// synchronously at module scope for form defaults and static help text, before
+// any API round-trip could resolve.
+export const PORTS = Object.freeze({
+ API: 5555, // Express API server (HTTPS when a Tailscale cert is active)
+ API_LOCAL: 5553, // Loopback-only HTTP mirror of API — binds only when HTTPS is on
+ UI: 5554, // Vite dev server (client)
+});
+
+// The port a newly-added federation peer is assumed to serve its API on.
+// Mirrors `DEFAULT_PEER_PORT` in server/lib/ports.js.
+export const DEFAULT_PEER_PORT = PORTS.API;
diff --git a/client/src/lib/ports.parity.test.js b/client/src/lib/ports.parity.test.js
new file mode 100644
index 0000000000..41a0981d04
--- /dev/null
+++ b/client/src/lib/ports.parity.test.js
@@ -0,0 +1,25 @@
+// @vitest-environment node
+import { describe, it, expect } from 'vitest';
+import { createRequire } from 'node:module';
+import { PORTS, DEFAULT_PEER_PORT } from './ports.js';
+
+const require = createRequire(import.meta.url);
+// ecosystem.config.cjs is the source of truth for every PortOS port.
+const ecosystem = require('../../../ecosystem.config.cjs');
+
+describe('client/src/lib/ports.js mirror parity', () => {
+ it('matches ecosystem.config.cjs for every mirrored port', () => {
+ for (const key of Object.keys(PORTS)) {
+ expect(ecosystem.PORTS[key], `ecosystem.config.cjs is missing PORTS.${key}`).toBeDefined();
+ expect(PORTS[key], `client mirror PORTS.${key} drifted`).toBe(ecosystem.PORTS[key]);
+ }
+ });
+
+ it('mirrors only the UI-facing subset', () => {
+ expect(Object.keys(PORTS).sort()).toEqual(['API', 'API_LOCAL', 'UI']);
+ });
+
+ it('defaults a new peer to the API port', () => {
+ expect(DEFAULT_PEER_PORT).toBe(ecosystem.PORTS.API);
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 31f7543e43..11c1056acc 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -23,6 +23,7 @@ import {
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
+import { DEFAULT_PEER_PORT } from '../lib/ports.js';
import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';
import UnattendedRenderRouting from '../components/instances/UnattendedRenderRouting';
import BrainParityPanel from '../components/instances/BrainParityPanel';
@@ -202,9 +203,11 @@ function SelfCard({ self, onUpdate, syncStatus, tailnetInfo }) {
);
}
-function AddPeerForm({ onAdd }) {
+// Exported for focused tests (the port input's placeholder must advertise the
+// same default the form actually submits — see Instances.test.jsx).
+export function AddPeerForm({ onAdd }) {
const [address, setAddress] = useState('');
- const [port, setPort] = useState('5555');
+ const [port, setPort] = useState(String(DEFAULT_PEER_PORT));
const [name, setName] = useState('');
const [showAuth, setShowAuth] = useState(false);
const [username, setUsername] = useState('');
@@ -215,7 +218,7 @@ function AddPeerForm({ onAdd }) {
e.preventDefault();
if (!address.trim()) return;
setAdding(true);
- const data = { address: address.trim(), port: parseInt(port, 10) || 5555 };
+ const data = { address: address.trim(), port: parseInt(port, 10) || DEFAULT_PEER_PORT };
if (name.trim()) data.name = name.trim();
// Only attach credentials when a password was entered — username alone
// (or neither) is treated as "no auth" by the server's sanitizer.
@@ -224,7 +227,7 @@ function AddPeerForm({ onAdd }) {
setAdding(false);
if (!result) return;
setAddress('');
- setPort('5555');
+ setPort(String(DEFAULT_PEER_PORT));
setName('');
setUsername('');
setPassword('');
@@ -252,7 +255,7 @@ function AddPeerForm({ onAdd }) {
aria-label="Peer port"
value={port}
onChange={e => setPort(e.target.value)}
- placeholder="5554"
+ placeholder={String(DEFAULT_PEER_PORT)}
type="number"
min="1"
max="65535"
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
new file mode 100644
index 0000000000..9bb1f810d8
--- /dev/null
+++ b/client/src/pages/Instances.test.jsx
@@ -0,0 +1,52 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { AddPeerForm } from './Instances.jsx';
+import { DEFAULT_PEER_PORT } from '../lib/ports.js';
+import { addPeer } from '../services/api';
+
+vi.mock('../services/api', () => ({
+ getInstances: vi.fn(),
+ updateSelfInstance: vi.fn(),
+ addPeer: vi.fn(),
+ updatePeer: vi.fn(),
+ removePeer: vi.fn(),
+ connectPeer: vi.fn(),
+ reciprocatePeer: vi.fn(),
+ probePeer: vi.fn(),
+ syncPeer: vi.fn(),
+ getTailnetInfo: vi.fn(),
+ getNetworkExposure: vi.fn(),
+ listPeerSubscriptions: vi.fn(),
+ getPeerFullSyncCoverage: vi.fn(),
+ getBrainParityReports: vi.fn(),
+}));
+
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+
+describe('AddPeerForm port default', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ addPeer.mockResolvedValue({ id: 'peer-1' });
+ });
+
+ // Regression: the placeholder advertised :5554 (the Vite dev port) while the
+ // field defaulted to the API port, so clearing the field suggested a port
+ // PortOS never serves the API on.
+ it('advertises the same port in the placeholder as it defaults to', () => {
+ render(<AddPeerForm onAdd={() => {}} />);
+ const portInput = screen.getByLabelText('Peer port');
+ expect(portInput).toHaveValue(DEFAULT_PEER_PORT);
+ expect(portInput.getAttribute('placeholder')).toBe(String(DEFAULT_PEER_PORT));
+ });
+
+ it('falls back to the default port when the field is cleared', async () => {
+ render(<AddPeerForm onAdd={() => {}} />);
+ fireEvent.change(screen.getByLabelText('Peer address'), { target: { value: '192.0.2.10' } });
+ fireEvent.change(screen.getByLabelText('Peer port'), { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));
+ await waitFor(() => expect(addPeer).toHaveBeenCalledWith({
+ address: '192.0.2.10',
+ port: DEFAULT_PEER_PORT,
+ }));
+ });
+});
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 9599440bc7..4a3d0da99a 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -7,7 +7,7 @@ PortOS uses a contiguous port allocation scheme to make it easy to understand wh
### Convention
1. **Contiguous Ranges**: Each app should use a contiguous block of ports
-2. **Labeled Ports**: Define all ports in the top-level `PORTS` object in `ecosystem.config.cjs` (mirrored — manually kept in sync — in `server/lib/ports.js`, since the ESM server can't `require()` the CommonJS config); the per-process label map for PM2 processes lives in `server/services/apps.js`. Infrastructure dependencies (such as PostgreSQL on 5561) are provisioned via `scripts/setup-db.js` / Docker Compose rather than registered as PM2 processes in `apps.js`. The mirror carries every port literal, including both PostgreSQL ports; the config's mode-dependent `POSTGRES` (resolved from `PGMODE` at load time) is exposed in the mirror as `resolvePostgresPort(pgMode)` over the `POSTGRES_NATIVE` / `POSTGRES_DOCKER` literals, so `server/lib/ports.js` stays free of filesystem reads. `server/lib/ports.test.js` fails if the two drift apart
+2. **Labeled Ports**: Define all ports in the top-level `PORTS` object in `ecosystem.config.cjs` (mirrored — manually kept in sync — in `server/lib/ports.js`, since the ESM server can't `require()` the CommonJS config); the per-process label map for PM2 processes lives in `server/services/apps.js`. Infrastructure dependencies (such as PostgreSQL on 5561) are provisioned via `scripts/setup-db.js` / Docker Compose rather than registered as PM2 processes in `apps.js`. The mirror carries every port literal, including both PostgreSQL ports; the config's mode-dependent `POSTGRES` (resolved from `PGMODE` at load time) is exposed in the mirror as `resolvePostgresPort(pgMode)` over the `POSTGRES_NATIVE` / `POSTGRES_DOCKER` literals, so `server/lib/ports.js` stays free of filesystem reads. `server/lib/ports.test.js` fails if the two drift apart. The browser bundle can't import either file, so `client/src/lib/ports.js` carries a third, deliberately minimal mirror of just the UI-facing subset (`API`, `API_LOCAL`, `UI`) plus `DEFAULT_PEER_PORT` — use it instead of re-hardcoding a port literal in client code; `client/src/lib/ports.parity.test.js` fails if it drifts
3. **No Gaps**: Avoid leaving gaps between port allocations within an app
### Port Labels