Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: reopen managed updates on the trusted origin
[._.]/ Adam Eivy4fc3f2a1c9f3
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsxindex 772f4e4613..97622d45f9 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx@@ -214,13 +214,16 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refresetUpdateIntent(null);setUpdating(true);+ const targetOrigin = appId === api.PORTOS_APP_ID && status?.updateRestartsApp+ ? await api.getPreferredSelfRestartOrigin()+ : null;const result = await api.pullAndUpdateApp(appId,{ syncFork: intent?.syncFork === true },{ silent: true },).catch((reason) => {if (appId === api.PORTOS_APP_ID && status?.updateRestartsApp && !reason?.status) {- api.handleSelfRestart();+ api.handleSelfRestart({ targetOrigin });return { selfRestartTriggered: true };}toast.error(reason.message || `Could not update ${appName || 'the app'}`);diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsxindex 00cbf5f2ed..e5d84b4e3e 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx@@ -6,6 +6,7 @@ vi.mock('../../../services/api', () => ({getAppRepositorySources: vi.fn(),syncAppRepositoryFork: vi.fn(),pullAndUpdateApp: vi.fn(),+ getPreferredSelfRestartOrigin: vi.fn(),handleSelfRestart: vi.fn(),}));@@ -189,13 +190,16 @@ describe('managed app repository sources', () => {});it('treats a PortOS update disconnect as the expected self-restart', async () => {+ api.getPreferredSelfRestartOrigin.mockResolvedValueOnce('https://host-alpha.example-tailnet.ts.net:5555');api.pullAndUpdateApp.mockRejectedValueOnce(new Error('Server unreachable — check your connection and try again'));render(<RepositorySourcePanel appId="portos-default" appName="PortOS" />);fireEvent.click(await screen.findByRole('button', { name: 'Update app' }));fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Update app' }));- await waitFor(() => expect(api.handleSelfRestart).toHaveBeenCalledOnce());+ await waitFor(() => expect(api.handleSelfRestart).toHaveBeenCalledWith({+ targetOrigin: 'https://host-alpha.example-tailnet.ts.net:5555',+ }));});it('refuses automatic fork sync after divergence but still permits updating from the fork as-is', async () => {diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex c435f628a5..a81eecf5d7 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -1,5 +1,6 @@import toast from '../components/ui/Toast';import { request, API_BASE } from './apiCore.js';+import { getNetworkExposure } from './apiSystem.js';// Appsexport const getApps = (options) => request('/apps', options);@@ -152,6 +153,17 @@ export const openAppFolder = (id) => request(`/apps/${id}/open-folder`, { method// comes back as a real error instead of a silent `xcode://` no-op.export const openAppInXcode = (id) => request(`/apps/${id}/open-xcode`, { method: 'POST' });export const refreshAppConfig = (id) => request(`/apps/${id}/refresh-config`, { method: 'POST' });+// Capture the server's currently trusted origin before a PortOS restart. A+// Vite dev UI on :5554 must not be reused after the server comes back when a+// Tailscale HTTPS origin is available. The read is best-effort so an instance+// without trusted HTTPS keeps the existing same-origin recovery behavior.+export const getPreferredSelfRestartOrigin = async () => {+ const exposure = await getNetworkExposure({ silent: true }).catch(() => null);+ const trustedUrl = exposure?.setup?.trustedUrl;+ return typeof trustedUrl === 'string' && trustedUrl.startsWith('https://')+ ? trustedUrl+ : null;+};export const pullAndUpdateApp = (id, body = {}, options = {}) => request(`/apps/${id}/update`, {method: 'POST',body: JSON.stringify(body),diff --git a/client/src/services/apiApps.test.js b/client/src/services/apiApps.test.jsindex defd77b68f..a3f970782b 100644--- a/client/src/services/apiApps.test.js+++ b/client/src/services/apiApps.test.js@@ -4,12 +4,16 @@ vi.mock('../components/ui/Toast', () => ({default: { loading: vi.fn(), success: vi.fn(), error: vi.fn() },}));+const mockNetwork = vi.hoisted(() => ({ getNetworkExposure: vi.fn() }));+vi.mock('./apiSystem.js', () => mockNetwork);+import toast from '../components/ui/Toast';-import { handleSelfRestart } from './apiApps';+import { getPreferredSelfRestartOrigin, handleSelfRestart } from './apiApps';beforeEach(() => {vi.useFakeTimers();vi.clearAllMocks();+ mockNetwork.getNetworkExposure.mockResolvedValue({ setup: { trustedUrl: null } });});afterEach(() => {@@ -54,3 +58,24 @@ describe('handleSelfRestart', () => {);});});++describe('getPreferredSelfRestartOrigin', () => {+ it('returns the active trusted origin supplied by network exposure', async () => {+ mockNetwork.getNetworkExposure.mockResolvedValueOnce({+ setup: { trustedUrl: 'https://host-alpha.example-tailnet.ts.net:5555' },+ });++ await expect(getPreferredSelfRestartOrigin()).resolves.toBe(+ 'https://host-alpha.example-tailnet.ts.net:5555',+ );+ expect(mockNetwork.getNetworkExposure).toHaveBeenCalledWith({ silent: true });+ });++ it('does not turn an unavailable or non-HTTPS setup value into a restart target', async () => {+ mockNetwork.getNetworkExposure.mockResolvedValueOnce({+ setup: { pendingTrustedUrl: 'https://host-alpha.example-tailnet.ts.net:5555', trustedUrl: null },+ });++ await expect(getPreferredSelfRestartOrigin()).resolves.toBeNull();+ });+});diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex dba19758ed..ccc854d265 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -1,10 +1,13 @@import { existsSync } from 'fs';import { join } from 'path';import { readFile } from 'fs/promises';+import { tmpdir } from 'os';import * as gitService from './git.js';import * as pm2Service from './pm2.js';import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';import { parseCommandArgs } from '../lib/commandSecurity.js';+import { isDetachedRunning, spawnDetached } from '../lib/detachedSpawn.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { syncManagedAppFork } from './managedAppRepositories.js';const CMD_TIMEOUT_MS = 5 * 60 * 1000;@@ -20,6 +23,46 @@ function runCommand(cmd, args, cwd) {// Per-app lock to prevent concurrent updatesconst updatingApps = new Set();+const DASHBOARD_OPEN_SCRIPT = 'scripts/open-ui-in-browser.js';+const DASHBOARD_OPEN_CONTROL_DIR = join(tmpdir(), 'portos-dashboard-open');++/**+ * Start the post-update dashboard handoff before any PortOS process is+ * restarted. The handoff is deliberately detached through the shared+ * double-fork helper: PM2's tree-kill would otherwise take the helper down+ * with portos-server before it can wait for the browser to return.+ *+ * @param {object} app+ * @returns {Promise<void>}+ */+async function startDashboardHandoff(app) {+ if (app.id !== PORTOS_APP_ID) return;++ const scriptPath = join(app.repoPath, DASHBOARD_OPEN_SCRIPT);+ const alreadyRunning = await isDetachedRunning(DASHBOARD_OPEN_CONTROL_DIR, {+ executable: process.execPath,+ args: [scriptPath],+ }).catch((err) => {+ // Do not let an unreadable control dir be mistaken for an idle one: the+ // detached helper clears stale sentinels before launching and could then+ // race a handoff that is still alive after the previous PM2 restart.+ console.error(`⚠️ Dashboard auto-open status check failed: ${err.message}`);+ return true;+ });+ if (alreadyRunning) return;++ const handoff = await spawnDetached(+ process.execPath,+ [scriptPath],+ { cwd: app.repoPath, controlDir: DASHBOARD_OPEN_CONTROL_DIR, cleanup: true },+ ).catch((err) => {+ console.error(`⚠️ Dashboard auto-open could not start: ${err.message}`);+ return null;+ });+ handoff?.on('error', (err) => {+ console.error(`⚠️ Dashboard auto-open failed: ${err.message}`);+ });+}/*** Run a full update cycle for an app:@@ -113,6 +156,7 @@ async function _doUpdate(app, emit, { syncFork }) {const processNames = app.pm2ProcessNames || [];if (processNames.length > 0) {emit('restart', 'running', 'Restarting app...');+ await startDashboardHandoff(app);const restartResults = await Promise.all(processNames.map(name =>pm2Service.restartApp(name, app.pm2Home).then(() => null, e => e)diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.jsindex 85df92f973..ba744df67e 100644--- a/server/services/appUpdater.test.js+++ b/server/services/appUpdater.test.js@@ -6,6 +6,9 @@ import { tmpdir } from 'os';const mock = vi.hoisted(() => ({pull: vi.fn(),spawn: vi.fn(),+ dashboardOpen: vi.fn(),+ dashboardRunning: vi.fn(),+ dashboardHandle: { on: vi.fn() },restart: vi.fn(),syncFork: vi.fn(),}));@@ -13,6 +16,10 @@ const mock = vi.hoisted(() => ({vi.mock('./git.js', () => ({ pull: mock.pull }));vi.mock('./pm2.js', () => ({ restartApp: mock.restart }));vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawnOrThrow: mock.spawn }));+vi.mock('../lib/detachedSpawn.js', () => ({+ isDetachedRunning: mock.dashboardRunning,+ spawnDetached: mock.dashboardOpen,+}));vi.mock('./managedAppRepositories.js', () => ({ syncManagedAppFork: mock.syncFork }));import { updateApp } from './appUpdater.js';@@ -28,6 +35,8 @@ describe('managed app updates', () => {await writeFile(join(repo, 'client', 'package.json'), JSON.stringify({}));mock.pull.mockResolvedValue({ output: 'Already up to date' });mock.spawn.mockResolvedValue({ stdout: '', stderr: '' });+ mock.dashboardRunning.mockResolvedValue(false);+ mock.dashboardOpen.mockResolvedValue(mock.dashboardHandle);mock.restart.mockResolvedValue({ success: true });mock.syncFork.mockResolvedValue({alreadyUpToDate: false,@@ -37,6 +46,10 @@ describe('managed app updates', () => {});afterEach(async () => {+ await Promise.all(mock.dashboardOpen.mock.calls+ .map(([, , options]) => options?.controlDir)+ .filter(Boolean)+ .map((controlDir) => rm(controlDir, { recursive: true, force: true })));await rm(repo, { recursive: true, force: true });});@@ -78,4 +91,52 @@ describe('managed app updates', () => {'Synced example-owner/example-app from example-org/example-app',);});++ it('starts the trusted dashboard handoff before restarting PortOS', async () => {+ const emit = vi.fn();+ const managed = {+ id: 'portos-default',+ name: 'PortOS',+ type: 'express',+ repoPath: repo,+ pm2ProcessNames: ['portos-server', 'portos-browser'],+ };++ await updateApp(managed, emit);++ expect(mock.dashboardOpen).toHaveBeenCalledWith(+ process.execPath,+ [join(repo, 'scripts/open-ui-in-browser.js')],+ expect.objectContaining({+ cwd: repo,+ cleanup: true,+ controlDir: expect.stringContaining('portos-dashboard-open'),+ }),+ );+ expect(mock.dashboardRunning).toHaveBeenCalledWith(+ expect.stringContaining('portos-dashboard-open'),+ {+ executable: process.execPath,+ args: [join(repo, 'scripts/open-ui-in-browser.js')],+ },+ );+ expect(mock.dashboardOpen.mock.invocationCallOrder[0]).toBeLessThan(mock.restart.mock.invocationCallOrder[0]);+ });++ it('does not overwrite an unreadable dashboard handoff control dir', async () => {+ const emit = vi.fn();+ mock.dashboardRunning.mockRejectedValueOnce(new Error('control dir unavailable'));+ const managed = {+ id: 'portos-default',+ name: 'PortOS',+ type: 'express',+ repoPath: repo,+ pm2ProcessNames: ['portos-server'],+ };++ await updateApp(managed, emit);++ expect(mock.dashboardOpen).not.toHaveBeenCalled();+ expect(mock.restart).toHaveBeenCalledWith('portos-server', undefined);+ });});