Skip to content

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

fix: keep setup guidance current and accurate

Adam Eivy0ebf9f053292
diff --git a/client/src/components/SetupBanner.jsx b/client/src/components/SetupBanner.jsx
index 4ce5f105f2..da44916834 100644
--- a/client/src/components/SetupBanner.jsx
+++ b/client/src/components/SetupBanner.jsx
@@ -21,7 +21,7 @@ export default function SetupBanner() {
})
.catch(() => {});
return () => { cancelled = true; };
- }, []);
+ }, [location.pathname]);
const setup = setupState?.setup;
if (!setup || setup.complete || location.pathname === '/capabilities') return null;
diff --git a/client/src/components/SetupBanner.test.jsx b/client/src/components/SetupBanner.test.jsx
index 7ee1c59c21..762a42a881 100644
--- a/client/src/components/SetupBanner.test.jsx
+++ b/client/src/components/SetupBanner.test.jsx
@@ -41,6 +41,7 @@ describe('SetupBanner', () => {
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();
+ await waitFor(() => expect(api.getCapabilities).toHaveBeenCalledTimes(2));
});
it('dismisses only the current setup state for the browser session', async () => {
diff --git a/client/src/pages/CapabilityMap.jsx b/client/src/pages/CapabilityMap.jsx
index cb6eb48aaa..990d1f4c1a 100644
--- a/client/src/pages/CapabilityMap.jsx
+++ b/client/src/pages/CapabilityMap.jsx
@@ -69,10 +69,11 @@ 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 optionalSummary = data.optionalSummary || summary;
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 overallStyle = STATUS_STYLE[optionalSummary.overall] || STATUS_STYLE.unconfigured;
const OverallIcon = overallStyle.icon;
return (
@@ -127,15 +128,15 @@ export default function CapabilityMap() {
</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>
+ <span className="text-xs font-semibold">{OVERALL_LABEL[optionalSummary.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>
+ <span className="flex items-center gap-1"><CheckCircle size={12} className="text-port-success" /> {optionalSummary.ok} ready</span>
+ <span className="flex items-center gap-1"><AlertTriangle size={12} className="text-port-warning" /> {optionalSummary.warn} degraded</span>
+ <span className="flex items-center gap-1"><XCircle size={12} className="text-port-error" /> {optionalSummary.error} error</span>
+ <span className="flex items-center gap-1"><Circle size={12} className="text-gray-500" /> {optionalSummary.unconfigured} not set up</span>
</div>
<div className="grid grid-cols-1 gap-2 lg:grid-cols-2">
diff --git a/client/src/pages/CapabilityMap.test.jsx b/client/src/pages/CapabilityMap.test.jsx
index ac4d1098e4..b5d87473e9 100644
--- a/client/src/pages/CapabilityMap.test.jsx
+++ b/client/src/pages/CapabilityMap.test.jsx
@@ -8,6 +8,7 @@ vi.mock('../hooks/useAutoRefetch', () => ({
data: {
setup: { total: 2, ready: 0, remaining: 2, complete: false },
summary: { ok: 0, warn: 2, error: 0, unconfigured: 1, total: 3, overall: 'warn' },
+ optionalSummary: { ok: 0, warn: 0, error: 0, unconfigured: 1, total: 1, overall: 'unconfigured' },
network: {
bind: { port: 5555 },
setup: {
@@ -55,5 +56,7 @@ describe('CapabilityMap setup walkthrough', () => {
expect(screen.getByText('Subscription CLI')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Optional capabilities' })).toBeInTheDocument();
expect(screen.getByText('Calendar')).toBeInTheDocument();
+ expect(screen.getByText('1 not set up')).toBeInTheDocument();
+ expect(screen.queryByText('2 degraded')).not.toBeInTheDocument();
});
});
diff --git a/scripts/setup-guide.js b/scripts/setup-guide.js
index 542fbca9e5..fc9cdec76b 100644
--- a/scripts/setup-guide.js
+++ b/scripts/setup-guide.js
@@ -7,7 +7,7 @@
* 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 { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { certPaths } from '../lib/certPaths.js';
import {
@@ -17,6 +17,7 @@ import {
import { hasTailscaleCert } from '../lib/tailscale-https.js';
import { buildNetworkSetupGuide } from '../server/lib/networkExposure.js';
import { getTailscaleStatus } from '../server/lib/tailscale.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const DATA_DIR = join(ROOT, 'data');
@@ -72,16 +73,16 @@ export function formatSetupSummary(guide) {
return next ? `${next.title} — ${next.detail}` : 'Tailscale HTTPS setup needs attention';
}
-async function detectActiveHttps() {
+async function probeHealthScheme(port) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 1500);
- const response = await fetch(`http://localhost:${MIRROR_PORT}/api/system/health`, {
+ const response = await fetch(`http://localhost:${port}/api/system/health`, {
signal: controller.signal,
}).catch(() => null);
clearTimeout(timer);
- if (!response?.ok) return false;
+ if (!response?.ok) return null;
const health = await response.json().catch(() => null);
- return health?.scheme === 'https';
+ return ['http', 'https'].includes(health?.scheme) ? health.scheme : null;
}
export async function getCliSetupGuide({ assumeActive = null } = {}) {
@@ -91,11 +92,19 @@ export async function getCliSetupGuide({ assumeActive = 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.
+ // PortOS restart; a direct invocation probes both possible live listeners so
+ // it also keeps linking to :5555 while a pre-existing HTTP process is still
+ // running with newly written certificate files on disk.
+ let liveScheme = null;
+ if (certProvisioned && assumeActive === true) {
+ liveScheme = 'https';
+ } else if (certProvisioned && assumeActive === null) {
+ liveScheme = await probeHealthScheme(MIRROR_PORT)
+ ?? await probeHealthScheme(API_PORT);
+ }
const httpsActive = certProvisioned && (assumeActive === null
- ? await detectActiveHttps()
- : assumeActive);
+ ? liveScheme === 'https'
+ : assumeActive === true);
const network = {
httpsEnabled: httpsActive,
bind: { port: API_PORT },
@@ -109,9 +118,9 @@ export async function getCliSetupGuide({ assumeActive = null } = {}) {
};
const tailscale = await getTailscaleStatus();
const guide = buildNetworkSetupGuide(network, tailscale);
- const localUrl = certProvisioned
- ? `http://localhost:${MIRROR_PORT}`
- : `http://localhost:${API_PORT}`;
+ const localUrl = liveScheme === 'http' || !certProvisioned
+ ? `http://localhost:${API_PORT}`
+ : `http://localhost:${MIRROR_PORT}`;
const browserBase = guide.trustedUrl || localUrl;
return {
...guide,
@@ -140,7 +149,6 @@ async function main() {
console.log(formatSetupGuide(guide, guide));
}
-const invokedPath = process.argv[1] ? resolve(process.argv[1]) : null;
-if (invokedPath === fileURLToPath(import.meta.url)) {
+if (isDirectlyInvoked(import.meta.url)) {
await main();
}
diff --git a/scripts/setup-guide.test.js b/scripts/setup-guide.test.js
index 9c1d0327b6..33ae66edef 100644
--- a/scripts/setup-guide.test.js
+++ b/scripts/setup-guide.test.js
@@ -1,5 +1,49 @@
-import { describe, expect, it } from 'vitest';
-import { formatSetupGuide, formatSetupSummary } from './setup-guide.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../lib/certMeta.js', async () => ({
+ ...await vi.importActual('../lib/certMeta.js'),
+ readCertMeta: vi.fn(),
+}));
+
+vi.mock('../lib/tailscale-https.js', () => ({
+ hasTailscaleCert: vi.fn(),
+}));
+
+vi.mock('../server/lib/tailscale.js', () => ({
+ getTailscaleStatus: vi.fn(),
+}));
+
+import { readCertMeta } from '../lib/certMeta.js';
+import { hasTailscaleCert } from '../lib/tailscale-https.js';
+import { getTailscaleStatus } from '../server/lib/tailscale.js';
+import {
+ formatSetupGuide,
+ formatSetupSummary,
+ getCliSetupGuide,
+} from './setup-guide.js';
+
+const readyTailscale = {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', vi.fn());
+ readCertMeta.mockReturnValue(null);
+ hasTailscaleCert.mockReturnValue(false);
+ getTailscaleStatus.mockResolvedValue({
+ available: false,
+ running: false,
+ reason: 'tailscale-not-installed',
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
const incompleteGuide = {
complete: false,
@@ -76,3 +120,58 @@ describe('setup walkthrough formatting', () => {
);
});
});
+
+describe('getCliSetupGuide', () => {
+ it('uses the trusted URL without probing when the restarted server is known active', async () => {
+ readCertMeta.mockReturnValue({
+ mode: 'tailscale',
+ hostname: 'host-alpha.example-tailnet.ts.net',
+ });
+ hasTailscaleCert.mockReturnValue(true);
+ getTailscaleStatus.mockResolvedValue(readyTailscale);
+
+ const guide = await getCliSetupGuide({ assumeActive: true });
+
+ expect(guide.complete).toBe(true);
+ expect(guide.trustedUrl).toBe('https://host-alpha.example-tailnet.ts.net:5555');
+ expect(guide.setupUrl).toBe('https://host-alpha.example-tailnet.ts.net:5555/capabilities');
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('keeps the live HTTP URL after a certificate is written before restart', async () => {
+ readCertMeta.mockReturnValue({
+ mode: 'tailscale',
+ hostname: 'host-alpha.example-tailnet.ts.net',
+ });
+ hasTailscaleCert.mockReturnValue(true);
+ getTailscaleStatus.mockResolvedValue(readyTailscale);
+ fetch
+ .mockRejectedValueOnce(new Error('mirror is not running'))
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ scheme: 'http' }),
+ });
+
+ const guide = await getCliSetupGuide();
+
+ expect(guide.complete).toBe(false);
+ expect(guide.nextStep).toMatchObject({ id: 'activate-https' });
+ expect(guide.localUrl).toBe('http://localhost:5555');
+ expect(guide.setupUrl).toBe('http://localhost:5555/capabilities');
+ expect(fetch).toHaveBeenNthCalledWith(1,
+ 'http://localhost:5553/api/system/health',
+ expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ expect(fetch).toHaveBeenNthCalledWith(2,
+ 'http://localhost:5555/api/system/health',
+ expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ });
+
+ it('uses the default HTTP URL without probing when no certificate exists', async () => {
+ const guide = await getCliSetupGuide();
+
+ expect(guide.complete).toBe(false);
+ expect(guide.localUrl).toBe('http://localhost:5555');
+ expect(guide.setupUrl).toBe('http://localhost:5555/capabilities');
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/networkExposure.js b/server/lib/networkExposure.js
index bf48c2eac4..11594a566a 100644
--- a/server/lib/networkExposure.js
+++ b/server/lib/networkExposure.js
@@ -185,17 +185,23 @@ export function buildNetworkSetupGuide(network = {}, tailscale = {}) {
setupStep(
'https-cert',
'Provision a trusted HTTPS certificate',
- certMatchesCurrentHost ? 'complete' : canProvision ? 'action' : 'blocked',
+ certMatchesCurrentHost
+ ? 'complete'
+ : canProvision || (magicDnsReady && tailscale?.sandboxed === true)
+ ? '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}.`
+ : trustedCertProvisioned && currentDnsName && provisionedHost !== currentDnsName
+ ? `The installed certificate is for ${provisionedHost}; reprovision it for ${currentDnsName}.`
+ : canProvision
+ ? 'Enable HTTPS Certificates in the Tailscale DNS admin, then let PortOS fetch the certificate automatically.'
: 'Complete the Tailscale and MagicDNS steps first.',
- tailscale?.sandboxed
+ certMatchesCurrentHost
+ ? null
+ : magicDnsReady && 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 }
diff --git a/server/lib/networkExposure.test.js b/server/lib/networkExposure.test.js
index 34d48a0d1b..242dda8f95 100644
--- a/server/lib/networkExposure.test.js
+++ b/server/lib/networkExposure.test.js
@@ -203,6 +203,45 @@ describe('networkExposure.buildNetworkSetupGuide', () => {
});
});
+ it('offers the writable CLI command when only the sandboxed macOS CLI is available', () => {
+ const guide = buildNetworkSetupGuide(baseNetwork, {
+ available: true,
+ running: true,
+ sandboxed: true,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ });
+
+ expect(guide.nextStep).toMatchObject({
+ id: 'https-cert',
+ status: 'action',
+ action: { type: 'command', command: 'brew install tailscale' },
+ });
+ });
+
+ it('names a stale certificate hostname before offering reprovisioning', () => {
+ const guide = buildNetworkSetupGuide({
+ ...baseNetwork,
+ cert: {
+ mode: null,
+ provisioned: true,
+ provisionedMode: 'tailscale',
+ provisionedHost: 'host-old.example-tailnet.ts.net',
+ },
+ }, {
+ available: true,
+ running: true,
+ sandboxed: false,
+ dnsName: 'host-alpha.example-tailnet.ts.net',
+ });
+
+ expect(guide.nextStep).toMatchObject({
+ id: 'https-cert',
+ status: 'action',
+ detail: 'The installed certificate is for host-old.example-tailnet.ts.net; reprovision it for host-alpha.example-tailnet.ts.net.',
+ action: { type: 'provision-cert' },
+ });
+ });
+
it('asks for a restart when the trusted cert exists but this process booted on HTTP', () => {
const guide = buildNetworkSetupGuide({
...baseNetwork,
diff --git a/server/lib/tailscale.js b/server/lib/tailscale.js
index 603c683912..005205124b 100644
--- a/server/lib/tailscale.js
+++ b/server/lib/tailscale.js
@@ -5,6 +5,15 @@ import { promisify } from 'util';
import { safeJSONParse } from './fileUtils.js';
const execFileAsync = promisify(execFile);
+const STATUS_CACHE_TTL_MS = 10_000;
+
+// Setup, capability, and instance surfaces can poll in the same render cycle.
+// Keep one short-lived local-daemon snapshot so they share a single CLI probe.
+// `null` deliberately means "not fetched"; a valid unavailable status object
+// is still cached instead of re-running the command on every request.
+let statusCacheValue = null;
+let statusCacheAt = 0;
+let statusInFlight = null;
const isWin = () => process.platform === 'win32';
const tailscaleBin = () => (isWin() ? 'tailscale.exe' : 'tailscale');
@@ -71,7 +80,7 @@ export function isSandboxedTailscale(binPath) {
* Never throws — execFile failures and non-JSON output degrade to a
* not-running result so callers can treat this as a plain boolean gate.
*/
-export async function getTailscaleStatus() {
+async function readTailscaleStatus() {
const bin = findTailscale();
const unavailable = (reason, { available = true } = {}) => ({
available,
@@ -119,6 +128,39 @@ export async function getTailscaleStatus() {
};
}
+export function __resetTailscaleStatusCache() {
+ statusCacheValue = null;
+ statusCacheAt = 0;
+ statusInFlight = null;
+}
+
+export async function getTailscaleStatus({ force = false } = {}) {
+ if (!force && statusCacheValue !== null && Date.now() - statusCacheAt < STATUS_CACHE_TTL_MS) {
+ return statusCacheValue;
+ }
+ if (!force && statusInFlight) return statusInFlight;
+
+ const request = readTailscaleStatus();
+ const tracked = request.then(
+ (value) => {
+ // A forced refresh may have superseded this probe. Only the newest probe
+ // publishes shared state, while existing callers still receive theirs.
+ if (statusInFlight === tracked) {
+ statusCacheValue = value;
+ statusCacheAt = Date.now();
+ statusInFlight = null;
+ }
+ return value;
+ },
+ (error) => {
+ if (statusInFlight === tracked) statusInFlight = null;
+ throw error;
+ },
+ );
+ statusInFlight = tracked;
+ return tracked;
+}
+
/**
* Convenience boolean: true only when Tailscale is installed AND connected to
* the tailnet (BackendState === 'Running').
diff --git a/server/lib/tailscale.test.js b/server/lib/tailscale.test.js
index bae25cc699..5e0484bfb7 100644
--- a/server/lib/tailscale.test.js
+++ b/server/lib/tailscale.test.js
@@ -15,6 +15,7 @@ import {
findTailscale,
isSandboxedTailscale,
hasOnlySandboxedTailscale,
+ __resetTailscaleStatusCache,
getTailscaleStatus,
isTailscaleUp,
MACOS_TAILSCALE_APP_BUNDLE
@@ -155,6 +156,7 @@ describe('getTailscaleStatus / isTailscaleUp', () => {
beforeEach(() => {
originalPath = process.env.PATH;
vi.clearAllMocks();
+ __resetTailscaleStatusCache();
// Default: a Tailscale binary exists at a known candidate path.
existsSync.mockImplementation((p) => p === INSTALLED_CANDIDATE);
});
@@ -195,6 +197,29 @@ describe('getTailscaleStatus / isTailscaleUp', () => {
expect(await isTailscaleUp()).toBe(true);
});
+ it('shares and briefly caches local status probes', async () => {
+ let finishProbe;
+ execFile.mockImplementation((cmd, args, opts, cb) => {
+ finishProbe = () => cb(null, { stdout: JSON.stringify({ BackendState: 'Running' }) });
+ });
+
+ const first = getTailscaleStatus();
+ const concurrent = getTailscaleStatus();
+ expect(execFile).toHaveBeenCalledTimes(1);
+ finishProbe();
+ await expect(Promise.all([first, concurrent])).resolves.toEqual([
+ expect.objectContaining({ running: true }),
+ expect.objectContaining({ running: true }),
+ ]);
+
+ await getTailscaleStatus();
+ expect(execFile).toHaveBeenCalledTimes(1);
+ const forced = getTailscaleStatus({ force: true });
+ expect(execFile).toHaveBeenCalledTimes(2);
+ finishProbe();
+ await forced;
+ });
+
it('normalizes the local MagicDNS name, suffix, and peer suggestions', async () => {
mockStatusJSON({
BackendState: 'Running',
diff --git a/server/routes/capabilities.js b/server/routes/capabilities.js
index a0c4b8a829..536422ec16 100644
--- a/server/routes/capabilities.js
+++ b/server/routes/capabilities.js
@@ -116,6 +116,7 @@ router.get('/', asyncHandler(async (req, res) => {
res.json({
timestamp: new Date().toISOString(),
summary: summarizeCapabilities(rows),
+ optionalSummary: summarizeCapabilities(rows.filter((row) => row.setupRequired !== true)),
setup: summarizeSetupCapabilities(rows),
capabilities: rows,
network,
diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.js
index fbb35aeed2..8598724e8c 100644
--- a/server/routes/capabilities.test.js
+++ b/server/routes/capabilities.test.js
@@ -90,6 +90,7 @@ 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.optionalSummary).toMatchObject({ overall: expect.any(String), total: 7 });
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