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: address Copilot review — broken pipe guard, stdio detach, DRY execGh, real tests
Adam Eivy5e69a7c28919
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 1e7241dcef..4372361ba4 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -119,6 +119,14 @@ export default function AppDetailView() {case 'processes':return <ProcessesTab pm2ProcessNames={app.pm2ProcessNames} />;case 'update':+ if (app.id !== api.PORTOS_APP_ID) {+ return (+ <div className="p-6 text-center">+ <p className="text-lg text-gray-400 mb-4">Update is not available for this app</p>+ <Link to={`/apps/${appId}/overview`} className="text-port-accent hover:underline">Back to Overview</Link>+ </div>+ );+ }return <UpdateTab />;default:return <OverviewTab app={app} onRefresh={fetchApp} />;diff --git a/scripts/portos-update.sh b/scripts/portos-update.shindex 3ced50355f..088b23a34f 100755--- a/scripts/portos-update.sh+++ b/scripts/portos-update.sh@@ -16,7 +16,7 @@ cd "$ROOT_DIR"# Log helperlog() {echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" >> "$LOG_FILE"- echo "$*"+ echo "$*" || true}# Step output helperdiff --git a/scripts/run-migrations.js b/scripts/run-migrations.jsindex 7423e7f0d7..416edd37b1 100644--- a/scripts/run-migrations.js+++ b/scripts/run-migrations.js@@ -2,7 +2,7 @@import { readdir, readFile, writeFile, mkdir } from 'fs/promises';import { existsSync } from 'fs';import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { fileURLToPath, pathToFileURL } from 'url';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');@@ -31,7 +31,7 @@ async function run() {if (applied.includes(file)) continue;console.log(`🔄 Running migration: ${file}`);- const migration = await import(join(migrationsDir, file));+ const migration = await import(pathToFileURL(join(migrationsDir, file)).href);await migration.up({ rootDir, migrationsDir });applied.push(file);await writeFile(appliedFile, JSON.stringify(applied, null, 2) + '\n');diff --git a/server/index.js b/server/index.jsindex bfe530299e..cced4dac99 100644--- a/server/index.js+++ b/server/index.js@@ -5,6 +5,7 @@ import { Server } from 'socket.io';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { existsSync } from 'fs';+import { readFile, unlink } from 'fs/promises';import appleHealthRoutes from './routes/appleHealth.js';import systemHealthRoutes from './routes/systemHealth.js';@@ -252,7 +253,6 @@ initBrainMemoryBridge();// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));// Check for update completion marker from a previous update cycle-import { readFile, unlink } from 'fs/promises';const updateMarkerPath = join(__dirname, '..', 'data', 'update-complete.json');readFile(updateMarkerPath, 'utf-8').then(raw => {const marker = JSON.parse(raw);diff --git a/server/services/github.js b/server/services/github.jsindex ddb90a2a5e..613b2192ec 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -39,7 +39,7 @@ async function save(data) {/*** Execute a gh CLI command safely using spawn*/-function execGh(args) {+export function execGh(args) {return new Promise((resolve, reject) => {const child = spawn('gh', args, { shell: false, windowsHide: true });let stdout = '';diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex 117b9820c3..affadd4fa7 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -1,9 +1,9 @@-import { spawn } from 'child_process';import { writeFile } from 'fs/promises';import { join } from 'path';import { EventEmitter } from 'events';import { readJSONFile, PATHS, ensureDir } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';+import { execGh } from './github.js';const UPDATE_FILE = join(PATHS.data, 'update.json');const CHECK_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes@@ -24,24 +24,6 @@ const defaultState = () => ({lastUpdateResult: null});-function execGh(args) {- return new Promise((resolve, reject) => {- const child = spawn('gh', args, { shell: false, windowsHide: true });- let stdout = '';- let stderr = '';- child.stdout.on('data', (d) => { stdout += d.toString(); });- child.stderr.on('data', (d) => { stderr += d.toString(); });- child.on('close', (code) => {- if (code !== 0) {- reject(new Error(stderr.trim() || `gh exited with code ${code}`));- } else {- resolve(stdout.trim());- }- });- child.on('error', (err) => reject(err));- });-}-/*** Read the current version from the root package.json.* Re-reads on each call so it picks up changes after updates.@@ -56,7 +38,7 @@ export async function getCurrentVersion() {* Compare two semver strings. Returns:* -1 if a < b, 0 if equal, 1 if a > b*/-function compareSemver(a, b) {+export function compareSemver(a, b) {const pa = a.split('.').map(Number);const pb = b.split('.').map(Number);for (let i = 0; i < 3; i++) {diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.jsindex bebc955049..c853fecd24 100644--- a/server/services/updateChecker.test.js+++ b/server/services/updateChecker.test.js@@ -1,37 +1,39 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-// Inline copy of compareSemver for testing without importing private function-function compareSemver(a, b) {- const pa = a.split('.').map(Number);- const pb = b.split('.').map(Number);- for (let i = 0; i < 3; i++) {- const na = pa[i] || 0;- const nb = pb[i] || 0;- if (na < nb) return -1;- if (na > nb) return 1;- }- return 0;-}-// Mock dependencies before importing the modulevi.mock('fs/promises', () => ({- readFile: vi.fn(),- writeFile: vi.fn(),- mkdir: vi.fn()+ writeFile: vi.fn().mockResolvedValue(undefined)}));-vi.mock('child_process', () => ({- spawn: vi.fn()+vi.mock('../lib/fileUtils.js', () => ({+ readJSONFile: vi.fn(),+ PATHS: {+ root: '/mock',+ data: '/mock/data'+ },+ ensureDir: vi.fn().mockResolvedValue(undefined)}));-import { readFile, writeFile, mkdir } from 'fs/promises';-import { spawn } from 'child_process';+vi.mock('../lib/asyncMutex.js', () => ({+ createMutex: () => (fn) => fn()+}));-// Mock the EventEmitter used internally-vi.mock('events', async () => {- const actual = await vi.importActual('events');- return actual;-});+vi.mock('./github.js', () => ({+ execGh: vi.fn()+}));++import { writeFile } from 'fs/promises';+import { readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { execGh } from './github.js';+import {+ compareSemver,+ getCurrentVersion,+ getUpdateStatus,+ ignoreVersion,+ clearIgnored,+ checkForUpdate,+ updateEvents+} from './updateChecker.js';describe('compareSemver', () => {it('should return 0 for equal versions', () => {@@ -59,93 +61,267 @@ describe('compareSemver', () => {});});-describe('updateChecker integration', () => {- const defaultState = {- lastCheck: null,- latestRelease: null,- ignoredVersions: [],- updateInProgress: false,- lastUpdateResult: null- };+describe('getCurrentVersion', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should read version from root package.json', async () => {+ readJSONFile.mockResolvedValue({ version: '1.26.0' });+ const version = await getCurrentVersion();+ expect(version).toBe('1.26.0');+ expect(readJSONFile).toHaveBeenCalledWith('/mock/package.json', { version: '0.0.0' });+ });++ it('should fall back to 0.0.0 when package.json missing', async () => {+ readJSONFile.mockResolvedValue({ version: '0.0.0' });+ const version = await getCurrentVersion();+ expect(version).toBe('0.0.0');+ });+});+describe('getUpdateStatus', () => {beforeEach(() => {vi.clearAllMocks();- mkdir.mockResolvedValue(undefined);- writeFile.mockResolvedValue(undefined);});- afterEach(() => {- vi.restoreAllMocks();+ it('should report no update when latestRelease is null', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.updateAvailable).toBe(false);+ expect(status.currentVersion).toBe('1.26.0');});it('should detect update available when remote version is newer', async () => {- // This tests the logic flow: if latestRelease.version > currentVersion and not ignored- const currentVersion = '1.26.0';- const latestVersion = '1.27.0';- const isNewer = compareSemver(latestVersion, currentVersion) > 0;- const ignoredVersions = [];- const isIgnored = ignoredVersions.includes(latestVersion);+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: '2024-01-01T00:00:00Z',+ latestRelease: { version: '1.27.0' },+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });- expect(isNewer).toBe(true);- expect(isIgnored).toBe(false);- expect(isNewer && !isIgnored).toBe(true);+ const status = await getUpdateStatus();+ expect(status.updateAvailable).toBe(true);});- it('should not detect update when versions are equal', () => {- const currentVersion = '1.26.0';- const latestVersion = '1.26.0';- const isNewer = compareSemver(latestVersion, currentVersion) > 0;+ it('should not detect update when versions are equal', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: '2024-01-01T00:00:00Z',+ latestRelease: { version: '1.26.0' },+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });- expect(isNewer).toBe(false);+ const status = await getUpdateStatus();+ expect(status.updateAvailable).toBe(false);});- it('should respect ignored versions', () => {- const currentVersion = '1.26.0';- const latestVersion = '1.27.0';- const ignoredVersions = ['1.27.0'];- const isNewer = compareSemver(latestVersion, currentVersion) > 0;- const isIgnored = ignoredVersions.includes(latestVersion);+ it('should respect ignored versions', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: '2024-01-01T00:00:00Z',+ latestRelease: { version: '1.27.0' },+ ignoredVersions: ['1.27.0'],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });- expect(isNewer).toBe(true);- expect(isIgnored).toBe(true);- expect(isNewer && !isIgnored).toBe(false);+ const status = await getUpdateStatus();+ expect(status.updateAvailable).toBe(false);});- it('should handle downgrade (remote older than current)', () => {- const currentVersion = '1.27.0';- const latestVersion = '1.26.0';- const isNewer = compareSemver(latestVersion, currentVersion) > 0;+ it('should handle downgrade (remote older than current)', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: '2024-01-01T00:00:00Z',+ latestRelease: { version: '1.26.0' },+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.27.0' });- expect(isNewer).toBe(false);+ const status = await getUpdateStatus();+ expect(status.updateAvailable).toBe(false);});+});- it('should correctly add version to ignore list', () => {- const state = { ...defaultState, ignoredVersions: [] };- const version = '1.27.0';+describe('ignoreVersion', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockResolvedValue(undefined);+ ensureDir.mockResolvedValue(undefined);+ });- if (!state.ignoredVersions.includes(version)) {- state.ignoredVersions.push(version);- }+ it('should add version to ignore list', async () => {+ readJSONFile.mockResolvedValue({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ });+ const state = await ignoreVersion('1.27.0');expect(state.ignoredVersions).toContain('1.27.0');- expect(state.ignoredVersions).toHaveLength(1);+ expect(writeFile).toHaveBeenCalled();});- it('should not duplicate ignored versions', () => {- const state = { ...defaultState, ignoredVersions: ['1.27.0'] };- const version = '1.27.0';-- if (!state.ignoredVersions.includes(version)) {- state.ignoredVersions.push(version);- }+ it('should not duplicate ignored versions', async () => {+ readJSONFile.mockResolvedValue({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: ['1.27.0'],+ updateInProgress: false,+ lastUpdateResult: null+ });+ const state = await ignoreVersion('1.27.0');expect(state.ignoredVersions).toHaveLength(1);+ expect(writeFile).not.toHaveBeenCalled();+ });+});++describe('clearIgnored', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockResolvedValue(undefined);+ ensureDir.mockResolvedValue(undefined);});- it('should clear all ignored versions', () => {- const state = { ...defaultState, ignoredVersions: ['1.27.0', '1.28.0'] };- state.ignoredVersions = [];+ it('should clear all ignored versions', async () => {+ readJSONFile.mockResolvedValue({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: ['1.27.0', '1.28.0'],+ updateInProgress: false,+ lastUpdateResult: null+ });+ const state = await clearIgnored();expect(state.ignoredVersions).toHaveLength(0);+ expect(writeFile).toHaveBeenCalled();+ });+});++describe('checkForUpdate', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockResolvedValue(undefined);+ ensureDir.mockResolvedValue(undefined);+ });++ it('should detect update when remote version is newer', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ execGh.mockResolvedValue(JSON.stringify({+ tag_name: 'v1.27.0',+ html_url: 'https://github.com/atomantic/PortOS/releases/tag/v1.27.0',+ published_at: '2024-01-15T00:00:00Z',+ body: 'Release notes'+ }));++ const result = await checkForUpdate();+ expect(result.updateAvailable).toBe(true);+ expect(result.currentVersion).toBe('1.26.0');+ expect(result.latestRelease.version).toBe('1.27.0');+ });++ it('should not detect update when versions match', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.27.0' });++ execGh.mockResolvedValue(JSON.stringify({+ tag_name: 'v1.27.0',+ html_url: 'https://github.com/atomantic/PortOS/releases/tag/v1.27.0',+ published_at: '2024-01-15T00:00:00Z',+ body: 'Release notes'+ }));++ const result = await checkForUpdate();+ expect(result.updateAvailable).toBe(false);+ });++ it('should emit update:available event when newer version found', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ execGh.mockResolvedValue(JSON.stringify({+ tag_name: 'v1.27.0',+ html_url: 'https://github.com/atomantic/PortOS/releases/tag/v1.27.0',+ published_at: '2024-01-15T00:00:00Z',+ body: 'Release notes'+ }));++ const handler = vi.fn();+ updateEvents.on('update:available', handler);++ await checkForUpdate();+ expect(handler).toHaveBeenCalledWith(expect.objectContaining({+ currentVersion: '1.26.0',+ latestVersion: '1.27.0'+ }));++ updateEvents.removeListener('update:available', handler);+ });++ it('should strip v prefix from tag_name', async () => {+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ execGh.mockResolvedValue(JSON.stringify({+ tag_name: 'v2.0.0',+ html_url: '',+ published_at: '',+ body: ''+ }));++ const result = await checkForUpdate();+ expect(result.latestRelease.version).toBe('2.0.0');});});diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex e6caaec775..9e681b0b61 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -14,46 +14,24 @@ const SCRIPT_PATH = join(PATHS.root, 'scripts', 'portos-update.sh');* @returns {Promise<{success: boolean}>}*/export async function executeUpdate(tag, emit) {+ if (process.platform === 'win32') {+ const msg = 'Auto-update execution is not supported on Windows — the update script requires bash';+ emit('starting', 'error', msg);+ return { success: false, error: msg };+ }+await setUpdateInProgress(true);emit('starting', 'running', `Starting update to ${tag}...`);return new Promise((resolve) => {const child = spawn('bash', [SCRIPT_PATH, tag], {detached: true,- stdio: ['ignore', 'pipe', 'pipe'],+ stdio: 'ignore',cwd: PATHS.root});let lastStep = 'starting';- child.stdout.on('data', (data) => {- const lines = data.toString().split('\n');- for (const line of lines) {- const trimmed = line.trim();- if (!trimmed) continue;-- // Parse structured STEP markers: STEP:name:status:message- const match = trimmed.match(/^STEP:([^:]+):([^:]+):(.*)$/);- if (match) {- const [, step, status, message] = match;- lastStep = step;- emit(step, status, message);-- // When the script signals it's about to restart, notify client- if (step === 'restart' && status === 'running') {- emit('restarting', 'running', `Restarting PortOS with ${tag}...`);- }- }- }- });-- child.stderr.on('data', (data) => {- const msg = data.toString().trim();- if (msg) {- console.error(`📦 Update stderr: ${msg}`);- }- });-child.on('close', (code) => {const success = code === 0;recordUpdateResult({