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

feat: guide secure PortOS setup

Adam Eivyb0b6ddc187c1
diff --git a/README.md b/README.md
index 36f0ab5785..0d6f7fcf2b 100644
--- a/README.md
+++ b/README.md
@@ -304,14 +304,15 @@ npm run setup
npm start
```
-`npm run setup` (aliased as `npm run install:all`) initializes bundled submodules; installs the root, client, server, and Autofixer dependencies; runs the trusted native rebuilds; prepares runtime data; and provisions PostgreSQL, local LLM tooling, and the headless browser. `npm start` builds the client and starts the managed processes with PM2. Access PortOS at `http://localhost:5555` (or via Tailscale at `http://<machine>.<tailnet>.ts.net:5555`).
+`npm run setup` (aliased as `npm run install:all`) initializes bundled submodules; installs the root, client, server, and Autofixer dependencies; runs the trusted native rebuilds; prepares runtime data; provisions PostgreSQL, local LLM tooling, and the headless browser; safely attempts a trusted Tailscale certificate; and prints an ordered setup walkthrough. `npm start` builds the client and starts the managed processes with PM2. Before HTTPS is ready, access PortOS locally at `http://localhost:5555`.
For a guided setup that also checks optional local media and command-line tooling, run `./setup.sh` instead. It prompts before starting PortOS; choose that option or run `npm start` afterward, not both.
-For HTTPS (recommended — required for the in-browser microphone, and you'll get a trusted cert via Tailscale's Let's Encrypt integration):
+For HTTPS (recommended — required for the in-browser microphone away from loopback), setup tells you when Tailscale, MagicDNS, or the tailnet's HTTPS Certificates toggle is still missing and automatically fetches the trusted certificate once those prerequisites are ready:
```bash
npm run setup:cert # Tailscale + Let's Encrypt (trusted)
+npm run setup:guide # show the next setup action + correct URL
npm run setup:cert -- --self-signed # fallback if you don't have Tailscale
pm2 restart ecosystem.config.cjs
```
@@ -320,6 +321,8 @@ After that, `https://<machine>.<tailnet>.ts.net:5555` is the user-facing URL on
> A fresh install with no Tailscale **stays on HTTP**, so `http://localhost:5555` works out of the box. `npm start` will only auto-provision a cert when Tailscale's `tailscale cert` succeeds — it won't silently flip you to a self-signed HTTPS that breaks the URL above. Pass `--self-signed` if you want HTTPS without Tailscale (browser warning included).
+The same walkthrough is always available in **Settings → Setup**. It verifies one runnable AI provider as well as secure remote access, and links directly to every action PortOS cannot perform at the account level. The Dashboard and Instances page surface the same network state; Unix and Windows update scripts retry certificate provisioning and print the guide after every update. See the [complete setup guide](./docs/SETUP.md).
+
PM2 keeps PortOS running in the background and auto-restarts on reboot (with `pm2 save` + `pm2 startup`).
### Development Mode
@@ -405,6 +408,7 @@ Full catalog (including design plans, ADRs, and research notes): [docs/README.md
- [API Reference](./docs/API.md) — REST endpoints, full route-domain index, and WebSocket events
- [API Tool Contract](./docs/API_TOOL_CONTRACT.md) — Unified semantic tool, Persistent Mind, and Agent Tools MCP contract
- [Companion App API](./docs/COMPANION_APP_API.md) — PortDeck native mobile client discovery and HTTP API contract
+- [Setup Guide](./docs/SETUP.md) — Tailscale, MagicDNS, trusted HTTPS, launch URLs, and AI-provider readiness
- [Remote Desktop Broker](./docs/REMOTE_DESKTOP.md) — PortDeck VNC broker security, host setup, and session flow
- [Federated Media Providers](./docs/FEDERATED_MEDIA_PROVIDERS.md) — Authenticated, capacity-aware peer audio provider wire contract and setup
- [Storage Classification Contract](./docs/STORAGE.md) — when data belongs in PostgreSQL vs the filesystem, plus the new-data-store checklist
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index e703439f8a..b010c3e0b9 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -123,6 +123,7 @@ import { useOnDemandTaskToast } from '../hooks/useOnDemandTaskToast';
import { useEngagementReminderToast } from '../hooks/useEngagementReminderToast';
import { useSharingNotifications } from '../hooks/useSharingNotifications';
import UpdateBanners from './UpdateBanners';
+import SetupBanner from './SetupBanner';
import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';
import { useNavWorkingSet } from '../hooks/useNavWorkingSet.js';
import { migrateLegacyNavPath } from '../utils/navWorkingSet.js';
@@ -1425,9 +1426,10 @@ export default function Layout() {
</div>
</header>
- {/* Update / out-of-sync advisories — inline (document flow) so they
+ {/* Update, out-of-sync, and essential-setup advisories — inline (document flow) so they
push the page instead of covering a bottom-anchored composer (#3786) */}
<UpdateBanners />
+ <SetupBanner />
{/* Main content */}
{(() => {
diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsx
index 14dd6344e0..b1255ede7d 100644
--- a/client/src/components/Layout.test.jsx
+++ b/client/src/components/Layout.test.jsx
@@ -22,6 +22,7 @@ vi.mock('../hooks/useSharingNotifications', () => ({ useSharingNotifications: ()
vi.mock('../hooks/useAgentFeedbackToast', () => ({ useAgentFeedbackToast: () => {} }));
vi.mock('../hooks/useAIStatusNotifications', () => ({ useAIStatusNotifications: () => {} }));
vi.mock('./UpdateBanners', () => ({ default: () => null }));
+vi.mock('./SetupBanner', () => ({ default: () => null }));
vi.mock('../hooks/useNotifications', () => ({
useNotifications: () => ({
notifications: [],
diff --git a/client/src/components/NetworkExposureWidget.jsx b/client/src/components/NetworkExposureWidget.jsx
index 6f1c97c303..f2dc2ad828 100644
--- a/client/src/components/NetworkExposureWidget.jsx
+++ b/client/src/components/NetworkExposureWidget.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, memo, useMemo } from 'react';
+import { Link } from 'react-router';
import {
Shield,
ShieldAlert,
@@ -14,6 +15,7 @@ import {
} from 'lucide-react';
import * as api from '../services/api';
import { isLoopbackOrigin, describeMicAvailability } from '../lib/loopbackHost.js';
+import NetworkSetupGuide from './NetworkSetupGuide.jsx';
function CertModeBadge({ mode, host }) {
if (mode === 'tailscale') {
@@ -110,11 +112,17 @@ const NetworkExposureWidget = memo(function NetworkExposureWidget() {
<AlertTriangle size={14} className="mt-0.5 flex-shrink-0" />
<span>
Bound on all interfaces over plain HTTP — anyone on this LAN/Tailnet
- can reach PortOS unencrypted. Run <code className="font-mono">npm run setup:cert</code> to enable HTTPS.
+ can reach PortOS unencrypted. Complete the secure-access step below to enable trusted HTTPS.
</span>
</div>
)}
+ {!status.setup?.complete && (
+ <div className="mb-4">
+ <NetworkSetupGuide networkExposure={status} compact />
+ </div>
+ )}
+
<dl className="space-y-3 text-sm">
<div className="flex items-start justify-between gap-3">
<dt className="text-gray-500 flex items-center gap-2">
@@ -199,15 +207,23 @@ const NetworkExposureWidget = memo(function NetworkExposureWidget() {
</dl>
<div className="mt-4 pt-3 border-t border-port-border">
- <a
- href={docsUrl}
- target="_blank"
- rel="noreferrer"
- className="inline-flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80"
- >
- <span>Port + scheme guide</span>
- <ExternalLink size={12} />
- </a>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <Link
+ to="/capabilities"
+ className="inline-flex min-h-[44px] items-center text-sm text-port-accent hover:text-port-accent/80 sm:min-h-0"
+ >
+ Open setup
+ </Link>
+ <a
+ href={docsUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex min-h-[44px] items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 sm:min-h-0"
+ >
+ <span>Port + scheme guide</span>
+ <ExternalLink size={12} />
+ </a>
+ </div>
</div>
</div>
);
diff --git a/client/src/components/NetworkSetupGuide.jsx b/client/src/components/NetworkSetupGuide.jsx
new file mode 100644
index 0000000000..065891a804
--- /dev/null
+++ b/client/src/components/NetworkSetupGuide.jsx
@@ -0,0 +1,186 @@
+import { useState } from 'react';
+import {
+ ArrowUpRight,
+ CheckCircle2,
+ Circle,
+ CircleAlert,
+ CircleHelp,
+ Copy,
+ Lock,
+ RefreshCw,
+} from 'lucide-react';
+import toast from './ui/Toast';
+import {
+ handleSelfRestart,
+ PORTOS_APP_ID,
+ provisionTailnetCert,
+ restartApp,
+} from '../services/api';
+import { copyToClipboard } from '../lib/clipboard.js';
+
+const STATUS = {
+ complete: { icon: CheckCircle2, color: 'text-port-success', label: 'Complete' },
+ action: { icon: CircleAlert, color: 'text-port-warning', label: 'Action needed' },
+ blocked: { icon: Circle, color: 'text-gray-600', label: 'Waiting' },
+ unknown: { icon: CircleHelp, color: 'text-port-warning', label: 'Check manually' },
+};
+
+function ExternalAction({ action }) {
+ return (
+ <a
+ href={action.url}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg border border-port-accent/40 px-3 py-2 text-xs font-medium text-port-accent hover:bg-port-accent/10 sm:min-h-0"
+ >
+ {action.label}
+ <ArrowUpRight size={12} />
+ </a>
+ );
+}
+
+export default function NetworkSetupGuide({ networkExposure, compact = false }) {
+ const [provisioning, setProvisioning] = useState(false);
+ const [provisionResult, setProvisionResult] = useState(null);
+ const [restarting, setRestarting] = useState(false);
+ const setup = networkExposure?.setup;
+
+ if (!setup || !Array.isArray(setup.steps)) return null;
+
+ const port = networkExposure?.bind?.port || 5555;
+ const visibleSteps = compact
+ ? [setup.nextStep || setup.steps.at(-1)].filter(Boolean)
+ : setup.steps;
+
+ const provision = async () => {
+ setProvisioning(true);
+ setProvisionResult(null);
+ const result = await provisionTailnetCert().catch(() => null);
+ setProvisioning(false);
+ if (!result?.ok) return;
+ setProvisionResult(result);
+ toast.success(result.message);
+ };
+
+ const restartPortos = async (targetUrl) => {
+ setRestarting(true);
+ const result = await restartApp(PORTOS_APP_ID, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Could not restart PortOS');
+ return null;
+ });
+ if (!result?.selfRestart) {
+ if (result) toast.error('PortOS did not accept the restart request');
+ setRestarting(false);
+ return;
+ }
+ handleSelfRestart({ targetOrigin: targetUrl });
+ };
+
+ const provisionedTarget = provisionResult?.hostname
+ ? `https://${provisionResult.hostname}:${port}`
+ : setup.pendingTrustedUrl;
+
+ const renderAction = (step) => {
+ const action = step.action;
+ if (!action) return null;
+ if (action.type === 'external') return <ExternalAction action={action} />;
+ if (action.type === 'command') {
+ return (
+ <button
+ type="button"
+ onClick={() => copyToClipboard(action.command, 'Command copied')}
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 font-mono text-xs text-gray-300 hover:border-port-accent/60 hover:text-white sm:min-h-0"
+ >
+ <Copy size={12} />
+ {action.command}
+ </button>
+ );
+ }
+ if (action.type === 'provision-cert') {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <ExternalAction action={{
+ type: 'external',
+ label: 'Enable certificates in Tailscale',
+ url: action.adminUrl,
+ }} />
+ <button
+ type="button"
+ onClick={provision}
+ disabled={provisioning}
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg bg-port-accent px-3 py-2 text-xs font-medium text-white hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-40 sm:min-h-0"
+ >
+ <Lock size={12} />
+ {provisioning ? 'Provisioning…' : action.label}
+ </button>
+ </div>
+ );
+ }
+ if (action.type === 'restart') {
+ return (
+ <button
+ type="button"
+ onClick={() => restartPortos(action.targetUrl)}
+ disabled={restarting || !action.targetUrl}
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg bg-port-accent px-3 py-2 text-xs font-medium text-white hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-40 sm:min-h-0"
+ >
+ <RefreshCw size={12} className={restarting ? 'animate-spin' : ''} />
+ {restarting ? 'Restarting…' : action.label}
+ </button>
+ );
+ }
+ return null;
+ };
+
+ return (
+ <div className={compact ? 'space-y-2' : 'space-y-3'}>
+ {visibleSteps.map((step, index) => {
+ const style = STATUS[step.status] || STATUS.unknown;
+ const Icon = style.icon;
+ return (
+ <div
+ key={step.id}
+ className={`rounded-lg border p-3 ${step.status === 'complete' ? 'border-port-success/20 bg-port-success/5' : 'border-port-border bg-port-bg/40'}`}
+ >
+ <div className="flex items-start gap-3">
+ <Icon size={17} className={`${style.color} mt-0.5 shrink-0`} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ {!compact && <span className="text-xs text-gray-600">{index + 1}</span>}
+ <span className="text-sm font-medium text-white">{step.title}</span>
+ <span className={`text-[11px] ${style.color}`}>{style.label}</span>
+ </div>
+ <p className="mt-1 text-xs leading-relaxed text-gray-400">{step.detail}</p>
+ {step.action && <div className="mt-2">{renderAction(step)}</div>}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+
+ {provisionResult?.ok && (
+ <div className="flex flex-wrap items-center gap-2 rounded-lg border border-port-success/30 bg-port-success/10 px-3 py-2 text-xs text-port-success">
+ <CheckCircle2 size={14} />
+ <span>
+ {provisionResult.requiresRestart
+ ? 'Certificate installed — restart PortOS to activate trusted HTTPS.'
+ : 'Certificate installed and active.'}
+ </span>
+ {provisionResult.requiresRestart && provisionedTarget ? (
+ <button
+ type="button"
+ onClick={() => restartPortos(provisionedTarget)}
+ disabled={restarting}
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-lg border border-port-success/50 px-3 py-2 font-medium hover:bg-port-success/10 disabled:opacity-40 sm:min-h-0"
+ >
+ <RefreshCw size={12} className={restarting ? 'animate-spin' : ''} />
+ {restarting ? 'Restarting…' : 'Restart PortOS'}
+ </button>
+ ) : provisionedTarget ? (
+ <a href={provisionedTarget} className="font-medium underline">Open trusted URL</a>
+ ) : null}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/SetupBanner.jsx b/client/src/components/SetupBanner.jsx
new file mode 100644
index 0000000000..4ce5f105f2
--- /dev/null
+++ b/client/src/components/SetupBanner.jsx
@@ -0,0 +1,88 @@
+import { useEffect, useState } from 'react';
+import { CircleAlert } from 'lucide-react';
+import { useLocation, useNavigate } from 'react-router';
+import * as api from '../services/api';
+import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage.js';
+import Banner from './ui/Banner';
+
+const DISMISSED_KEY = 'portos-setup-banner-dismissed';
+
+export default function SetupBanner() {
+ const [setupState, setSetupState] = useState(null);
+ const [dismissed, setDismissed] = useState(() => safeReadJsonSession(DISMISSED_KEY));
+ const navigate = useNavigate();
+ const location = useLocation();
+
+ useEffect(() => {
+ let cancelled = false;
+ api.getCapabilities({ silent: true })
+ .then((data) => {
+ if (!cancelled) setSetupState(data);
+ })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, []);
+
+ const setup = setupState?.setup;
+ if (!setup || setup.complete || location.pathname === '/capabilities') return null;
+
+ const caps = Array.isArray(setupState.capabilities) ? setupState.capabilities : [];
+ const network = caps.find((entry) => entry.id === 'network');
+ const providers = caps.find((entry) => entry.id === 'providers');
+ const nextNetwork = setupState?.network?.setup?.nextStep;
+ const nextNetworkStep = nextNetwork?.title;
+ // A dismissal belongs to the exact state the user postponed. Re-show after
+ // progress (or a newly discovered blocker) even when both top-level booleans
+ // remain false—for example, installing a CLI but still needing to sign in.
+ const signature = [
+ network?.setupComplete === true,
+ nextNetwork?.id || '',
+ network?.summary || '',
+ providers?.setupComplete === true,
+ providers?.summary || '',
+ ].join(':');
+ if (dismissed === signature) return null;
+
+ const missing = [];
+ if (network?.setupComplete !== true) missing.push(nextNetworkStep || 'Tailscale HTTPS');
+ if (providers?.setupComplete !== true) missing.push('a ready AI provider');
+ const message = missing.length > 0
+ ? `Finish setup: ${missing.join(' and ')}.`
+ : `${setup.remaining} setup ${setup.remaining === 1 ? 'step needs' : 'steps need'} attention.`;
+
+ const dismiss = () => {
+ safeWriteJsonSession(DISMISSED_KEY, signature);
+ setDismissed(signature);
+ };
+
+ return (
+ <div className="shrink-0 px-3 pt-2 print:hidden">
+ <Banner
+ tone="warning"
+ icon={CircleAlert}
+ align="center"
+ role="status"
+ actions={(
+ <div className="flex flex-col gap-1 sm:flex-row sm:gap-2">
+ <button
+ type="button"
+ onClick={() => navigate('/capabilities')}
+ className="min-h-[44px] rounded bg-port-warning px-3 py-2 text-xs font-medium text-black hover:bg-port-warning/80 lg:min-h-0 lg:py-1"
+ >
+ Review setup
+ </button>
+ <button
+ type="button"
+ onClick={dismiss}
+ className="min-h-[44px] rounded bg-gray-600 px-3 py-2 text-xs text-white hover:bg-gray-500 lg:min-h-0 lg:py-1"
+ >
+ Later
+ </button>
+ </div>
+ )}
+ >
+ {message}
+ </Banner>
+ </div>
+ );
+}
diff --git a/client/src/components/SetupBanner.test.jsx b/client/src/components/SetupBanner.test.jsx
new file mode 100644
index 0000000000..7ee1c59c21
--- /dev/null
+++ b/client/src/components/SetupBanner.test.jsx
@@ -0,0 +1,84 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router';
+
+vi.mock('../services/api', () => ({
+ getCapabilities: vi.fn(),
+}));
+
+import * as api from '../services/api';
+import SetupBanner from './SetupBanner';
+
+const incomplete = {
+ setup: { total: 2, ready: 0, remaining: 2, complete: false },
+ network: { setup: { nextStep: { id: 'magic-dns', title: 'Enable MagicDNS' } } },
+ capabilities: [
+ { id: 'network', setupRequired: true, setupComplete: false },
+ { id: 'providers', setupRequired: true, setupComplete: false },
+ ],
+};
+
+const renderBanner = () => render(
+ <MemoryRouter initialEntries={['/']}>
+ <SetupBanner />
+ <Routes>
+ <Route path="/capabilities" element={<div>Setup destination</div>} />
+ </Routes>
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+});
+
+describe('SetupBanner', () => {
+ it('names the next network blocker and missing provider, then opens setup', async () => {
+ api.getCapabilities.mockResolvedValue(incomplete);
+ renderBanner();
+
+ expect(await screen.findByText('Finish setup: Enable MagicDNS and a ready AI provider.')).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: 'Review setup' }));
+ expect(await screen.findByText('Setup destination')).toBeInTheDocument();
+ });
+
+ it('dismisses only the current setup state for the browser session', async () => {
+ api.getCapabilities.mockResolvedValue(incomplete);
+ const { unmount } = renderBanner();
+ await userEvent.click(await screen.findByRole('button', { name: 'Later' }));
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Review setup' })).not.toBeInTheDocument());
+
+ unmount();
+ renderBanner();
+ await waitFor(() => expect(api.getCapabilities).toHaveBeenCalledTimes(2));
+ expect(screen.queryByRole('button', { name: 'Review setup' })).not.toBeInTheDocument();
+ });
+
+ it('reappears when setup progresses to a different incomplete state', async () => {
+ api.getCapabilities.mockResolvedValueOnce(incomplete);
+ const { unmount } = renderBanner();
+ await userEvent.click(await screen.findByRole('button', { name: 'Later' }));
+ unmount();
+
+ api.getCapabilities.mockResolvedValueOnce({
+ ...incomplete,
+ capabilities: incomplete.capabilities.map((entry) => entry.id === 'providers'
+ ? { ...entry, summary: '1 enabled · sign-in required' }
+ : entry),
+ });
+ renderBanner();
+
+ expect(await screen.findByRole('button', { name: 'Review setup' })).toBeInTheDocument();
+ });
+
+ it('stays hidden after essential setup is complete', async () => {
+ api.getCapabilities.mockResolvedValue({
+ ...incomplete,
+ setup: { total: 2, ready: 2, remaining: 0, complete: true },
+ });
+ renderBanner();
+ await waitFor(() => expect(api.getCapabilities).toHaveBeenCalled());
+ expect(screen.queryByRole('button', { name: 'Review setup' })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index 509a6d8492..35004cefad 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -18,6 +18,7 @@ const STEP_LABELS = {
setup: 'Running setup',
ffmpeg: 'Checking ffmpeg',
migrations: 'Running migrations',
+ 'network-setup': 'Checking secure access',
build: 'Building client',
restart: 'Restarting PortOS',
restarting: 'Restarting PortOS',
diff --git a/client/src/components/instances/TailnetHelpBanner.jsx b/client/src/components/instances/TailnetHelpBanner.jsx
index e7c1be2eda..6e5657a631 100644
--- a/client/src/components/instances/TailnetHelpBanner.jsx
+++ b/client/src/components/instances/TailnetHelpBanner.jsx
@@ -1,188 +1,77 @@
-import { useState } from 'react';
import {
AlertCircle,
- ArrowUpRight,
CheckCircle2,
ChevronDown,
ChevronRight,
Info,
Lock,
- RefreshCw,
} from 'lucide-react';
-import toast from '../ui/Toast';
import Pill from '../ui/Pill';
-import {
- handleSelfRestart,
- PORTOS_APP_ID,
- provisionTailnetCert,
- restartApp,
-} from '../../services/api';
+import NetworkSetupGuide from '../NetworkSetupGuide.jsx';
import { useLocalStorageBool } from '../../hooks/useLocalStorageBool';
export default function TailnetHelpBanner({ tailnetInfo, networkExposure }) {
const [collapsed, setCollapsed] = useLocalStorageBool('portos-tailnet-help-collapsed', false);
- const [provisioning, setProvisioning] = useState(false);
- const [provisionResult, setProvisionResult] = useState(null);
- const [restarting, setRestarting] = useState(false);
-
- const toggle = () => setCollapsed((prev) => !prev);
-
- const provision = async (e) => {
- e.stopPropagation();
- setProvisioning(true);
- setProvisionResult(null);
- const result = await provisionTailnetCert().catch(() => null);
- setProvisioning(false);
- if (!result?.ok) return; // request() already toasted the error
- setProvisionResult(result);
- toast.success(result.message);
- };
-
- const trustedHttpsPort = networkExposure?.bind?.port || 5555;
+ const setup = networkExposure?.setup;
+ const complete = setup?.complete === true;
- const restartPortos = async () => {
- setRestarting(true);
- const result = await restartApp(PORTOS_APP_ID, { silent: true }).catch((error) => {
- toast.error(error.message || 'Could not restart PortOS');
- return null;
- });
- if (!result) {
- setRestarting(false);
- return;
- }
- if (!result.selfRestart) {
- toast.error('PortOS did not accept the restart request');
- setRestarting(false);
- return;
- }
-
- const targetHost = provisionResult.hostname || tailnetInfo?.self;
- const targetOrigin = `https://${targetHost}:${trustedHttpsPort}`;
- handleSelfRestart({ targetOrigin });
- };
-
- const status = tailnetInfo === null
- ? { label: 'Tailscale DNS not detected', tone: 'warn', detail: 'Install Tailscale and enable MagicDNS in your tailnet admin to auto-suggest peer DNS names.' }
- : tailnetInfo?.suffix
- ? { label: `MagicDNS: ${tailnetInfo.suffix}`, tone: 'ok', detail: tailnetInfo.self ? `This instance: ${tailnetInfo.self}` : null }
- : { label: 'Tailscale running but MagicDNS suffix not found', tone: 'warn', detail: 'Enable MagicDNS in your tailnet admin console (login.tailscale.com/admin/dns).' };
+ const status = complete
+ ? { label: 'Running on Tailscale HTTPS', tone: 'ok', detail: setup.summary }
+ : tailnetInfo === null
+ ? { label: 'Tailscale DNS not detected', tone: 'warn', detail: 'Install Tailscale and enable MagicDNS to get a stable private URL.' }
+ : tailnetInfo?.suffix
+ ? {
+ label: `MagicDNS: ${tailnetInfo.suffix}`,
+ tone: 'warn',
+ detail: setup?.summary || (tailnetInfo.self ? `This instance: ${tailnetInfo.self}` : null),
+ }
+ : { label: 'MagicDNS needs attention', tone: 'warn', detail: setup?.summary || 'Enable MagicDNS in the Tailscale DNS admin.' };
const ToneIcon = status.tone === 'ok' ? CheckCircle2 : AlertCircle;
const toneClass = status.tone === 'ok' ? 'text-port-success' : 'text-port-warning';
- const trustedHttpsHost = networkExposure?.httpsEnabled && networkExposure?.cert?.mode === 'tailscale'
- ? networkExposure.cert.tailscaleHost || tailnetInfo?.self || null
- : null;
- const trustedHttpsUrl = trustedHttpsHost ? `https://${trustedHttpsHost}:${trustedHttpsPort}` : null;
-
- // Only offer the one-click provision button when Tailscale is actually
- // detected and we have a MagicDNS hostname for this instance — otherwise
- // the API call will fail with the same "enable MagicDNS first" guidance.
- const canProvision = !!tailnetInfo?.self;
-
- if (trustedHttpsHost) {
- return (
- <div className="bg-port-card border border-port-border rounded-xl px-4 py-3">
- <div className="flex items-center gap-3 flex-wrap">
- <Lock size={16} className="text-port-success shrink-0" />
- <div className="flex-1 min-w-[220px]">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm font-medium text-white">Tailnet DNS &amp; trusted HTTPS</span>
- <Pill tone="success" size="xs" bordered={false} icon={CheckCircle2}>
- Running on Tailscale HTTPS
- </Pill>
- </div>
- <p className="text-xs text-gray-400 mt-1">
- Currently running on HTTPS with Tailscale DNS.
- </p>
- </div>
- {trustedHttpsUrl && (
- <a
- href={trustedHttpsUrl}
- target="_blank"
- rel="noreferrer"
- className="inline-flex items-center gap-1.5 text-xs text-port-accent hover:text-port-accent/80 font-mono"
- title={`Open ${trustedHttpsUrl}`}
- >
- {trustedHttpsHost}
- <ArrowUpRight size={12} />
- </a>
- )}
- </div>
- </div>
- );
- }
return (
- <div className="bg-port-card border border-port-border rounded-xl">
+ <div className="rounded-xl border border-port-border bg-port-card">
<button
- onClick={toggle}
- className="w-full flex items-center gap-2 p-4 text-left"
+ type="button"
+ onClick={() => setCollapsed((prev) => !prev)}
+ className="flex min-h-[44px] w-full items-center gap-2 p-4 text-left"
+ aria-expanded={!collapsed}
>
- <Lock size={16} className="text-port-accent shrink-0" />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
+ <Lock size={16} className={complete ? 'shrink-0 text-port-success' : 'shrink-0 text-port-accent'} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium text-white">Tailnet DNS &amp; trusted HTTPS</span>
<Pill tone="bare" size="xs" bordered={false} icon={ToneIcon} className={`${toneClass} bg-port-bg`}>
{status.label}
</Pill>
</div>
</div>
- {collapsed ? <ChevronRight size={14} className="text-gray-500" /> : <ChevronDown size={14} className="text-gray-500" />}
+ {collapsed
+ ? <ChevronRight size={14} className="text-gray-500" />
+ : <ChevronDown size={14} className="text-gray-500" />}
</button>
{!collapsed && (
- <div className="px-4 pb-4 -mt-1 text-xs text-gray-400 space-y-2">
+ <div className="space-y-3 px-4 pb-4">
{status.detail && (
- <div className="flex items-start gap-1.5">
- <Info size={11} className="mt-0.5 text-gray-500 shrink-0" />
- <span className="font-mono">{status.detail}</span>
+ <div className="flex items-start gap-1.5 text-xs text-gray-400">
+ <Info size={12} className="mt-0.5 shrink-0 text-gray-500" />
+ <span>{status.detail}</span>
</div>
)}
- <p>
- By default, federation traffic uses <span className="font-mono text-gray-300">http://{`<ip>`}:5555</span>. Setting a Tailscale MagicDNS host on a peer
- switches that hop to <span className="font-mono text-gray-300">https://{`<host>`}.{tailnetInfo?.suffix || `<tailnet>`}.ts.net</span> with a
- browser-trusted Let&apos;s Encrypt cert provisioned by Tailscale.
- </p>
- <ol className="list-decimal list-inside space-y-1 text-gray-500">
- <li>On each instance, enable MagicDNS + HTTPS Certificates in your tailnet admin (<span className="font-mono">login.tailscale.com/admin/dns</span>).</li>
- <li>
- Click <span className="text-port-accent">Enable HTTPS</span> below to fetch the cert via Tailscale
- (or run <span className="font-mono text-gray-300">npm run setup:cert</span> from a shell).
- </li>
- <li>Below, click <span className="text-port-accent">use {`<host>`}</span> on each peer to switch the link to HTTPS. Or click <span className="text-gray-400">use IP only</span> to revert.</li>
- </ol>
- <div className="flex items-center gap-2 flex-wrap pt-1">
- <button
- onClick={provision}
- disabled={provisioning || !canProvision}
- title={canProvision
- ? `Run \`tailscale cert\` for ${tailnetInfo.self} and write data/certs/{cert,key}.pem`
- : 'Enable MagicDNS in your tailnet admin first, then reload this page'}
- className="inline-flex items-center gap-1.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white px-3 py-1.5 rounded text-xs font-medium transition-colors min-h-[40px] sm:min-h-0"
- >
- <Lock size={12} />
- {provisioning ? 'Provisioning…' : 'Enable HTTPS'}
- </button>
- {provisionResult?.ok && (
- <>
- <span className="inline-flex items-center gap-1 text-[11px] text-port-success">
- <CheckCircle2 size={11} />
- {provisionResult.requiresRestart
- ? 'Cert installed — restart PortOS to activate HTTPS'
- : 'Cert installed and live'}
- </span>
- {provisionResult.requiresRestart && (
- <button
- onClick={restartPortos}
- disabled={restarting}
- className="inline-flex items-center gap-1.5 border border-port-accent text-port-accent hover:bg-port-accent/10 disabled:opacity-40 disabled:cursor-not-allowed px-3 py-1.5 rounded text-xs font-medium transition-colors min-h-[40px] sm:min-h-0"
- >
- <RefreshCw size={12} className={restarting ? 'animate-spin' : ''} />
- {restarting ? 'Restarting…' : 'Restart PortOS'}
- </button>
- )}
- </>
- )}
+
+ <NetworkSetupGuide networkExposure={networkExposure} compact={complete} />
+
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-3 text-xs leading-relaxed text-gray-400">
+ <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>
+ to its browser-trusted
+ <span className="font-mono text-gray-300"> https://{'<host>'}.{tailnetInfo?.suffix || '<tailnet>'}.ts.net:5555</span>
+ {' '}address. “Use IP only” reverts that peer to its IP.
+ </p>
</div>
</div>
)}
diff --git a/client/src/components/instances/TailnetHelpBanner.test.jsx b/client/src/components/instances/TailnetHelpBanner.test.jsx
index 435bd6bbcb..36106e1435 100644
--- a/client/src/components/instances/TailnetHelpBanner.test.jsx
+++ b/client/src/components/instances/TailnetHelpBanner.test.jsx
@@ -29,6 +29,33 @@ const tailnetInfo = {
const networkExposure = {
httpsEnabled: false,
bind: { port: 5555 },
+ setup: {
+ complete: false,
+ summary: 'Provision a trusted HTTPS certificate.',
+ pendingTrustedUrl: null,
+ nextStep: {
+ id: 'https-cert',
+ title: 'Provision a trusted HTTPS certificate',
+ status: 'action',
+ detail: 'Enable HTTPS Certificates in the Tailscale DNS admin, then let PortOS fetch the certificate automatically.',
+ action: {
+ type: 'provision-cert',
+ label: 'Enable HTTPS',
+ adminUrl: 'https://login.tailscale.com/admin/dns',
+ },
+ },
+ steps: [{
+ id: 'https-cert',
+ title: 'Provision a trusted HTTPS certificate',
+ status: 'action',
+ detail: 'Enable HTTPS Certificates in the Tailscale DNS admin, then let PortOS fetch the certificate automatically.',
+ action: {
+ type: 'provision-cert',
+ label: 'Enable HTTPS',
+ adminUrl: 'https://login.tailscale.com/admin/dns',
+ },
+ }],
+ },
};
beforeEach(() => {
@@ -55,7 +82,7 @@ describe('TailnetHelpBanner HTTPS activation', () => {
);
await user.click(screen.getByRole('button', { name: 'Enable HTTPS' }));
- expect(await screen.findByText('Cert installed — restart PortOS to activate HTTPS')).toBeInTheDocument();
+ expect(await screen.findByText('Certificate installed — restart PortOS to activate trusted HTTPS.')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Restart PortOS' }));
@@ -83,7 +110,7 @@ describe('TailnetHelpBanner HTTPS activation', () => {
await userEvent.click(screen.getByRole('button', { name: 'Enable HTTPS' }));
- expect(await screen.findByText('Cert installed and live')).toBeInTheDocument();
+ expect(await screen.findByText('Certificate installed and active.')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Restart PortOS' })).not.toBeInTheDocument();
});
diff --git a/client/src/pages/CapabilityMap.jsx b/client/src/pages/CapabilityMap.jsx
index 58eea9b60b..cb6eb48aaa 100644
--- a/client/src/pages/CapabilityMap.jsx
+++ b/client/src/pages/CapabilityMap.jsx
@@ -1,9 +1,10 @@
import { Link } from 'react-router';
import {
- CheckCircle, AlertTriangle, XCircle, Circle, ChevronRight, LayoutGrid,
+ CheckCircle, AlertTriangle, XCircle, Circle, ChevronRight, ListChecks,
} from 'lucide-react';
import * as api from '../services/api';
import PageSkeleton from '../components/ui/PageSkeleton';
+import NetworkSetupGuide from '../components/NetworkSetupGuide.jsx';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
// Status presentation. Mirrors the server's CAPABILITY_STATUS tiers.
@@ -68,6 +69,9 @@ export default function CapabilityMap() {
const caps = Array.isArray(data.capabilities) ? data.capabilities : [];
const summary = data.summary || { ok: 0, warn: 0, error: 0, unconfigured: 0, overall: 'unconfigured' };
+ const setup = data.setup || { total: 0, ready: 0, remaining: 0, complete: false };
+ const providerCapability = caps.find((cap) => cap.id === 'providers');
+ const optionalCapabilities = caps.filter((cap) => cap.setupRequired !== true);
const overallStyle = STATUS_STYLE[summary.overall] || STATUS_STYLE.unconfigured;
const OverallIcon = overallStyle.icon;
@@ -75,32 +79,71 @@ export default function CapabilityMap() {
<div className="space-y-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
<h2 className="text-xl font-bold text-white flex items-center gap-2">
- <LayoutGrid size={20} />
- Capabilities
+ <ListChecks size={20} />
+ Setup &amp; Capabilities
</h2>
- <div className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border ${overallStyle.border} ${overallStyle.color} ${overallStyle.bg}`}>
- <OverallIcon size={16} />
- <span className="font-semibold">{OVERALL_LABEL[summary.overall] || 'Status'}</span>
+ <div className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border ${setup.complete ? STATUS_STYLE.ok.border : STATUS_STYLE.warn.border} ${setup.complete ? STATUS_STYLE.ok.color : STATUS_STYLE.warn.color} ${setup.complete ? STATUS_STYLE.ok.bg : STATUS_STYLE.warn.bg}`}>
+ {setup.complete ? <CheckCircle size={16} /> : <AlertTriangle size={16} />}
+ <span className="font-semibold">
+ {setup.complete ? 'Essential setup complete' : `${setup.remaining} essential ${setup.remaining === 1 ? 'step' : 'steps'} remaining`}
+ </span>
</div>
</div>
<p className="text-sm text-gray-500">
- Each connected system's status at a glance — a setup checklist and a runtime health overview.
- Select a row to configure it.
+ Finish secure remote access and enable at least one runnable AI provider. Optional integrations stay below as a health overview.
</p>
- <div className="flex items-center gap-4 text-xs text-gray-400">
- <span className="flex items-center gap-1"><CheckCircle size={12} className="text-port-success" /> {summary.ok} ready</span>
- <span className="flex items-center gap-1"><AlertTriangle size={12} className="text-port-warning" /> {summary.warn} degraded</span>
- <span className="flex items-center gap-1"><XCircle size={12} className="text-port-error" /> {summary.error} error</span>
- <span className="flex items-center gap-1"><Circle size={12} className="text-gray-500" /> {summary.unconfigured} not set up</span>
- </div>
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4 sm:p-5">
+ <div>
+ <h3 className="font-semibold text-white">1. Tailscale, MagicDNS &amp; HTTPS</h3>
+ <p className="mt-1 text-xs text-gray-500">
+ PortOS automates certificate provisioning once Tailscale is connected and HTTPS Certificates are enabled in the tailnet.
+ </p>
+ </div>
+ <NetworkSetupGuide networkExposure={data.network} />
+ </section>
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
- {caps.map((cap) => (
- <CapabilityRow key={cap.id} cap={cap} />
- ))}
- </div>
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4 sm:p-5">
+ <div>
+ <h3 className="font-semibold text-white">2. AI provider</h3>
+ <p className="mt-1 text-xs text-gray-500">
+ Enable one option you intend to use: an authenticated subscription CLI, a paid API key, or a local runtime with a downloaded model. PortOS never enables a paid provider or starts model work without your action.
+ </p>
+ </div>
+ {providerCapability && <CapabilityRow cap={providerCapability} />}
+ <div className="grid gap-2 text-xs text-gray-400 sm:grid-cols-3">
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-3"><strong className="text-gray-200">Subscription CLI</strong><br />Claude Code, Codex, or Antigravity after local sign-in.</div>
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-3"><strong className="text-gray-200">API provider</strong><br />Add a key only for the paid service you chose.</div>
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-3"><strong className="text-gray-200">Local/private</strong><br />Ollama or LM Studio with a runnable model.</div>
+ </div>
+ </section>
+
+ <section className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <h3 className="font-semibold text-white">Optional capabilities</h3>
+ <p className="mt-1 text-xs text-gray-500">Configure these when they are useful; they do not block initial setup.</p>
+ </div>
+ <div className={`flex items-center gap-2 rounded-lg border px-3 py-1.5 ${overallStyle.border} ${overallStyle.color} ${overallStyle.bg}`}>
+ <OverallIcon size={15} />
+ <span className="text-xs font-semibold">{OVERALL_LABEL[summary.overall] || 'Status'}</span>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-4 text-xs text-gray-400">
+ <span className="flex items-center gap-1"><CheckCircle size={12} className="text-port-success" /> {summary.ok} ready</span>
+ <span className="flex items-center gap-1"><AlertTriangle size={12} className="text-port-warning" /> {summary.warn} degraded</span>
+ <span className="flex items-center gap-1"><XCircle size={12} className="text-port-error" /> {summary.error} error</span>
+ <span className="flex items-center gap-1"><Circle size={12} className="text-gray-500" /> {summary.unconfigured} not set up</span>
+ </div>
+
+ <div className="grid grid-cols-1 gap-2 lg:grid-cols-2">
+ {optionalCapabilities.map((cap) => (
+ <CapabilityRow key={cap.id} cap={cap} />
+ ))}
+ </div>
+ </section>
</div>
);
}
diff --git a/client/src/pages/CapabilityMap.test.jsx b/client/src/pages/CapabilityMap.test.jsx
new file mode 100644
index 0000000000..ac4d1098e4
--- /dev/null
+++ b/client/src/pages/CapabilityMap.test.jsx
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../hooks/useAutoRefetch', () => ({
+ useAutoRefetch: () => ({
+ loading: false,
+ data: {
+ setup: { total: 2, ready: 0, remaining: 2, complete: false },
+ summary: { ok: 0, warn: 2, error: 0, unconfigured: 1, total: 3, overall: 'warn' },
+ network: {
+ bind: { port: 5555 },
+ setup: {
+ complete: false,
+ summary: 'Enable MagicDNS',
+ nextStep: {
+ id: 'magic-dns',
+ title: 'Enable MagicDNS',
+ status: 'action',
+ detail: 'Enable MagicDNS in the tailnet DNS admin.',
+ action: { type: 'external', label: 'Open Tailscale DNS admin', url: 'https://login.tailscale.com/admin/dns' },
+ },
+ steps: [{
+ id: 'magic-dns',
+ title: 'Enable MagicDNS',
+ status: 'action',
+ detail: 'Enable MagicDNS in the tailnet DNS admin.',
+ action: { type: 'external', label: 'Open Tailscale DNS admin', url: 'https://login.tailscale.com/admin/dns' },
+ }],
+ },
+ },
+ capabilities: [
+ { id: 'network', label: 'Tailscale & HTTPS', settingsPath: '/instances', status: 'warn', summary: 'Enable MagicDNS', setupRequired: true, setupComplete: false },
+ { id: 'providers', label: 'AI Providers', settingsPath: '/ai', status: 'error', summary: '1 enabled · 0 ready · 1 needs setup', setupRequired: true, setupComplete: false },
+ { id: 'calendar', label: 'Calendar', settingsPath: '/calendar/config', status: 'unconfigured', summary: 'No accounts', setupRequired: false, setupComplete: false },
+ ],
+ },
+ }),
+}));
+
+import CapabilityMap from './CapabilityMap';
+
+describe('CapabilityMap setup walkthrough', () => {
+ it('keeps essential network/provider setup above optional capabilities', () => {
+ render(<MemoryRouter><CapabilityMap /></MemoryRouter>);
+
+ expect(screen.getByRole('heading', { name: 'Setup & Capabilities' })).toBeInTheDocument();
+ expect(screen.getByText('2 essential steps remaining')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: '1. Tailscale, MagicDNS & HTTPS' })).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Open Tailscale DNS admin' })).toHaveAttribute(
+ 'href',
+ 'https://login.tailscale.com/admin/dns',
+ );
+ expect(screen.getByRole('heading', { name: '2. AI provider' })).toBeInTheDocument();
+ expect(screen.getByText('Subscription CLI')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Optional capabilities' })).toBeInTheDocument();
+ expect(screen.getByText('Calendar')).toBeInTheDocument();
+ });
+});
diff --git a/docs/PORTS.md b/docs/PORTS.md
index e2ab45ef82..b1add2ed33 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -64,6 +64,8 @@ Rules of thumb:
- **Production side:** `server/lib/assetRoutePrefixes.js` lists the namespaces the server owns (`SERVER_OWNED_PREFIXES`) alongside the exact client routes inside them (`spaPaths` — `/data` itself is the Data Manager page), and `mountAssetRoutes` closes each one with a terminating 404 (#4688).
- `scripts/dev-proxy-drift.test.js` fails if the proxy, the mounts, and the client's own routes drift apart. It reads both `NAV_COMMANDS` and `App.jsx`'s nested `<Route>` tree, so a new page under a server-owned prefix — which the terminator would otherwise 404 silently — fails the build even when only its `:id` detail route exists.
+Run `npm run setup:guide` to print the currently valid local URL, the exact trusted MagicDNS URL when available, and the next Tailscale/HTTPS prerequisite. The end-to-end walkthrough is in [SETUP.md](./SETUP.md).
+
## Defining Ports in ecosystem.config.cjs
Define all ports in a top-level `PORTS` object as the single source of truth:
diff --git a/docs/README.md b/docs/README.md
index 70dc6cc374..4d9296f5d8 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,6 +12,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |
| [API_TOOL_CONTRACT.md](./API_TOOL_CONTRACT.md) | Unified semantic tool, Persistent Mind, and Agent Tools MCP contract |
| [COMPANION_APP_API.md](./COMPANION_APP_API.md) | PortDeck native iOS companion client discovery and HTTP API contract |
+| [SETUP.md](./SETUP.md) | First install: Tailscale, MagicDNS, trusted HTTPS, exact launch URL, and AI-provider readiness |
| [REMOTE_DESKTOP.md](./REMOTE_DESKTOP.md) | PortDeck VNC broker security, host setup, and session flow |
| [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md) | Authenticated, capacity-aware peer audio provider wire contract and setup |
| [STORAGE.md](./STORAGE.md) | Storage classification contract — PostgreSQL vs filesystem, new-data-store checklist |
diff --git a/docs/SETUP.md b/docs/SETUP.md
new file mode 100644
index 0000000000..905ddc2d51
--- /dev/null
+++ b/docs/SETUP.md
@@ -0,0 +1,68 @@
+# PortOS Setup Guide
+
+PortOS can automate local installation, certificate provisioning, and launch URLs, but two account-level decisions stay with you: joining a Tailscale tailnet and choosing which AI provider may run work. The CLI and **Settings → Setup** show the same ordered readiness checks so a missing prerequisite is visible instead of becoming a broken URL later.
+
+## First install
+
+```bash
+git clone --recurse-submodules https://github.com/atomantic/PortOS.git
+cd PortOS
+./setup.sh # macOS / Linux guided installer
+# or: .\setup.ps1 # Windows PowerShell
+```
+
+`npm run setup` is the non-wrapper equivalent. All three paths install dependencies, provision PostgreSQL, prepare runtime data and the managed browser, ask about a local LLM when an interactive terminal is available, safely attempt Tailscale certificate provisioning, and print the remaining setup walkthrough.
+
+The network sequence is:
+
+1. Install [Tailscale](https://tailscale.com/download) on the PortOS host.
+2. Open Tailscale and sign the host into your tailnet.
+3. Enable MagicDNS and **HTTPS Certificates** in the [Tailscale DNS admin](https://login.tailscale.com/admin/dns).
+4. Let PortOS run `tailscale cert` with `npm run setup:cert`.
+5. Restart PortOS and open the exact URL printed by setup: `https://<machine>.<tailnet>.ts.net:5555`.
+
+The installer performs step 4 automatically whenever the preceding account settings are ready. If an account setting is missing, it exits successfully with the exact next action; it never waits for a hidden prompt and never substitutes an untrusted self-signed certificate unless you explicitly pass `--self-signed`.
+
+## URLs and ports
+
+- `:5555` is always the user-facing PortOS port. It serves HTTP before a certificate exists and HTTPS after the trusted certificate is active.
+- `http://localhost:5553` is a host-only HTTP mirror when HTTPS is active. It exists for local scripts and does not work from another device.
+- `:5554` is only the Vite development UI.
+
+Run `npm run setup:guide` at any time to print the current walkthrough and correct URL. Add `-- --summary` for one line or `-- --json` for automation. PortOS's managed browser also opens the trusted MagicDNS URL when one is provisioned rather than defaulting to localhost.
+
+## Choose an AI provider
+
+Initial setup is complete once at least one enabled provider is actually runnable. Choose one path under **AI → Providers**:
+
+- **Subscription CLI:** install and authenticate a supported CLI such as Claude Code, Codex, or Antigravity. This is the recommended cost model for sustained autonomous work.
+- **API provider:** add a key for the paid provider you intend to use. PortOS never enables a paid provider automatically.
+- **Local/private:** install Ollama or LM Studio and download a compatible model under **Models → LLMs**.
+
+The Setup page checks binaries, credentials, local runtimes, and models without making an LLM request. PortOS never performs cold-bootstrap model calls.
+
+## Setup guidance in the app
+
+After PortOS starts:
+
+- The global setup banner names the next missing essential and links to **Settings → Setup**. “Later” hides only the current state for the browser session.
+- **Settings → Setup** keeps the complete network walkthrough and AI-provider choice above optional capability health.
+- The Dashboard's **Network Exposure** widget shows the next network action.
+- **Dev Tools → Instances** exposes the same full network guide alongside peer MagicDNS suggestions.
+
+Certificate provisioning and the PortOS restart are one-click actions in the UI once MagicDNS and the Tailscale admin certificate toggle are ready.
+
+## Updates and recovery
+
+`update.sh`, `update.ps1`, and the in-app updater retry the safe certificate provisioning step on every update, report the current network prerequisite in update progress, and print the full walkthrough afterward. An update does not fail merely because Tailscale is absent or an account toggle still needs you.
+
+Useful checks:
+
+```bash
+npm run setup:guide # ordered network + provider walkthrough
+npm run setup:cert # retry trusted Tailscale certificate provisioning
+npm run doctor # read-only report of all install prerequisites
+npm run pm2:restart # activate a newly provisioned certificate
+```
+
+For HTTPS without Tailscale, `npm run setup:cert -- --self-signed` remains an explicit fallback. Browsers will warn because that certificate is not publicly trusted, and a stable MagicDNS URL is still preferable for remote use.
diff --git a/lib/certMeta.js b/lib/certMeta.js
index 1762d519e6..a90da55484 100644
--- a/lib/certMeta.js
+++ b/lib/certMeta.js
@@ -34,3 +34,28 @@ export function readCertMeta(metaPath) {
return null;
}
}
+
+/**
+ * Return the browser-trusted MagicDNS hostname recorded by setup-cert, or null
+ * for self-signed/legacy/malformed metadata. Keeping validation here means CLI
+ * banners and browser auto-open cannot disagree about whether a stored value is
+ * safe to interpolate into a URL.
+ */
+export function getTailscaleCertHostname(meta) {
+ if (meta?.mode !== 'tailscale' || typeof meta?.hostname !== 'string') return null;
+ const hostname = meta.hostname.trim().replace(/\.$/, '').toLowerCase();
+ if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+ts\.net$/.test(hostname)) {
+ return null;
+ }
+ return hostname;
+}
+
+/** Exact trusted PortOS origin from certificate metadata. */
+export function getTailscaleHttpsUrl(meta, port = 5555) {
+ const hostname = getTailscaleCertHostname(meta);
+ const numericPort = Number(port);
+ if (!hostname || !Number.isInteger(numericPort) || numericPort < 1 || numericPort > 65535) {
+ return null;
+ }
+ return `https://${hostname}:${numericPort}`;
+}
diff --git a/lib/certMeta.test.js b/lib/certMeta.test.js
index 6b76adf10b..7dccbb71ae 100644
--- a/lib/certMeta.test.js
+++ b/lib/certMeta.test.js
@@ -6,7 +6,11 @@ vi.mock('node:fs', () => ({
}));
import { readFileSync, statSync } from 'node:fs';
-import { readCertMeta } from './certMeta.js';
+import {
+ getTailscaleCertHostname,
+ getTailscaleHttpsUrl,
+ readCertMeta,
+} from './certMeta.js';
const META_PATH = '/mock/data/certs/meta.json';
@@ -81,3 +85,18 @@ describe('certMeta.readCertMeta', () => {
}
});
});
+
+describe('certMeta trusted Tailscale URL helpers', () => {
+ it('normalizes a valid Tailscale hostname and includes the PortOS port', () => {
+ const meta = { mode: 'tailscale', hostname: 'Host-Alpha.Example-Tailnet.TS.NET.' };
+ expect(getTailscaleCertHostname(meta)).toBe('host-alpha.example-tailnet.ts.net');
+ expect(getTailscaleHttpsUrl(meta, 6000)).toBe('https://host-alpha.example-tailnet.ts.net:6000');
+ });
+
+ it('rejects untrusted modes, non-Tailscale hostnames, and invalid ports', () => {
+ expect(getTailscaleCertHostname({ mode: 'self-signed', hostname: 'host.example.ts.net' })).toBeNull();
+ expect(getTailscaleCertHostname({ mode: 'tailscale', hostname: 'example.com' })).toBeNull();
+ expect(getTailscaleHttpsUrl({ mode: 'tailscale', hostname: 'host.example.ts.net' }, 0)).toBeNull();
+ expect(getTailscaleHttpsUrl({ mode: 'tailscale', hostname: 'host.example.ts.net' }, 65536)).toBeNull();
+ });
+});
diff --git a/package.json b/package.json
index b8ebac46a9..97411fa1bc 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,7 @@
"install:all": "npm run setup",
"doctor": "node scripts/doctor.js",
"migrations": "node scripts/run-migrations.js",
- "setup": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && git submodule update --init --recursive && npm install --no-save && npm install --no-save --prefix client && npm install --no-save --prefix server && npm install --no-save --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js",
+ "setup": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && git submodule update --init --recursive && npm install --no-save && npm install --no-save --prefix client && npm install --no-save --prefix server && npm install --no-save --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js && node scripts/setup-cert.js && node scripts/setup-guide.js",
"setup:data": "node scripts/setup-data.js",
"setup:db": "node scripts/setup-db.js",
"setup:db:test": "npm run setup:db:test --prefix server",
@@ -38,6 +38,7 @@
"setup:remote-desktop": "node scripts/setup-remote-desktop.js",
"fix:windows-console": "node scripts/fix-windows-console.js",
"setup:cert": "node scripts/setup-cert.js",
+ "setup:guide": "node scripts/setup-guide.js",
"setup:ghostty": "node scripts/setup-ghostty.js",
"setup:hooks": "bash scripts/setup-git-hooks.sh",
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
diff --git a/scripts/open-ui-in-browser.js b/scripts/open-ui-in-browser.js
index 54f70544a3..e1517c9549 100644
--- a/scripts/open-ui-in-browser.js
+++ b/scripts/open-ui-in-browser.js
@@ -9,6 +9,7 @@ import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { hasTailscaleCert } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
+import { getCliSetupGuide } from './setup-guide.js';
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const { dir: CERT_DIR } = certPaths(join(ROOT, 'data'));
@@ -22,12 +23,20 @@ const HTTPS_MODE = hasTailscaleCert(CERT_DIR);
// When HTTPS is on, :5555 speaks TLS only — plain http:// requests hit a TLS
// mismatch and time out. The loopback HTTP mirror on :5553 serves the same
-// app and skips the cert warning. We use it for both polling and the URL
-// handed to the browser. See docs/PORTS.md.
+// app and skips the cert warning, so startup polling always stays local even
+// when the final browser destination is the trusted MagicDNS origin.
const LOCAL_BASE = HTTPS_MODE
? `http://localhost:${HTTP_LOOPBACK_PORT}`
: `http://localhost:${API_PORT}`;
-const TARGET_URL = LOCAL_BASE;
+// Poll through loopback so certificate trust never delays startup detection,
+// but land the browser on the real MagicDNS origin when a trusted Tailscale
+// cert exists. That is the URL remote devices use and the secure context where
+// microphone/browser APIs work; opening the mirror hid this final setup step.
+// The shared walkthrough also proves that Tailscale is currently connected and
+// the cert matches its current MagicDNS name; a stale cert alone must not send
+// the managed browser to an unreachable host.
+const setupGuide = await getCliSetupGuide({ assumeActive: HTTPS_MODE });
+const TARGET_URL = setupGuide.trustedUrl || LOCAL_BASE;
// First-boot startup can take a while: the server binds, opens the DB pool,
// loads the brain index, attaches Socket.IO, then health responds. 90s is
diff --git a/scripts/print-access-url.js b/scripts/print-access-url.js
index b15f12a38f..252e257557 100644
--- a/scripts/print-access-url.js
+++ b/scripts/print-access-url.js
@@ -9,7 +9,7 @@
*/
import { hasTailscaleCert } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
-import { readCertMeta } from '../lib/certMeta.js';
+import { getTailscaleHttpsUrl, readCertMeta } from '../lib/certMeta.js';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
@@ -23,11 +23,13 @@ if (!hasTailscaleCert(CERT_DIR)) {
process.exit(0);
}
-const mode = readCertMeta(META_PATH)?.mode || '';
+const meta = readCertMeta(META_PATH);
+const mode = meta?.mode || '';
+const trustedUrl = getTailscaleHttpsUrl(meta, API_PORT);
console.log(`Access at: http://localhost:${MIRROR_PORT} (loopback HTTP mirror — no cert warning)`);
-if (mode === 'tailscale') {
- console.log(` or: https://<machine>.<tailnet>.ts.net:${API_PORT} (trusted via Tailscale)`);
+if (mode === 'tailscale' && trustedUrl) {
+ console.log(` or: ${trustedUrl} (trusted via Tailscale)`);
console.log(` or: https://localhost:${API_PORT} (browser warns — cert is for the Tailscale hostname)`);
} else if (mode === 'self-signed') {
console.log(` or: https://localhost:${API_PORT} (browser warns on first visit — self-signed cert)`);
diff --git a/scripts/setup-cert.js b/scripts/setup-cert.js
index cbf1b98cfb..982cfa9a79 100644
--- a/scripts/setup-cert.js
+++ b/scripts/setup-cert.js
@@ -27,6 +27,7 @@
* --self-signed skip Tailscale attempt and go straight to self-signed
*/
import { execFileSync } from 'child_process';
+import { X509Certificate } from 'crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'fs';
import { networkInterfaces } from 'os';
import { join, dirname } from 'path';
@@ -146,9 +147,15 @@ function readMeta() {
function certExpiresAt() {
if (!existsSync(CERT_PATH)) return null;
- const out = execFileSync('openssl', ['x509', '-in', CERT_PATH, '-noout', '-enddate']).toString();
- const match = out.match(/notAfter=(.+)/);
- return match ? new Date(match[1]) : null;
+ // Node already ships the same X.509 parser its TLS stack uses. Relying on an
+ // `openssl` executable here made otherwise-successful Tailscale provisioning
+ // fail on Windows, where OpenSSL is not normally on PATH.
+ try {
+ const expiresAt = new Date(new X509Certificate(readFileSync(CERT_PATH)).validTo);
+ return Number.isNaN(expiresAt.getTime()) ? null : expiresAt;
+ } catch {
+ return null;
+ }
}
function daysUntil(date) {
diff --git a/scripts/setup-guide.js b/scripts/setup-guide.js
new file mode 100644
index 0000000000..542fbca9e5
--- /dev/null
+++ b/scripts/setup-guide.js
@@ -0,0 +1,146 @@
+#!/usr/bin/env node
+/**
+ * PortOS first-run/update walkthrough.
+ *
+ * Reads the same Tailscale and certificate facts as the runtime API and formats
+ * the ordered guide from server/lib/networkExposure.js. It never prompts and
+ * never changes state: setup-cert.js owns the safe automatic provisioning
+ * attempt, while this script explains the remaining human-only actions.
+ */
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { certPaths } from '../lib/certPaths.js';
+import {
+ getTailscaleCertHostname,
+ readCertMeta,
+} from '../lib/certMeta.js';
+import { hasTailscaleCert } from '../lib/tailscale-https.js';
+import { buildNetworkSetupGuide } from '../server/lib/networkExposure.js';
+import { getTailscaleStatus } from '../server/lib/tailscale.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const DATA_DIR = join(ROOT, 'data');
+const { dir: CERT_DIR, meta: META_PATH } = certPaths(DATA_DIR);
+const API_PORT = Number(process.env.PORT) || 5555;
+const MIRROR_PORT = Number(process.env.PORTOS_HTTP_PORT) || 5553;
+
+const MARK = {
+ complete: '✓',
+ action: '→',
+ blocked: '·',
+ unknown: '?',
+};
+
+export function formatSetupGuide(guide, { localUrl, setupUrl } = {}) {
+ const lines = [
+ '===================================',
+ ' PortOS Setup Walkthrough',
+ '===================================',
+ '',
+ ];
+
+ for (const step of guide.steps || []) {
+ lines.push(`[${MARK[step.status] || '·'}] ${step.title}`);
+ lines.push(` ${step.detail}`);
+ if (step.action?.type === 'external' && step.action.url) {
+ lines.push(` ${step.action.label}: ${step.action.url}`);
+ } else if (step.action?.type === 'command' && step.action.command) {
+ lines.push(` Run: ${step.action.command}`);
+ } else if (step.action?.type === 'provision-cert') {
+ lines.push(` 1. Enable HTTPS Certificates: ${step.action.adminUrl}`);
+ lines.push(' 2. Re-run: npm run setup:cert');
+ } else if (step.action?.type === 'restart') {
+ lines.push(' Start/restart: npm start (first run) or npm run pm2:restart');
+ }
+ }
+
+ lines.push('', 'AI provider setup (enable at least one runnable option):');
+ lines.push(' • Subscription CLI: use a CLI you already installed and authenticated (Claude Code, Codex, or Antigravity).');
+ lines.push(' • API provider: add the key for the paid provider you intend to use.');
+ lines.push(' • Local/private: install Ollama or LM Studio plus a model under Models → LLMs.');
+ lines.push(' PortOS marks missing CLIs, keys, runtimes, and models in the Setup page; it never enables a paid provider automatically.');
+ if (setupUrl) lines.push(` Open setup: ${setupUrl}`);
+ if (guide.trustedUrl) lines.push('', `Trusted PortOS URL: ${guide.trustedUrl}`);
+ else if (localUrl) lines.push('', `Local PortOS URL: ${localUrl}`);
+
+ return lines.join('\n');
+}
+
+export function formatSetupSummary(guide) {
+ if (guide.complete) return `Trusted Tailscale HTTPS ready at ${guide.trustedUrl}`;
+ const next = guide.nextStep;
+ return next ? `${next.title} — ${next.detail}` : 'Tailscale HTTPS setup needs attention';
+}
+
+async function detectActiveHttps() {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 1500);
+ const response = await fetch(`http://localhost:${MIRROR_PORT}/api/system/health`, {
+ signal: controller.signal,
+ }).catch(() => null);
+ clearTimeout(timer);
+ if (!response?.ok) return false;
+ const health = await response.json().catch(() => null);
+ return health?.scheme === 'https';
+}
+
+export async function getCliSetupGuide({ assumeActive = null } = {}) {
+ const meta = readCertMeta(META_PATH);
+ const certProvisioned = hasTailscaleCert(CERT_DIR);
+ const provisionedMode = certProvisioned ? (meta?.mode || 'unknown') : null;
+ const provisionedHost = getTailscaleCertHostname(meta);
+ // Setup and the pre-restart update phase must not claim a newly written cert
+ // is already live. Wrappers pass `--assume-active` only after a successful
+ // PortOS restart; a direct invocation confirms the live scheme through the
+ // always-public loopback health route before dropping the restart action.
+ const httpsActive = certProvisioned && (assumeActive === null
+ ? await detectActiveHttps()
+ : assumeActive);
+ const network = {
+ httpsEnabled: httpsActive,
+ bind: { port: API_PORT },
+ cert: {
+ mode: certProvisioned ? provisionedMode : null,
+ tailscaleHost: provisionedHost,
+ provisioned: certProvisioned,
+ provisionedMode,
+ provisionedHost,
+ },
+ };
+ const tailscale = await getTailscaleStatus();
+ const guide = buildNetworkSetupGuide(network, tailscale);
+ const localUrl = certProvisioned
+ ? `http://localhost:${MIRROR_PORT}`
+ : `http://localhost:${API_PORT}`;
+ const browserBase = guide.trustedUrl || localUrl;
+ return {
+ ...guide,
+ localUrl,
+ setupUrl: `${browserBase}/capabilities`,
+ };
+}
+
+async function main() {
+ // The Unix wrapper may still auto-install the writable macOS Tailscale CLI
+ // after `npm run setup`; defer its one walkthrough until that attempt has
+ // finished so users see one current answer rather than an immediately stale
+ // checklist followed by a second copy.
+ if (process.env.PORTOS_DEFER_SETUP_GUIDE === '1') return;
+ const guide = await getCliSetupGuide({
+ assumeActive: process.argv.includes('--assume-active') ? true : null,
+ });
+ if (process.argv.includes('--json')) {
+ console.log(JSON.stringify(guide, null, 2));
+ return;
+ }
+ if (process.argv.includes('--summary')) {
+ console.log(formatSetupSummary(guide));
+ return;
+ }
+ console.log(formatSetupGuide(guide, guide));
+}
+
+const invokedPath = process.argv[1] ? resolve(process.argv[1]) : null;
+if (invokedPath === fileURLToPath(import.meta.url)) {
+ await main();
+}
diff --git a/scripts/setup-guide.test.js b/scripts/setup-guide.test.js
new file mode 100644
index 0000000000..9c1d0327b6
--- /dev/null
+++ b/scripts/setup-guide.test.js
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { formatSetupGuide, formatSetupSummary } from './setup-guide.js';
+
+const incompleteGuide = {
+ complete: false,
+ nextStep: {
+ id: 'https-cert',
+ title: 'Provision a trusted HTTPS certificate',
+ detail: 'Enable HTTPS Certificates, then let PortOS fetch the certificate.',
+ },
+ steps: [
+ {
+ id: 'tailscale-install',
+ title: 'Install Tailscale',
+ status: 'complete',
+ detail: 'The Tailscale CLI is installed.',
+ action: null,
+ },
+ {
+ id: 'magic-dns',
+ title: 'Enable MagicDNS',
+ status: 'complete',
+ detail: 'MagicDNS assigned host-alpha.example-tailnet.ts.net.',
+ action: null,
+ },
+ {
+ id: 'https-cert',
+ title: 'Provision a trusted HTTPS certificate',
+ status: 'action',
+ detail: 'Enable HTTPS Certificates, then let PortOS fetch the certificate.',
+ action: {
+ type: 'provision-cert',
+ label: 'Enable HTTPS',
+ adminUrl: 'https://login.tailscale.com/admin/dns',
+ },
+ },
+ ],
+};
+
+describe('setup walkthrough formatting', () => {
+ it('prints the ordered network actions and all three AI provider paths', () => {
+ const output = formatSetupGuide(incompleteGuide, {
+ localUrl: 'http://localhost:5555',
+ setupUrl: 'http://localhost:5555/capabilities',
+ });
+
+ expect(output).toContain('[✓] Install Tailscale');
+ expect(output).toContain('[→] Provision a trusted HTTPS certificate');
+ expect(output).toContain('https://login.tailscale.com/admin/dns');
+ expect(output).toContain('npm run setup:cert');
+ expect(output).toContain('Subscription CLI');
+ expect(output).toContain('API provider');
+ expect(output).toContain('Local/private');
+ expect(output).toContain('Open setup: http://localhost:5555/capabilities');
+ expect(output).toContain('Local PortOS URL: http://localhost:5555');
+ });
+
+ it('summarizes the next action without claiming setup is complete', () => {
+ expect(formatSetupSummary(incompleteGuide)).toBe(
+ 'Provision a trusted HTTPS certificate — Enable HTTPS Certificates, then let PortOS fetch the certificate.',
+ );
+ });
+
+ it('prints the exact trusted URL for a completed install', () => {
+ const guide = {
+ complete: true,
+ trustedUrl: 'https://host-alpha.example-tailnet.ts.net:5555',
+ nextStep: null,
+ steps: [],
+ };
+ expect(formatSetupSummary(guide)).toBe(
+ 'Trusted Tailscale HTTPS ready at https://host-alpha.example-tailnet.ts.net:5555',
+ );
+ expect(formatSetupGuide(guide)).toContain(
+ 'Trusted PortOS URL: https://host-alpha.example-tailnet.ts.net:5555',
+ );
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index cf8c4f5dc3..0dac3c12cd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -305,11 +305,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sharingOrigin.js` | Origin metadata for records imported from share buckets. |
| `syncIntegrity.js` | Pure diff of local vs remote manifest lists. `INTEGRITY_STATUS` constants + `computeRecordIntegrity(localList, remoteList)` — classifies each record as `in-parity`, `local-only`, `peer-only`, `diverged`, or `assets-missing`. No I/O. |
| `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). |
-| `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build (which can't write `tailscale cert` output outside its container), and read backend state (`getTailscaleStatus` / `isTailscaleUp`) to know whether we're actually connected to the tailnet. |
+| `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build, and return a normalized backend/MagicDNS/peer snapshot (`getTailscaleStatus` / `isTailscaleUp`). |
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
| `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Mirrors client `urlNormalize.js`'s `isHttpUrl`. |
-| `networkExposure.js` | Snapshot of scheme + bind + cert mode for the dashboard's Network Exposure widget. |
+| `networkExposure.js` | Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI. |
## Search & indexing
@@ -351,7 +351,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `appIdentity.js` | The baseline managed-app id (`PORTOS_APP_ID`) — importable without pulling in the `services/apps.js` graph (pm2, scheduler, settings) behind it. Re-exported by `apps.js`. |
| `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. |
-| `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. |
+| `capabilityMap.js` | Pure row builders for Setup & Capabilities, including strict network/provider first-run readiness and optional-integration health rollups; fed by `routes/capabilities.js`. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, pitch math (`pitchToMidi`/`midiToFreq`), and `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
| `civitai.js` | Civitai URL parsing + API client. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 444403cfa0..161d0905cd 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -3852,7 +3852,7 @@
"sources": [
{
"source": "server/routes/capabilities.js",
- "line": 51
+ "line": 57
}
]
},
@@ -11288,7 +11288,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 126
+ "line": 121
}
]
},
@@ -11299,7 +11299,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 141
+ "line": 136
}
]
},
@@ -11310,7 +11310,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 264
+ "line": 250
}
]
},
@@ -11321,7 +11321,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 292
+ "line": 278
}
]
},
@@ -11332,7 +11332,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 278
+ "line": 264
}
]
},
@@ -11343,7 +11343,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 299
+ "line": 285
}
]
},
@@ -11354,7 +11354,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 364
+ "line": 350
}
]
},
@@ -11365,7 +11365,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 336
+ "line": 322
}
]
},
@@ -11376,7 +11376,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 379
+ "line": 365
}
]
},
@@ -11387,7 +11387,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 324
+ "line": 310
}
]
},
@@ -11398,7 +11398,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 348
+ "line": 334
}
]
},
@@ -11409,7 +11409,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 237
+ "line": 223
}
]
},
@@ -11420,7 +11420,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 309
+ "line": 295
}
]
},
@@ -11431,7 +11431,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 206
+ "line": 192
}
]
},
@@ -11442,7 +11442,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 216
+ "line": 202
}
]
},
@@ -11453,7 +11453,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 229
+ "line": 215
}
]
},
@@ -11464,7 +11464,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 167
+ "line": 162
}
]
},
@@ -11475,7 +11475,7 @@
"sources": [
{
"source": "server/routes/instances.js",
- "line": 182
+ "line": 177
}
]
},
diff --git a/server/lib/capabilityMap.js b/server/lib/capabilityMap.js
index 21ae7788ee..3552e11626 100644
--- a/server/lib/capabilityMap.js
+++ b/server/lib/capabilityMap.js
@@ -10,6 +10,8 @@
// 'error' — configured but broken (red)
// 'unconfigured' — not set up yet (gray) — the setup-checklist signal
+import { localRuntimeForProvider } from './localProviderRuntime.js';
+
export const CAPABILITY_STATUS = Object.freeze({
OK: 'ok',
WARN: 'warn',
@@ -19,7 +21,14 @@ export const CAPABILITY_STATUS = Object.freeze({
const { OK, WARN, ERROR, UNCONFIGURED } = CAPABILITY_STATUS;
-const row = (id, label, settingsPath, { status, configured, summary, detail }) => ({
+const row = (id, label, settingsPath, {
+ status,
+ configured,
+ summary,
+ detail,
+ setupRequired = false,
+ setupComplete = status === OK,
+}) => ({
id,
label,
settingsPath,
@@ -27,39 +36,92 @@ const row = (id, label, settingsPath, { status, configured, summary, detail }) =
configured,
summary,
detail: detail ?? null,
+ setupRequired,
+ setupComplete,
});
const plural = (n, one, many) => (n === 1 ? one : (many ?? `${one}s`));
-export function providersRow(providers = [], statuses = {}) {
+export function providersRow(
+ providers = [],
+ statuses = {},
+ prerequisiteReadiness = undefined,
+ localReadiness = undefined,
+) {
const enabled = (Array.isArray(providers) ? providers : []).filter((p) => p && p.enabled !== false);
if (enabled.length === 0) {
return row('providers', 'AI Providers', '/ai', {
status: UNCONFIGURED,
configured: false,
summary: 'No AI providers configured',
+ setupRequired: true,
+ setupComplete: false,
});
}
// getAllProviderStatuses() returns { ...cache, providers: { [id]: status } }.
// A provider that was never marked unavailable has no entry — treat as available.
const statusMap = statuses?.providers ?? statuses ?? {};
+ const prerequisiteReadinessRequested = prerequisiteReadiness !== undefined;
+ const hasPrerequisiteReadiness = prerequisiteReadiness
+ && typeof prerequisiteReadiness === 'object'
+ && !Array.isArray(prerequisiteReadiness);
+ const localReadinessRequested = localReadiness !== undefined;
+ const hasLocalReadiness = localReadiness
+ && typeof localReadiness === 'object'
+ && !Array.isArray(localReadiness);
let available = 0;
let unavailable = 0;
+ let blocked = 0;
+ let unknown = 0;
+ let setupReady = 0;
for (const p of enabled) {
+ const prerequisite = hasPrerequisiteReadiness ? prerequisiteReadiness[p.id] : null;
+ if (prerequisite?.status === 'blocked') {
+ blocked += 1;
+ continue;
+ }
+ if (prerequisite?.status === 'unknown') {
+ unknown += 1;
+ continue;
+ }
+ if (prerequisiteReadinessRequested && prerequisite?.status !== 'ready') {
+ unknown += 1;
+ continue;
+ }
+ if (localReadinessRequested && localRuntimeForProvider(p)) {
+ const local = hasLocalReadiness ? localReadiness[p.id] : null;
+ if (local?.ready === false) {
+ const checks = Array.isArray(local.checks) ? local.checks : [];
+ if (checks.length > 0 && checks.every((check) => check?.ok !== false)) unknown += 1;
+ else blocked += 1;
+ continue;
+ }
+ if (local?.ready !== true) {
+ unknown += 1;
+ continue;
+ }
+ }
+ if (prerequisiteReadinessRequested) setupReady += 1;
const s = statusMap?.[p.id];
if (!s || s.available) available += 1;
else unavailable += 1;
}
let status = OK;
- if (available === 0) status = ERROR;
- else if (unavailable > 0) status = WARN;
- const parts = [`${enabled.length} configured`, `${available} available`];
+ if (available === 0) status = unknown > 0 ? WARN : ERROR;
+ else if (unavailable > 0 || blocked > 0 || unknown > 0) status = WARN;
+ const parts = [`${enabled.length} enabled`, `${available} ready`];
if (unavailable > 0) parts.push(`${unavailable} unavailable`);
+ if (blocked > 0) parts.push(`${blocked} need setup`);
+ if (unknown > 0) parts.push(`${unknown} still checking`);
return row('providers', 'AI Providers', '/ai', {
status,
configured: true,
summary: parts.join(' · '),
- detail: { configured: enabled.length, available, unavailable },
+ detail: prerequisiteReadinessRequested
+ ? { configured: enabled.length, available, unavailable, blocked, unknown, setupReady }
+ : { configured: enabled.length, available, unavailable },
+ setupRequired: true,
+ setupComplete: prerequisiteReadinessRequested ? setupReady > 0 : available > 0,
});
}
@@ -145,6 +207,22 @@ export function voiceRow(cfg = {}) {
}
export function networkRow(net = {}) {
+ if (net?.setup && typeof net.setup === 'object') {
+ const complete = net.setup.complete === true;
+ const started = net?.tailscale?.available === true || net?.cert?.provisioned === true;
+ return row('network', 'Tailscale & HTTPS', '/instances', {
+ status: complete ? OK : started ? WARN : UNCONFIGURED,
+ configured: started,
+ summary: net.setup.summary || 'Tailscale HTTPS setup is incomplete',
+ detail: {
+ https: !!net?.httpsEnabled,
+ tailscaleHost: net.setup.dnsName || net?.cert?.tailscaleHost || null,
+ nextStepId: net.setup.nextStep?.id || null,
+ },
+ setupRequired: true,
+ setupComplete: complete,
+ });
+ }
const https = !!net?.httpsEnabled;
const tailscaleHost = net?.cert?.tailscaleHost || null;
const tailscale = !!tailscaleHost;
@@ -153,6 +231,8 @@ export function networkRow(net = {}) {
status: UNCONFIGURED,
configured: false,
summary: 'HTTP only · Tailscale not detected',
+ setupRequired: true,
+ setupComplete: false,
});
}
return row('network', 'Tailscale & HTTPS', '/instances', {
@@ -163,6 +243,8 @@ export function networkRow(net = {}) {
tailscale ? `Tailscale: ${tailscaleHost}` : 'Tailscale not detected',
].join(' · '),
detail: { https, tailscaleHost },
+ setupRequired: true,
+ setupComplete: https && tailscale,
});
}
@@ -256,11 +338,16 @@ export function appsRow(summary = {}) {
*/
export function buildCapabilityRows(data = {}) {
return [
- providersRow(data.providers, data.providerStatuses),
+ networkRow(data.network),
+ providersRow(
+ data.providers,
+ data.providerStatuses,
+ data.providerPrerequisiteReadiness,
+ data.providerLocalReadiness,
+ ),
calendarRow(data.calendarAccounts),
brainRow({ memoryCount: data.memoryCount, embeddingProviderConfigured: data.embeddingProviderConfigured }),
voiceRow(data.voiceConfig),
- networkRow(data.network),
genomeRow(data.genome),
telegramRow(data.telegram),
messagesRow(data.messageAccounts),
@@ -289,3 +376,15 @@ export function summarizeCapabilities(rows = []) {
else overall = UNCONFIGURED;
return { ...counts, total: list.length, overall };
}
+
+/** Roll up only the two first-run contracts (network + one usable AI provider). */
+export function summarizeSetupCapabilities(rows = []) {
+ const setupRows = (Array.isArray(rows) ? rows : []).filter((entry) => entry?.setupRequired === true);
+ const ready = setupRows.filter((entry) => entry.setupComplete === true).length;
+ return {
+ total: setupRows.length,
+ ready,
+ remaining: setupRows.length - ready,
+ complete: setupRows.length > 0 && ready === setupRows.length,
+ };
+}
diff --git a/server/lib/capabilityMap.test.js b/server/lib/capabilityMap.test.js
index f9232ab05f..cd5eb6f69c 100644
--- a/server/lib/capabilityMap.test.js
+++ b/server/lib/capabilityMap.test.js
@@ -12,6 +12,7 @@ import {
appsRow,
buildCapabilityRows,
summarizeCapabilities,
+ summarizeSetupCapabilities,
} from './capabilityMap.js';
const { OK, WARN, ERROR, UNCONFIGURED } = CAPABILITY_STATUS;
@@ -46,6 +47,87 @@ describe('providersRow', () => {
const r = providersRow([{ id: 'a' }], { a: { available: false } });
expect(r.status).toBe(ERROR);
});
+
+ it('does not call an enabled provider ready when strict prerequisites are blocked or unknown', () => {
+ const blocked = providersRow(
+ [{ id: 'a' }],
+ { providers: {} },
+ { a: { status: 'blocked', reasonCodes: ['runtime'] } },
+ );
+ expect(blocked).toMatchObject({ status: ERROR, setupComplete: false });
+ expect(blocked.detail).toMatchObject({ available: 0, blocked: 1, unknown: 0, setupReady: 0 });
+
+ const unavailableProbe = providersRow([{ id: 'a' }], { providers: {} }, null);
+ expect(unavailableProbe).toMatchObject({ status: WARN, setupComplete: false });
+ expect(unavailableProbe.detail.unknown).toBe(1);
+ });
+
+ it('marks setup complete when at least one strictly ready provider exists', () => {
+ const r = providersRow(
+ [{ id: 'a' }, { id: 'b' }],
+ { providers: {} },
+ { a: { status: 'ready' }, b: { status: 'blocked' } },
+ );
+ expect(r).toMatchObject({ status: WARN, setupComplete: true });
+ expect(r.detail).toMatchObject({ available: 1, blocked: 1, setupReady: 1 });
+ });
+
+ it('keeps setup complete during a transient provider availability outage', () => {
+ const r = providersRow(
+ [{ id: 'a' }],
+ { providers: { a: { available: false, reason: 'rate-limit' } } },
+ { a: { status: 'ready' } },
+ );
+ expect(r).toMatchObject({ status: ERROR, setupComplete: true });
+ expect(r.detail).toMatchObject({ setupReady: 1, unavailable: 1 });
+ });
+
+ it('requires a local daemon provider to be running with its model ready', () => {
+ const provider = {
+ id: 'local',
+ type: 'api',
+ endpoint: 'http://localhost:11434/v1',
+ defaultModel: 'example-model',
+ };
+ const blocked = providersRow(
+ [provider],
+ { providers: {} },
+ { local: { status: 'ready' } },
+ { local: { ready: false } },
+ );
+ expect(blocked).toMatchObject({ status: ERROR, setupComplete: false });
+ expect(blocked.detail).toMatchObject({ blocked: 1, setupReady: 0 });
+
+ const ready = providersRow(
+ [provider],
+ { providers: {} },
+ { local: { status: 'ready' } },
+ { local: { ready: true } },
+ );
+ expect(ready).toMatchObject({ status: OK, setupComplete: true });
+ });
+
+ it('keeps local provider readiness unknown when its daemon probe fails', () => {
+ const r = providersRow(
+ [{ id: 'local', type: 'api', endpoint: 'http://localhost:11434/v1' }],
+ { providers: {} },
+ { local: { status: 'ready' } },
+ null,
+ );
+ expect(r).toMatchObject({ status: WARN, setupComplete: false });
+ expect(r.detail).toMatchObject({ unknown: 1, setupReady: 0 });
+ });
+
+ it('does not turn an inconclusive local model listing into a setup failure', () => {
+ const r = providersRow(
+ [{ id: 'local', type: 'api', endpoint: 'http://localhost:11434/v1' }],
+ { providers: {} },
+ { local: { status: 'ready' } },
+ { local: { ready: false, checks: [{ id: 'runtime', ok: true }, { id: 'model', ok: null }] } },
+ );
+ expect(r).toMatchObject({ status: WARN, setupComplete: false });
+ expect(r.detail).toMatchObject({ blocked: 0, unknown: 1 });
+ });
});
describe('calendarRow / messagesRow', () => {
@@ -121,6 +203,21 @@ describe('networkRow', () => {
expect(networkRow({ httpsEnabled: true, cert: {} }).status).toBe(WARN);
expect(networkRow({ httpsEnabled: false, cert: { tailscaleHost: 'h' } }).status).toBe(WARN);
});
+
+ it('uses the ordered setup contract when present', () => {
+ const r = networkRow({
+ httpsEnabled: false,
+ tailscale: { available: true },
+ setup: {
+ complete: false,
+ summary: 'Enable MagicDNS',
+ nextStep: { id: 'magic-dns' },
+ },
+ cert: {},
+ });
+ expect(r).toMatchObject({ status: WARN, setupRequired: true, setupComplete: false });
+ expect(r.detail.nextStepId).toBe('magic-dns');
+ });
});
describe('genomeRow', () => {
@@ -230,3 +327,22 @@ describe('summarizeCapabilities', () => {
expect(s).toMatchObject({ ok: 0, warn: 0, error: 0, unconfigured: 0, total: 2, overall: UNCONFIGURED });
});
});
+
+describe('summarizeSetupCapabilities', () => {
+ it('rolls up only essential first-run capabilities', () => {
+ expect(summarizeSetupCapabilities([
+ { setupRequired: true, setupComplete: true },
+ { setupRequired: true, setupComplete: false },
+ { setupRequired: false, setupComplete: false },
+ ])).toEqual({ total: 2, ready: 1, remaining: 1, complete: false });
+ });
+
+ it('requires a non-empty setup contract before reporting completion', () => {
+ expect(summarizeSetupCapabilities([])).toEqual({
+ total: 0,
+ ready: 0,
+ remaining: 0,
+ complete: false,
+ });
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index a047f10f5a..9215a69ce4 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -290,6 +290,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', feature: 'health', aliases: ['settings-mortalloom', 'mortalloom'] },
{ id: 'nav.settings.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Settings', feature: 'openclaw', aliases: ['openclaw', 'settings-openclaw'], keywords: ['operator', 'chat', 'agent', 'runtime', 'sessions', 'streaming'] },
{ id: 'nav.settings.security', path: '/settings/security', label: 'Security', section: 'Settings', aliases: ['settings-security', 'login-password', 'auth-password', 'password-settings'], keywords: ['password', 'login', 'auth', 'sign-in', 'lock', 'tailnet', 'sidecar'] },
+ { id: 'nav.capabilities', path: '/capabilities', label: 'Setup', section: 'Settings', aliases: ['setup', 'onboarding', 'walkthrough', 'capabilities', 'capability-map', 'integrations'], keywords: ['first run', 'status', 'setup', 'checklist', 'tailscale', 'https', 'dns', 'providers', 'connected systems', 'integrations', 'health overview'] },
{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },
{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },
{ id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },
@@ -297,7 +298,6 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.settings.call-host', path: '/voice/call-host', label: 'Call Host', section: 'Settings', feature: 'facetime', aliases: ['call-host', 'voice-call-host', 'facetime-call-host', 'audio-bridge', 'meeting-capture', 'capture-audio'], keywords: ['facetime', 'call audio', 'blackhole', 'bridge', 'attach', 'microphone', 'speaker', 'call host', 'meeting capture', 'transcribe meeting', 'record meeting'] },
{ id: 'nav.ambient', path: '/ambient', label: 'Ambient', section: 'Dev Tools', aliases: ['ambient', 'ambient-mode', 'ambient mode'], keywords: ['idle', 'background', 'display', 'screensaver', 'fullscreen'] },
- { id: 'nav.capabilities', path: '/capabilities', label: 'Capabilities', section: 'Dev Tools', aliases: ['capabilities', 'capability-map', 'integrations'], keywords: ['status', 'setup', 'checklist', 'connected systems', 'integrations', 'providers', 'health overview'] },
{ id: 'nav.data', path: '/data', label: 'Data', section: 'Dev Tools', aliases: ['data'] },
{ id: 'nav.instances', path: '/instances', label: 'Instances', section: 'Dev Tools', aliases: ['instances'] },
{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'Dev Tools', aliases: ['loops'] },
diff --git a/server/lib/networkExposure.js b/server/lib/networkExposure.js
index 1837622270..bf48c2eac4 100644
--- a/server/lib/networkExposure.js
+++ b/server/lib/networkExposure.js
@@ -14,10 +14,15 @@ import { PORTS } from './ports.js';
import { PATHS } from './fileUtils.js';
import { getHttpsEnabledAtBoot } from './httpsState.js';
import { getSelfHost } from './peerSelfHost.js';
+import { getTailscaleStatus } from './tailscale.js';
import { certPaths } from '../../lib/certPaths.js';
-import { readCertMeta } from '../../lib/certMeta.js';
+import { getTailscaleCertHostname, readCertMeta } from '../../lib/certMeta.js';
+import { hasTailscaleCert } from '../../lib/tailscale-https.js';
-const { meta: META_PATH } = certPaths(PATHS.data);
+const { dir: CERT_DIR, meta: META_PATH } = certPaths(PATHS.data);
+
+export const TAILSCALE_DOWNLOAD_URL = 'https://tailscale.com/download';
+export const TAILSCALE_DNS_ADMIN_URL = 'https://login.tailscale.com/admin/dns';
// docs/PORTS.md is checked into the repo but the server doesn't serve the
// docs/ directory, so link out to GitHub for the canonical guide rather than
@@ -42,6 +47,12 @@ export function getNetworkExposureStatus() {
const loopbackPort = Number(process.env.PORTOS_HTTP_PORT) || PORTS.API_LOCAL;
const meta = readCertMeta(META_PATH);
+ const certProvisioned = hasTailscaleCert(CERT_DIR);
+ const provisionedMode = certProvisioned ? (meta?.mode || 'unknown') : null;
+ const provisionedHost = certProvisioned ? getTailscaleCertHostname(meta) : null;
+ // The listener may still be serving the certificate loaded at boot even if
+ // its files or metadata were removed afterward. Preserve the runtime-facing
+ // `unknown` sentinel instead of incorrectly reporting plain HTTP/no cert.
const certMode = httpsEnabled ? (meta?.mode || 'unknown') : null;
const tailscaleHost = getSelfHost();
const tailscaleIps = Array.isArray(meta?.ips) ? meta.ips : [];
@@ -72,7 +83,189 @@ export function getNetworkExposureStatus() {
mode: certMode,
tailscaleHost,
ips: tailscaleIps,
+ provisioned: certProvisioned,
+ provisionedMode,
+ provisionedHost,
},
docsUrl: PORTS_DOCS_URL,
};
}
+
+const setupStep = (id, title, status, detail, action = null) => ({
+ id,
+ title,
+ status,
+ detail,
+ action,
+});
+
+const tailscaleStatusUnknown = (tailscale) => [
+ 'tailscale-status-failed',
+ 'tailscale-parse-error',
+].includes(tailscale?.reason);
+
+/**
+ * Ordered, side-effect-free remote-access walkthrough shared by the API and
+ * the setup/update CLI. `status` is one of complete/action/blocked/unknown;
+ * callers render the same facts in their own medium and execute actions only
+ * after an explicit user click (the CLI provisioner is invoked separately).
+ */
+export function buildNetworkSetupGuide(network = {}, tailscale = {}) {
+ const cert = network?.cert ?? {};
+ const port = Number(network?.bind?.port) || PORTS.API;
+ const currentDnsName = getTailscaleCertHostname({
+ mode: 'tailscale',
+ hostname: tailscale?.dnsName,
+ });
+ const provisionedHost = typeof cert?.provisionedHost === 'string' && cert.provisionedHost
+ ? cert.provisionedHost.replace(/\.$/, '').toLowerCase()
+ : null;
+ const accessHost = currentDnsName || provisionedHost;
+ const installed = tailscale?.available === true;
+ const running = tailscale?.running === true;
+ const statusUnknown = tailscaleStatusUnknown(tailscale);
+ const magicDnsReady = running && Boolean(currentDnsName);
+ const trustedCertProvisioned = cert?.provisioned === true
+ && cert?.provisionedMode === 'tailscale';
+ const certMatchesCurrentHost = trustedCertProvisioned
+ && Boolean(provisionedHost)
+ && (!currentDnsName || provisionedHost === currentDnsName);
+ const canActivate = certMatchesCurrentHost && magicDnsReady;
+ const trustedHttpsActive = network?.httpsEnabled === true
+ && cert?.mode === 'tailscale'
+ && canActivate;
+ const trustedUrl = trustedHttpsActive && accessHost
+ ? `https://${accessHost}:${port}`
+ : null;
+ const pendingTrustedUrl = canActivate && accessHost
+ ? `https://${accessHost}:${port}`
+ : null;
+
+ const writableCli = installed && tailscale?.sandboxed !== true;
+ const canProvision = magicDnsReady && writableCli;
+
+ const steps = [
+ setupStep(
+ 'tailscale-install',
+ 'Install Tailscale',
+ installed ? 'complete' : 'action',
+ installed
+ ? 'The Tailscale CLI is installed on this machine.'
+ : 'Install Tailscale on the PortOS host so other devices can reach it privately.',
+ installed ? null : { type: 'external', label: 'Install Tailscale', url: TAILSCALE_DOWNLOAD_URL },
+ ),
+ setupStep(
+ 'tailscale-connect',
+ 'Connect this machine',
+ running ? 'complete' : installed && statusUnknown ? 'unknown' : installed ? 'action' : 'blocked',
+ running
+ ? 'This machine is connected to its tailnet.'
+ : statusUnknown
+ ? 'PortOS could not read Tailscale status. Open Tailscale and confirm this machine is connected.'
+ : installed
+ ? `Tailscale is ${tailscale?.state || 'not connected'}. Open the Tailscale app and sign in.`
+ : 'Install Tailscale before connecting this machine.',
+ installed && !running
+ ? { type: 'external', label: 'Tailscale connection help', url: TAILSCALE_DOWNLOAD_URL }
+ : null,
+ ),
+ setupStep(
+ 'magic-dns',
+ 'Enable MagicDNS',
+ magicDnsReady ? 'complete' : running ? 'action' : 'blocked',
+ magicDnsReady
+ ? `MagicDNS assigned ${currentDnsName}.`
+ : running
+ ? 'Enable MagicDNS in the tailnet DNS admin so this machine gets a stable .ts.net name.'
+ : 'Connect Tailscale before checking the MagicDNS name.',
+ running && !magicDnsReady
+ ? { type: 'external', label: 'Open Tailscale DNS admin', url: TAILSCALE_DNS_ADMIN_URL }
+ : null,
+ ),
+ setupStep(
+ 'https-cert',
+ 'Provision a trusted HTTPS certificate',
+ certMatchesCurrentHost ? 'complete' : canProvision ? 'action' : 'blocked',
+ certMatchesCurrentHost
+ ? `A Tailscale certificate is installed for ${provisionedHost}.`
+ : tailscale?.sandboxed
+ ? 'The macOS App Store CLI cannot write PortOS certificate files. Install the writable CLI with `brew install tailscale`, then retry.'
+ : canProvision
+ ? 'Enable HTTPS Certificates in the Tailscale DNS admin, then let PortOS fetch the certificate automatically.'
+ : trustedCertProvisioned && currentDnsName && provisionedHost !== currentDnsName
+ ? `The installed certificate is for ${provisionedHost}; reprovision it for ${currentDnsName}.`
+ : 'Complete the Tailscale and MagicDNS steps first.',
+ tailscale?.sandboxed
+ ? { type: 'command', label: 'Install writable CLI', command: 'brew install tailscale' }
+ : canProvision && !certMatchesCurrentHost
+ ? { type: 'provision-cert', label: 'Enable HTTPS', adminUrl: TAILSCALE_DNS_ADMIN_URL }
+ : null,
+ ),
+ setupStep(
+ 'activate-https',
+ 'Launch PortOS on its trusted URL',
+ trustedHttpsActive ? 'complete' : canActivate ? 'action' : 'blocked',
+ trustedHttpsActive
+ ? `PortOS is live at ${trustedUrl}.`
+ : canActivate
+ ? `Restart PortOS, then open ${pendingTrustedUrl}.`
+ : certMatchesCurrentHost
+ ? 'Connect Tailscale and confirm its current MagicDNS name before launching the trusted URL.'
+ : 'Provision the trusted certificate before switching the listener to HTTPS.',
+ canActivate && !trustedHttpsActive
+ ? { type: 'restart', label: 'Restart PortOS', targetUrl: pendingTrustedUrl }
+ : trustedHttpsActive
+ ? { type: 'external', label: 'Open PortOS', url: trustedUrl }
+ : null,
+ ),
+ ];
+
+ const nextStep = trustedHttpsActive
+ ? null
+ : steps.find((step) => step.status === 'action')
+ || steps.find((step) => step.status === 'unknown')
+ || steps.find((step) => step.status !== 'complete')
+ || null;
+
+ return {
+ complete: trustedHttpsActive,
+ canProvision,
+ dnsName: currentDnsName,
+ trustedUrl,
+ pendingTrustedUrl,
+ nextStep,
+ steps,
+ summary: trustedHttpsActive
+ ? `Trusted Tailscale HTTPS is active at ${trustedUrl}`
+ : canActivate
+ ? 'Trusted certificate installed — restart PortOS to activate HTTPS'
+ : nextStep?.detail || 'Tailscale HTTPS setup is incomplete',
+ urls: {
+ download: TAILSCALE_DOWNLOAD_URL,
+ dnsAdmin: TAILSCALE_DNS_ADMIN_URL,
+ },
+ };
+}
+
+/** Runtime snapshot plus the ordered setup guide consumed by API clients. */
+export async function getNetworkExposureSetupStatus() {
+ const [network, tailscale] = await Promise.all([
+ Promise.resolve().then(() => getNetworkExposureStatus()),
+ getTailscaleStatus(),
+ ]);
+ return {
+ ...network,
+ // Setup surfaces need the local daemon/MagicDNS facts, not the peer map or
+ // peer IPs returned by `tailscale status`. Keep that separate for the
+ // explicitly peer-oriented Instances endpoint.
+ tailscale: {
+ available: tailscale.available,
+ running: tailscale.running,
+ state: tailscale.state,
+ reason: tailscale.reason,
+ sandboxed: tailscale.sandboxed,
+ dnsName: tailscale.dnsName,
+ },
+ setup: buildNetworkSetupGuide(network, tailscale),
+ };
+}
diff --git a/server/lib/networkExposure.test.js b/server/lib/networkExposure.test.js
index 6b5eb82592..34d48a0d1b 100644
--- a/server/lib/networkExposure.test.js
+++ b/server/lib/networkExposure.test.js
@@ -13,6 +13,14 @@ vi.mock('./peerSelfHost.js', () => ({
getSelfHost: vi.fn(),
}));
+vi.mock('./tailscale.js', () => ({
+ getTailscaleStatus: vi.fn(),
+}));
+
+vi.mock('../../lib/tailscale-https.js', () => ({
+ hasTailscaleCert: vi.fn(),
+}));
+
vi.mock('node:fs', () => ({
readFileSync: vi.fn(),
statSync: vi.fn(),
@@ -21,7 +29,14 @@ vi.mock('node:fs', () => ({
import { readFileSync, statSync } from 'node:fs';
import { getHttpsEnabledAtBoot } from './httpsState.js';
import { getSelfHost } from './peerSelfHost.js';
-import { getNetworkExposureStatus, isLoopbackHost } from './networkExposure.js';
+import { getTailscaleStatus } from './tailscale.js';
+import { hasTailscaleCert } from '../../lib/tailscale-https.js';
+import {
+ buildNetworkSetupGuide,
+ getNetworkExposureSetupStatus,
+ getNetworkExposureStatus,
+ isLoopbackHost,
+} from './networkExposure.js';
describe('networkExposure.isLoopbackHost', () => {
it.each([
@@ -49,6 +64,7 @@ describe('networkExposure.getNetworkExposureStatus', () => {
delete process.env.PORT;
delete process.env.PORTOS_HTTP_PORT;
statSync.mockReturnValue(undefined);
+ hasTailscaleCert.mockReturnValue(false);
});
afterEach(() => {
@@ -70,6 +86,7 @@ describe('networkExposure.getNetworkExposureStatus', () => {
it('reports HTTPS + tailscale mode when cert meta.json indicates tailscale', () => {
getHttpsEnabledAtBoot.mockReturnValue({ value: true, initialized: true });
getSelfHost.mockReturnValue('host-alpha.example-tailnet.ts.net');
+ hasTailscaleCert.mockReturnValue(true);
statSync.mockReturnValue({ mtimeMs: 1 });
readFileSync.mockReturnValue(JSON.stringify({
mode: 'tailscale',
@@ -82,6 +99,8 @@ describe('networkExposure.getNetworkExposureStatus', () => {
expect(status.httpsEnabled).toBe(true);
expect(status.loopbackMirror.enabled).toBe(true);
expect(status.cert.mode).toBe('tailscale');
+ expect(status.cert.provisioned).toBe(true);
+ expect(status.cert.provisionedHost).toBe('host-alpha.example-tailnet.ts.net');
expect(status.cert.tailscaleHost).toBe('host-alpha.example-tailnet.ts.net');
expect(status.cert.ips).toEqual(['100.64.0.50']);
});
@@ -89,6 +108,7 @@ describe('networkExposure.getNetworkExposureStatus', () => {
it('reports HTTPS + self-signed mode when meta.json mode is self-signed', () => {
getHttpsEnabledAtBoot.mockReturnValue({ value: true, initialized: true });
getSelfHost.mockReturnValue(null);
+ hasTailscaleCert.mockReturnValue(true);
statSync.mockReturnValue({ mtimeMs: 1 });
readFileSync.mockReturnValue(JSON.stringify({
mode: 'self-signed',
@@ -135,3 +155,168 @@ describe('networkExposure.getNetworkExposureStatus', () => {
expect(status.loopbackMirror.port).toBe(6001);
});
});
+
+describe('networkExposure.buildNetworkSetupGuide', () => {
+ const baseNetwork = {
+ httpsEnabled: false,
+ bind: { port: 5555 },
+ cert: {
+ mode: null,
+ provisioned: false,
+ provisionedMode: null,
+ provisionedHost: null,
+ tailscaleHost: null,
+ },
+ };
+
+ it('starts at Tailscale installation when the CLI is absent', () => {
+ const guide = buildNetworkSetupGuide(baseNetwork, {
+ available: false,
+ running: false,
+ reason: 'tailscale-not-installed',
+ });
+
+ expect(guide.complete).toBe(false);
+ expect(guide.nextStep).toMatchObject({ id: 'tailscale-install', status: 'action' });
+ expect(guide.steps.map((step) => step.id)).toEqual([
+ 'tailscale-install',
+ 'tailscale-connect',
+ 'magic-dns',
+ 'https-cert',
+ 'activate-https',
+ ]);
+ });
+
+ it('offers automatic provisioning after Tailscale and MagicDNS are ready', () => {
+ const guide = buildNetworkSetupGuide(baseNetwork, {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'Host-Alpha.Example-Tailnet.ts.net.',
+ });
+
+ expect(guide.canProvision).toBe(true);
+ expect(guide.dnsName).toBe('host-alpha.example-tailnet.ts.net');
+ expect(guide.nextStep).toMatchObject({
+ id: 'https-cert',
+ action: { type: 'provision-cert' },
+ });
+ });
+
+ it('asks for a restart when the trusted cert exists but this process booted on HTTP', () => {
+ const guide = buildNetworkSetupGuide({
+ ...baseNetwork,
+ cert: {
+ mode: null,
+ provisioned: true,
+ provisionedMode: 'tailscale',
+ provisionedHost: 'host-alpha.example-tailnet.ts.net',
+ },
+ }, {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ });
+
+ expect(guide.nextStep).toMatchObject({ id: 'activate-https', action: { type: 'restart' } });
+ expect(guide.pendingTrustedUrl).toBe('https://host-alpha.example-tailnet.ts.net:5555');
+ });
+
+ it('reports the exact trusted URL only when HTTPS is active for the current host', () => {
+ const guide = buildNetworkSetupGuide({
+ ...baseNetwork,
+ httpsEnabled: true,
+ cert: {
+ mode: 'tailscale',
+ provisioned: true,
+ provisionedMode: 'tailscale',
+ provisionedHost: 'host-alpha.example-tailnet.ts.net',
+ },
+ }, {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ });
+
+ expect(guide.complete).toBe(true);
+ expect(guide.nextStep).toBeNull();
+ expect(guide.trustedUrl).toBe('https://host-alpha.example-tailnet.ts.net:5555');
+ });
+
+ it('never constructs a trusted URL from invalid or missing certificate host metadata', () => {
+ const guide = buildNetworkSetupGuide({
+ ...baseNetwork,
+ httpsEnabled: true,
+ cert: {
+ mode: 'tailscale',
+ provisioned: true,
+ provisionedMode: 'tailscale',
+ provisionedHost: null,
+ },
+ }, {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'https://example.com/path',
+ });
+
+ expect(guide.complete).toBe(false);
+ expect(guide.dnsName).toBeNull();
+ expect(guide.trustedUrl).toBeNull();
+ expect(guide.pendingTrustedUrl).toBeNull();
+ });
+
+ it('does not report remote setup complete while Tailscale is disconnected', () => {
+ const guide = buildNetworkSetupGuide({
+ ...baseNetwork,
+ httpsEnabled: true,
+ cert: {
+ mode: 'tailscale',
+ provisioned: true,
+ provisionedMode: 'tailscale',
+ provisionedHost: 'host-alpha.example-tailnet.ts.net',
+ },
+ }, {
+ available: true,
+ running: false,
+ state: 'Stopped',
+ dnsName: null,
+ });
+
+ expect(guide.complete).toBe(false);
+ expect(guide.nextStep).toMatchObject({ id: 'tailscale-connect', status: 'action' });
+ expect(guide.trustedUrl).toBeNull();
+ });
+});
+
+describe('networkExposure.getNetworkExposureSetupStatus', () => {
+ it('publishes only local setup facts and excludes the Tailscale peer map', async () => {
+ readFileSync.mockImplementation(() => { throw new Error('missing'); });
+ statSync.mockReturnValue(undefined);
+ getHttpsEnabledAtBoot.mockReturnValue({ value: false, initialized: true });
+ getSelfHost.mockReturnValue(null);
+ hasTailscaleCert.mockReturnValue(false);
+ getTailscaleStatus.mockResolvedValue({
+ available: true,
+ running: true,
+ state: 'Running',
+ reason: 'running',
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ peers: [{ hostName: 'host-beta', ips: ['100.64.0.50'] }],
+ });
+
+ const status = await getNetworkExposureSetupStatus();
+ expect(status.tailscale).toEqual({
+ available: true,
+ running: true,
+ state: 'Running',
+ reason: 'running',
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ });
+ expect(JSON.stringify(status)).not.toContain('host-beta');
+ });
+});
diff --git a/server/lib/tailscale.js b/server/lib/tailscale.js
index bf01e5b22c..603c683912 100644
--- a/server/lib/tailscale.js
+++ b/server/lib/tailscale.js
@@ -73,19 +73,49 @@ export function isSandboxedTailscale(binPath) {
*/
export async function getTailscaleStatus() {
const bin = findTailscale();
- if (!bin) return { available: false, running: false, state: null, reason: 'tailscale-not-installed' };
+ const unavailable = (reason, { available = true } = {}) => ({
+ available,
+ running: false,
+ state: null,
+ reason,
+ sandboxed: bin ? isSandboxedTailscale(bin) : false,
+ dnsName: null,
+ magicDnsSuffix: null,
+ peers: [],
+ });
+ if (!bin) return unavailable('tailscale-not-installed', { available: false });
const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 })
.catch(() => ({ stdout: null }));
- if (!stdout) return { available: true, running: false, state: null, reason: 'tailscale-status-failed' };
+ if (!stdout) return unavailable('tailscale-status-failed');
// Guard against non-JSON output (warnings, partial reads) so we never throw.
const status = safeJSONParse(stdout, null);
- if (!status) return { available: true, running: false, state: null, reason: 'tailscale-parse-error' };
- const state = status.BackendState ?? null;
+ if (!status) return unavailable('tailscale-parse-error');
+ const state = typeof status?.BackendState === 'string' && status.BackendState.trim()
+ ? status.BackendState.trim()
+ : null;
+ const trimDnsName = (value) => typeof value === 'string'
+ ? value.trim().replace(/\.$/, '') || null
+ : null;
+ const peers = Object.values(status?.Peer ?? {}).map((peer) => ({
+ dnsName: trimDnsName(peer?.DNSName),
+ hostName: typeof peer?.HostName === 'string' && peer.HostName.trim()
+ ? peer.HostName.trim()
+ : null,
+ ips: Array.isArray(peer?.TailscaleIPs)
+ ? peer.TailscaleIPs.filter((ip) => typeof ip === 'string')
+ : [],
+ }));
return {
available: true,
running: state === 'Running',
state,
- reason: state === 'Running' ? 'running' : `tailscale-${(state || 'unknown').toLowerCase()}`
+ reason: state === 'Running' ? 'running' : `tailscale-${(state || 'unknown').toLowerCase()}`,
+ sandboxed: isSandboxedTailscale(bin),
+ dnsName: trimDnsName(status?.Self?.DNSName),
+ magicDnsSuffix: trimDnsName(
+ status?.CurrentTailnet?.MagicDNSSuffix ?? status?.MagicDNSSuffix,
+ ),
+ peers,
};
}
diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.js
index 1553274064..bae25cc699 100644
--- a/server/lib/tailscale.test.js
+++ b/server/lib/tailscale.test.js
@@ -174,7 +174,16 @@ describe('getTailscaleStatus / isTailscaleUp', () => {
existsSync.mockReturnValue(false);
process.env.PATH = '';
const status = await getTailscaleStatus();
- expect(status).toEqual({ available: false, running: false, state: null, reason: 'tailscale-not-installed' });
+ expect(status).toEqual({
+ available: false,
+ running: false,
+ state: null,
+ reason: 'tailscale-not-installed',
+ sandboxed: false,
+ dnsName: null,
+ magicDnsSuffix: null,
+ peers: [],
+ });
expect(execFile).not.toHaveBeenCalled();
expect(await isTailscaleUp()).toBe(false);
});
@@ -186,6 +195,32 @@ describe('getTailscaleStatus / isTailscaleUp', () => {
expect(await isTailscaleUp()).toBe(true);
});
+ it('normalizes the local MagicDNS name, suffix, and peer suggestions', async () => {
+ mockStatusJSON({
+ BackendState: 'Running',
+ Self: { DNSName: 'host-alpha.example-tailnet.ts.net.' },
+ CurrentTailnet: { MagicDNSSuffix: 'example-tailnet.ts.net.' },
+ Peer: {
+ peer1: {
+ DNSName: 'host-beta.example-tailnet.ts.net.',
+ HostName: 'host-beta',
+ TailscaleIPs: ['100.64.0.50'],
+ },
+ },
+ });
+
+ await expect(getTailscaleStatus()).resolves.toMatchObject({
+ running: true,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ magicDnsSuffix: 'example-tailnet.ts.net',
+ peers: [{
+ dnsName: 'host-beta.example-tailnet.ts.net',
+ hostName: 'host-beta',
+ ips: ['100.64.0.50'],
+ }],
+ });
+ });
+
it('reports not-running when Tailscale is installed but Stopped', async () => {
mockStatusJSON({ BackendState: 'Stopped' });
const status = await getTailscaleStatus();
diff --git a/server/routes/capabilities.js b/server/routes/capabilities.js
index 33d03548f6..a0c4b8a829 100644
--- a/server/routes/capabilities.js
+++ b/server/routes/capabilities.js
@@ -1,14 +1,20 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
-import { buildCapabilityRows, summarizeCapabilities } from '../lib/capabilityMap.js';
+import {
+ buildCapabilityRows,
+ summarizeCapabilities,
+ summarizeSetupCapabilities,
+} from '../lib/capabilityMap.js';
import { getAllProviders, getProviderById } from '../services/providers.js';
+import { getProviderPrerequisiteReadinessMap } from '../services/providerPrerequisites.js';
+import { getProviderReadinessMap } from '../services/providerReadiness.js';
import { getAllProviderStatuses } from '../services/providerStatus.js';
import { listAccounts as listCalendarAccounts } from '../services/calendarAccounts.js';
import { listAccounts as listMessageAccounts } from '../services/messageAccounts.js';
import { countMemories } from '../services/memoryBackend.js';
import { getConfig as getCosConfig } from '../services/cos.js';
import { getVoiceConfig } from '../services/voice/config.js';
-import { getNetworkExposureStatus } from '../lib/networkExposure.js';
+import { getNetworkExposureSetupStatus } from '../lib/networkExposure.js';
import { getGenomeSummary } from '../services/genome.js';
import { getSettings } from '../services/settings.js';
import * as telegram from '../services/telegram.js';
@@ -49,8 +55,22 @@ async function resolveTelegram() {
// GET /api/capabilities — capability map of every connected system.
router.get('/', asyncHandler(async (req, res) => {
+ const providersPromise = getAllProviders().catch(() => ({ providers: [] }));
+ const providerPrerequisiteReadinessPromise = providersPromise.then((data) => {
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
+ const enabled = providers.filter((provider) => provider?.enabled !== false);
+ return getProviderPrerequisiteReadinessMap(providers, { candidates: enabled });
+ }).catch(() => null);
+ const providerLocalReadinessPromise = providersPromise.then((data) => {
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
+ const enabled = providers.filter((provider) => provider?.enabled !== false);
+ return getProviderReadinessMap(enabled);
+ }).catch(() => null);
+
const [
providersData,
+ providerPrerequisiteReadiness,
+ providerLocalReadiness,
providerStatuses,
calendarAccounts,
messageAccounts,
@@ -62,7 +82,9 @@ router.get('/', asyncHandler(async (req, res) => {
appSummary,
network,
] = await Promise.all([
- getAllProviders().catch(() => ({ providers: [] })),
+ providersPromise,
+ providerPrerequisiteReadinessPromise,
+ providerLocalReadinessPromise,
Promise.resolve().then(() => getAllProviderStatuses()).catch(() => ({})),
listCalendarAccounts().catch(() => []),
listMessageAccounts().catch(() => []),
@@ -72,13 +94,13 @@ router.get('/', asyncHandler(async (req, res) => {
getGenomeSummary().catch(() => ({ uploaded: false })),
resolveTelegram().catch(() => ({})),
apps.getAppStatusSummary().catch(() => ({ total: 0 })),
- // Synchronous in-memory read — wrap so a cert-meta read failure degrades
- // to {} instead of 500-ing the whole page (no try/catch in route bodies).
- Promise.resolve().then(() => getNetworkExposureStatus()).catch(() => ({})),
+ getNetworkExposureSetupStatus().catch(() => ({})),
]);
const rows = buildCapabilityRows({
providers: providersData?.providers ?? [],
+ providerPrerequisiteReadiness,
+ providerLocalReadiness,
providerStatuses,
calendarAccounts,
messageAccounts,
@@ -94,7 +116,9 @@ router.get('/', asyncHandler(async (req, res) => {
res.json({
timestamp: new Date().toISOString(),
summary: summarizeCapabilities(rows),
+ setup: summarizeSetupCapabilities(rows),
capabilities: rows,
+ network,
});
}));
diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.js
index 7192ef50e7..fbb35aeed2 100644
--- a/server/routes/capabilities.test.js
+++ b/server/routes/capabilities.test.js
@@ -12,6 +12,14 @@ vi.mock('../services/providers.js', () => ({
vi.mock('../services/providerStatus.js', () => ({
getAllProviderStatuses: vi.fn(() => ({ providers: {} })),
}));
+vi.mock('../services/providerPrerequisites.js', () => ({
+ getProviderPrerequisiteReadinessMap: vi.fn(async () => ({
+ p1: { status: 'ready', reasonCodes: [] },
+ })),
+}));
+vi.mock('../services/providerReadiness.js', () => ({
+ getProviderReadinessMap: vi.fn(async () => ({})),
+}));
vi.mock('../services/calendarAccounts.js', () => ({
listAccounts: vi.fn(async () => [{ enabled: true, lastSyncStatus: 'success' }]),
}));
@@ -28,7 +36,19 @@ vi.mock('../services/voice/config.js', () => ({
getVoiceConfig: vi.fn(async () => ({ enabled: true, tts: { engine: 'kokoro' }, stt: { engine: 'whisper' } })),
}));
vi.mock('../lib/networkExposure.js', () => ({
- getNetworkExposureStatus: vi.fn(() => ({ httpsEnabled: true, cert: { tailscaleHost: 'host.ts.net' } })),
+ getNetworkExposureSetupStatus: vi.fn(async () => ({
+ httpsEnabled: true,
+ bind: { port: 5555 },
+ cert: { mode: 'tailscale', tailscaleHost: 'host.example.ts.net', provisioned: true },
+ tailscale: { available: true, running: true },
+ setup: {
+ complete: true,
+ trustedUrl: 'https://host.example.ts.net:5555',
+ summary: 'Trusted Tailscale HTTPS is active',
+ nextStep: null,
+ steps: [],
+ },
+ })),
}));
vi.mock('../services/genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({ uploaded: true, markerCount: 10, statusCounts: {} })),
@@ -48,6 +68,9 @@ vi.mock('../services/apps.js', () => ({
const { countMemories } = await import('../services/memoryBackend.js');
const { getGenomeSummary } = await import('../services/genome.js');
+const { getAllProviders } = await import('../services/providers.js');
+const { getProviderPrerequisiteReadinessMap } = await import('../services/providerPrerequisites.js');
+const { getProviderReadinessMap } = await import('../services/providerReadiness.js');
const { default: capabilitiesRoutes } = await import('./capabilities.js');
const makeApp = () => {
@@ -67,6 +90,8 @@ describe('GET /api/capabilities', () => {
expect(Array.isArray(res.body.capabilities)).toBe(true);
expect(res.body.capabilities).toHaveLength(9);
expect(res.body.summary).toMatchObject({ overall: expect.any(String), total: 9 });
+ expect(res.body.setup).toEqual({ total: 2, ready: 2, remaining: 0, complete: true });
+ expect(res.body.network.setup.complete).toBe(true);
// every row is fully formed + deep-links to settings
for (const c of res.body.capabilities) {
expect(c.id).toBeTruthy();
@@ -100,4 +125,54 @@ describe('GET /api/capabilities', () => {
expect(res.status).toBe(200);
expect(byId(res.body, 'brain').detail.memoryCount).toBe(0);
});
+
+ it('keeps provider setup incomplete when strict prerequisite probing fails', async () => {
+ getProviderPrerequisiteReadinessMap.mockRejectedValueOnce(new Error('probe unavailable'));
+ const res = await request(makeApp()).get('/api/capabilities');
+
+ expect(res.status).toBe(200);
+ expect(byId(res.body, 'providers')).toMatchObject({
+ status: 'warn',
+ setupComplete: false,
+ detail: { available: 0, unknown: 1, setupReady: 0 },
+ });
+ expect(res.body.setup).toMatchObject({ complete: false, remaining: 1 });
+ });
+
+ it('keeps local provider setup unknown when daemon readiness probing fails', async () => {
+ getProviderReadinessMap.mockRejectedValueOnce(new Error('daemon probe unavailable'));
+ const res = await request(makeApp()).get('/api/capabilities');
+
+ expect(res.status).toBe(200);
+ // The default fixture is not local-daemon backed, so an unrelated local
+ // probe outage must not invalidate its proven CLI/API prerequisites.
+ expect(byId(res.body, 'providers')).toMatchObject({ setupComplete: true });
+ });
+
+ it('requires an enabled local provider daemon and selected model to be ready', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: 'local',
+ providers: [{
+ id: 'local',
+ enabled: true,
+ type: 'api',
+ endpoint: 'http://localhost:11434/v1',
+ defaultModel: 'example-model',
+ }],
+ });
+ getProviderPrerequisiteReadinessMap.mockResolvedValueOnce({
+ local: { status: 'ready', reasonCodes: [] },
+ });
+ getProviderReadinessMap.mockResolvedValueOnce({
+ local: { ready: false, checks: [{ id: 'model', ok: false }] },
+ });
+
+ const res = await request(makeApp()).get('/api/capabilities');
+ expect(res.status).toBe(200);
+ expect(byId(res.body, 'providers')).toMatchObject({
+ status: 'error',
+ setupComplete: false,
+ detail: { blocked: 1, setupReady: 0 },
+ });
+ });
});
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 78d06c02ed..79e51df9fa 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -6,20 +6,15 @@
import { Router } from 'express';
import { z } from 'zod';
-import { execFile } from '../lib/childProcess.js';
-import { promisify } from 'util';
import * as instances from '../services/instances.js';
import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';
import { getFullSyncCoverageForPeer } from '../services/sharing/peerSync.js';
import { provisionTailscaleCert } from '../services/certProvisioner.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
-import { findTailscale } from '../lib/tailscale.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { getTailscaleStatus } from '../lib/tailscale.js';
import { federatedMediaPeerSettingsSchema, validateRequest } from '../lib/validation.js';
-const execFileAsync = promisify(execFile);
-
const router = Router();
// Optional HTTP Basic credential for a peer behind an auth proxy. `null` clears
@@ -180,22 +175,13 @@ router.get('/sync-status', asyncHandler(async (req, res) => {
// so the UI can auto-suggest DNS names (e.g., `phone-example` + `.example-tailnet.ts.net`)
// for peers that currently use bare IP addresses.
router.get('/tailnet-suffix', asyncHandler(async (req, res) => {
- const bin = findTailscale();
- if (!bin) return res.json({ suffix: null, reason: 'tailscale-not-installed' });
- const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 }).catch(() => ({ stdout: null }));
- if (!stdout) return res.json({ suffix: null, reason: 'tailscale-not-running' });
- // Guard against non-JSON output (warnings, partial reads, etc.) so we never 500 the endpoint.
- const status = safeJSONParse(stdout, null);
- if (!status) return res.json({ suffix: null, reason: 'tailscale-parse-error' });
- const suffix = status?.CurrentTailnet?.MagicDNSSuffix ?? status?.MagicDNSSuffix ?? null;
- // Also include the peer map so the UI can auto-match a peer's instanceId/hostname
- // to its tailnet DNS name without asking the peer.
- const peers = Object.values(status?.Peer ?? {}).map(p => ({
- dnsName: (p.DNSName ?? '').replace(/\.$/, ''),
- hostName: p.HostName ?? null,
- ips: p.TailscaleIPs ?? []
- }));
- res.json({ suffix, self: (status?.Self?.DNSName ?? '').replace(/\.$/, '') || null, peers });
+ const status = await getTailscaleStatus();
+ res.json({
+ suffix: status.magicDnsSuffix,
+ self: status.dnsName,
+ peers: status.peers,
+ reason: status.reason,
+ });
}));
// POST /api/instances/provision-cert — runtime helper for the Tailscale/MagicDNS
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index f0ecf1027b..d0c5c46da8 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -21,11 +21,12 @@ vi.mock('../services/certProvisioner.js', () => ({
provisionTailscaleCert: vi.fn(),
}));
vi.mock('../lib/tailscale.js', () => ({
- findTailscale: vi.fn(() => null),
+ getTailscaleStatus: vi.fn(),
}));
import { getSyncStatus } from '../services/syncOrchestrator.js';
import * as instances from '../services/instances.js';
+import { getTailscaleStatus } from '../lib/tailscale.js';
import instancesRoutes from './instances.js';
const buildApp = () => {
@@ -36,6 +37,36 @@ const buildApp = () => {
return app;
};
+describe('GET /api/instances/tailnet-suffix', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns the shared normalized MagicDNS snapshot used by setup guidance', async () => {
+ getTailscaleStatus.mockResolvedValue({
+ reason: 'running',
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ magicDnsSuffix: 'example-tailnet.ts.net',
+ peers: [{
+ dnsName: 'host-beta.example-tailnet.ts.net',
+ hostName: 'host-beta',
+ ips: ['100.64.0.50'],
+ }],
+ });
+
+ const res = await request(buildApp()).get('/api/instances/tailnet-suffix');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ reason: 'running',
+ self: 'host-alpha.example-tailnet.ts.net',
+ suffix: 'example-tailnet.ts.net',
+ peers: [{
+ dnsName: 'host-beta.example-tailnet.ts.net',
+ hostName: 'host-beta',
+ ips: ['100.64.0.50'],
+ }],
+ });
+ });
+});
+
// #4520: the CoS task form's instance picker reads this. It is deliberately
// narrower than GET /api/instances — no addresses, no sync state, no peer that
// has yet to advertise a federation identity.
diff --git a/server/routes/networkExposure.js b/server/routes/networkExposure.js
index 68be625275..64cada207b 100644
--- a/server/routes/networkExposure.js
+++ b/server/routes/networkExposure.js
@@ -1,11 +1,11 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
-import { getNetworkExposureStatus } from '../lib/networkExposure.js';
+import { getNetworkExposureSetupStatus } from '../lib/networkExposure.js';
const router = Router();
router.get('/status', asyncHandler(async (_req, res) => {
- res.json(getNetworkExposureStatus());
+ res.json(await getNetworkExposureSetupStatus());
}));
export default router;
diff --git a/server/routes/networkExposure.test.js b/server/routes/networkExposure.test.js
index 6901efd739..3b8a226ba4 100644
--- a/server/routes/networkExposure.test.js
+++ b/server/routes/networkExposure.test.js
@@ -4,13 +4,14 @@ import { request } from '../lib/testHelper.js';
import networkExposureRoutes from './networkExposure.js';
vi.mock('../lib/networkExposure.js', () => ({
- getNetworkExposureStatus: vi.fn().mockReturnValue({
+ getNetworkExposureSetupStatus: vi.fn().mockResolvedValue({
scheme: 'https',
httpsEnabled: true,
httpsStateInitialized: true,
bind: { host: '0.0.0.0', port: 5555, audience: 'all-interfaces' },
loopbackMirror: { enabled: true, port: 5553 },
cert: { mode: 'tailscale', tailscaleHost: 'host-alpha.example-tailnet.ts.net', ips: [] },
+ setup: { complete: true, trustedUrl: 'https://host-alpha.example-tailnet.ts.net:5555' },
docsUrl: 'https://github.com/atomantic/PortOS/blob/main/docs/PORTS.md',
}),
}));
@@ -27,6 +28,7 @@ describe('Network Exposure Routes', () => {
expect(res.body.bind.port).toBe(5555);
expect(res.body.loopbackMirror.port).toBe(5553);
expect(res.body.cert.tailscaleHost).toBe('host-alpha.example-tailnet.ts.net');
+ expect(res.body.setup.complete).toBe(true);
expect(res.body.docsUrl).toMatch(/PORTS\.md$/);
});
});
diff --git a/setup.ps1 b/setup.ps1
index 3cbb04c122..314073c65b 100644
--- a/setup.ps1
+++ b/setup.ps1
@@ -86,8 +86,14 @@ node scripts/setup-data.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
node scripts/setup-db.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+node scripts/setup-llm.js
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
node scripts/setup-browser.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+node scripts/setup-cert.js
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+node scripts/setup-guide.js
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# Install/update slash-do (project-level slash commands for Claude Code et al.)
# via npx. Failures are non-fatal — PortOS still works without the
@@ -120,5 +126,5 @@ Write-Host " Production: " -NoNewline; Write-Host "npm start" -ForegroundColo
Write-Host " Stop: " -NoNewline; Write-Host "npm run pm2:stop" -ForegroundColor Cyan
Write-Host " Logs: " -NoNewline; Write-Host "npm run pm2:logs" -ForegroundColor Cyan
Write-Host ""
-Write-Host "Access at: " -NoNewline; Write-Host "http://localhost:5555" -ForegroundColor Yellow
+node scripts/print-access-url.js | ForEach-Object { Write-Host $_ -ForegroundColor Yellow }
Write-Host ""
diff --git a/setup.sh b/setup.sh
index 9b76b8900e..973f439569 100755
--- a/setup.sh
+++ b/setup.sh
@@ -40,7 +40,7 @@ fi
# deps + the trusted native rebuilds (scripts/trusted-rebuilds.js) + data dir, db, and browser
# setup. install:all is kept as a backward-compat alias.
echo "Installing dependencies and running setup..."
-if ! npm run setup; then
+if ! PORTOS_DEFER_SETUP_GUIDE=1 npm run setup; then
echo ""
echo "==================================="
echo " Setup incomplete"
@@ -76,9 +76,9 @@ if node --input-type=module -e "import('./server/lib/tailscale.js').then(m => pr
echo " Without it, the 'Enable HTTPS' button on the Instances page will fail with EPERM."
fi
# Re-run cert setup now that the unsandboxed CLI is available. `npm run
- # setup` already ran setup-cert.js with only the sandboxed CLI, falling
- # back to self-signed; without this re-run the instance stays on the
- # fallback cert until the user manually invokes `npm run setup:cert`.
+ # setup` already made a safe attempt with only the sandboxed CLI, but it
+ # deliberately stayed on HTTP rather than silently creating a self-signed
+ # fallback. This second attempt can now write the trusted cert files.
if [ "$brewInstalled" = "1" ]; then
echo "Re-running cert provisioning with the freshly-installed Tailscale CLI..."
npm run setup:cert || echo "⚠️ setup:cert failed — re-run manually if needed."
@@ -211,6 +211,8 @@ if [ "$start_now" = "1" ]; then
echo "==================================="
echo ""
print_access_url
+ echo ""
+ node scripts/setup-guide.js --assume-active
echo "Logs: npm run pm2:logs"
echo "Stop: npm run pm2:stop"
echo ""
@@ -227,4 +229,6 @@ else
echo ""
print_access_url
echo ""
+ node scripts/setup-guide.js
+ echo ""
fi
diff --git a/update.ps1 b/update.ps1
index e7719b0453..ff22de7eb3 100644
--- a/update.ps1
+++ b/update.ps1
@@ -286,8 +286,8 @@ if (-not (Test-Path "client/node_modules/vite/bin/vite.js")) {
Step "npm-install" "done" "Dependencies installed"
# Run data/db/browser setup. Don't call `npm run setup` — that re-runs the
-# installs we just did above. The three scripts here are the data-side half
-# of `npm run setup` and are idempotent.
+# installs we just did above. These scripts are the data-side half of
+# `npm run setup` and are idempotent.
Step "setup" "running" "Running setup..."
Invoke-Logged node scripts/setup-data.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
@@ -299,6 +299,23 @@ Invoke-Logged node scripts/setup-ghostty.js
Step "setup" "done" "Setup complete"
Write-SafeHost ""
+# Retry the safe Tailscale certificate path on every update. Missing sign-in,
+# MagicDNS, or the admin HTTPS toggle is reported as guidance rather than a
+# failed update; setup-guide owns the shared human-readable next step.
+Step "network-setup" "running" "Checking Tailscale, MagicDNS, and HTTPS..."
+Invoke-Logged node scripts/setup-cert.js
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+$networkSummary = & {
+ $ErrorActionPreference = 'Continue'
+ & node scripts/setup-guide.js --summary 2>> $UpdateLog
+}
+if ($LASTEXITCODE -ne 0 -or -not $networkSummary) {
+ $networkSummary = "Network setup checked"
+ $global:LASTEXITCODE = 0
+}
+Step "network-setup" "done" ($networkSummary -join " ")
+Write-SafeHost ""
+
# Run data migrations
Step "migrations" "running" "Running data migrations..."
$migrationsScript = Join-Path $RootDir "scripts\run-migrations.js"
@@ -405,6 +422,16 @@ if ($accessUrl) {
Write-SafeHost ""
}
+$setupGuide = & {
+ $ErrorActionPreference = 'Continue'
+ & node scripts/setup-guide.js --assume-active 2>$null
+}
+$global:LASTEXITCODE = 0
+if ($setupGuide) {
+ $setupGuide | ForEach-Object { Write-SafeHost $_ -ForegroundColor Cyan }
+ Write-SafeHost ""
+}
+
if ($stashedForBranch) {
Write-SafeHost "ℹ️ Your local changes from '$stashedForBranch' were stashed for the update." -ForegroundColor Cyan
if ($stashedForBranch -eq "detached HEAD") {
diff --git a/update.sh b/update.sh
index 8a3e09492d..58a53a4cad 100755
--- a/update.sh
+++ b/update.sh
@@ -211,8 +211,8 @@ fi
step "npm-install" "done" "Dependencies installed"
# Run data/db/browser setup. Don't call `npm run setup` — that re-runs the
-# installs we just did above. The three scripts here are the data-side half
-# of `npm run setup` and are idempotent.
+# installs we just did above. These scripts are the data-side half of
+# `npm run setup` and are idempotent.
step "setup" "running" "Running setup..."
run node scripts/setup-data.js
run node scripts/setup-db.js
@@ -221,6 +221,15 @@ run node scripts/setup-ghostty.js || true
step "setup" "done" "Setup complete"
log ""
+# Retry the safe Tailscale certificate path on every update. setup-cert exits 0
+# with an actionable explanation when a human-only prerequisite (sign-in,
+# MagicDNS, HTTPS Certificates) is missing, so updates never hang or fail on it.
+step "network-setup" "running" "Checking Tailscale, MagicDNS, and HTTPS..."
+run node scripts/setup-cert.js
+network_summary=$(node scripts/setup-guide.js --summary 2>> "$UPDATE_LOG" || true)
+step "network-setup" "done" "${network_summary:-Network setup checked}"
+log ""
+
# Ensure ffmpeg is present — it's a runtime dependency for the media/video
# features (camera-device enumeration, video generation, thumbnailing, audio
# mux) that server/lib/ffmpeg.js shells out to, not an npm package. Without it
@@ -371,6 +380,12 @@ if [ -n "$access_url" ]; then
log ""
fi
+setup_guide=$(node scripts/setup-guide.js --assume-active 2>/dev/null || true)
+if [ -n "$setup_guide" ]; then
+ log "$setup_guide"
+ log ""
+fi
+
if [ -n "$stashed_for_branch" ]; then
log "ℹ️ Your local changes from '$stashed_for_branch' were stashed for the update."
if [ "$stashed_for_branch" = "detached HEAD" ]; then