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: use update.sh for auto-updates instead of portos-update.sh (#124)

[._.]/ Adam Eivycb25ceb01feb
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index c4b837a3be..aed8113a63 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -8,8 +8,8 @@ import socket from '../../../services/socket';
const STEP_LABELS = {
starting: 'Starting update',
- 'git-fetch': 'Fetching tags',
- 'git-checkout': 'Checking out release',
+ 'git-pull': 'Pulling latest changes',
+ 'pm2-stop': 'Stopping apps',
'npm-install': 'Installing dependencies',
migrations: 'Running migrations',
build: 'Building client',
@@ -68,10 +68,13 @@ export default function UpdateTab() {
}
};
- const handleComplete = ({ success, newVersion }) => {
+ const handleComplete = ({ success, newVersion, versionKnown }) => {
setUpdating(false);
if (success) {
- targetVersionRef.current = newVersion;
+ // Use server-reported actual version when available; fall back to target
+ if (versionKnown && newVersion) {
+ targetVersionRef.current = newVersion;
+ }
setPolling(true);
toast.loading('PortOS is restarting...', { id: 'portos-update-restart', duration: Infinity });
}
@@ -108,10 +111,14 @@ export default function UpdateTab() {
const ok = await api.checkHealth()
.catch(() => null);
- if (ok?.version === targetVersionRef.current) {
+ // Accept either an exact target match or any version different from
+ // the pre-update version (git pull may land on a newer version than
+ // the release tag that triggered the update)
+ const preUpdateVersion = status?.currentVersion;
+ if (ok?.version && (ok.version === targetVersionRef.current || (preUpdateVersion && ok.version !== preUpdateVersion))) {
clearInterval(pollRef.current);
setPolling(false);
- toast.success(`Updated to v${targetVersionRef.current}`, { id: 'portos-update-restart' });
+ toast.success(`Updated to v${ok.version}`, { id: 'portos-update-restart' });
setTimeout(() => window.location.reload(), 1000);
return;
}
diff --git a/scripts/portos-update.sh b/scripts/portos-update.sh
deleted file mode 100755
index 52f76c519f..0000000000
--- a/scripts/portos-update.sh
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-# Ignore SIGPIPE: when PM2 restarts the server mid-update (watch detects
-# git-checkout file changes), the parent Node process dies and our stdout
-# pipe breaks. Without this trap, SIGPIPE kills the script before
-# `|| true` can fire, leaving the update incomplete.
-trap '' PIPE
-
-# PortOS Auto-Update Script
-# Usage: bash scripts/portos-update.sh <tag>
-# Outputs structured STEP markers for progress tracking:
-# STEP:name:status:message
-
-TAG="${1:?Usage: portos-update.sh <tag>}"
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
-mkdir -p "$ROOT_DIR/data"
-LOG_FILE="$ROOT_DIR/data/update.log"
-
-cd "$ROOT_DIR"
-
-# Log helper
-log() {
- echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" >> "$LOG_FILE"
- echo "$*" || true
-}
-
-# Step output helper
-step() {
- local name="$1" status="$2" message="$3"
- log "STEP:$name:$status:$message"
-}
-
-log "=== PortOS update to $TAG started ==="
-
-# Step 1: Git fetch
-step "git-fetch" "running" "Fetching tags from origin..."
-git fetch origin --tags >> "$LOG_FILE" 2>&1
-step "git-fetch" "done" "Tags fetched"
-
-# Step 2: Git checkout
-step "git-checkout" "running" "Checking out $TAG..."
-git checkout "$TAG" >> "$LOG_FILE" 2>&1
-step "git-checkout" "done" "Checked out $TAG"
-
-# Step 3: npm install (root + client + server + setup)
-step "npm-install" "running" "Installing all dependencies..."
-npm run install:all >> "$LOG_FILE" 2>&1
-step "npm-install" "done" "Dependencies installed"
-
-# Step 4: Migrations
-step "migrations" "running" "Running data migrations..."
-if [ -f "$ROOT_DIR/scripts/run-migrations.js" ]; then
- node "$ROOT_DIR/scripts/run-migrations.js" >> "$LOG_FILE" 2>&1
-fi
-step "migrations" "done" "Migrations complete"
-
-# Step 5: Build client
-step "build" "running" "Building client..."
-npm run build --prefix client >> "$LOG_FILE" 2>&1
-step "build" "done" "Client built"
-
-# Step 6: Restart via PM2
-step "restart" "running" "Restarting PortOS..."
-
-log "=== PortOS update to $TAG restarting ==="
-
-# Write completion marker atomically before restart so server reads it on boot
-echo "{\"version\":\"${TAG#v}\",\"completedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" > "$ROOT_DIR/data/update-complete.json.tmp"
-mv "$ROOT_DIR/data/update-complete.json.tmp" "$ROOT_DIR/data/update-complete.json"
-
-# Use the local pm2 binary to restart
-node "$ROOT_DIR/node_modules/pm2/bin/pm2" restart ecosystem.config.cjs >> "$LOG_FILE" 2>&1
-
-step "restart" "done" "PortOS restarted"
diff --git a/server/routes/update.js b/server/routes/update.js
index 3a8f308528..f6eaf60d01 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -52,11 +52,6 @@ router.post('/execute', asyncHandler(async (req, res) => {
throw new ServerError('Invalid release tag format', { status: 400, code: 'INVALID_TAG' });
}
- // Reject unsupported platforms before locking, so the flag isn't left stuck
- if (process.platform === 'win32') {
- throw new ServerError('Auto-update is not supported on Windows', { status: 400, code: 'UNSUPPORTED_PLATFORM' });
- }
-
// Atomic check-and-set: rejects if already in progress, preventing concurrent updates
const acquired = await updateChecker.setUpdateInProgress(true);
if (!acquired) {
@@ -73,15 +68,17 @@ router.post('/execute', asyncHandler(async (req, res) => {
};
// Don't await — respond immediately, progress streams via socket.
- // The update script emits STEP:restart:running when it reaches the PM2
- // restart phase, which triggers the client's health polling.
+ // The update script runs `git pull --rebase` to get the latest code,
+ // so the actual post-update version may differ from `tag` if new commits
+ // landed after the release. The script writes the true version to
+ // data/update-complete.json, which the server reads on boot.
executeUpdate(tag, emit).then(result => {
// Note: this .then() may never fire if the update script's PM2 restart
// kills this server process first. The client handles this by polling
// /api/system/health after receiving the 'restart' step.
if (io) {
if (result.success) {
- io.emit('portos:update:complete', { success: true, newVersion: tag.replace(/^v/, '') });
+ io.emit('portos:update:complete', { success: true, newVersion: result.version || tag.replace(/^v/, ''), versionKnown: !!result.version });
} else {
io.emit('portos:update:error', { message: result.errorMessage ?? 'Update failed', step: result.failedStep ?? 'unknown' });
}
diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.js
index c2bd50ff15..09530a9c54 100644
--- a/server/services/updateExecutor.js
+++ b/server/services/updateExecutor.js
@@ -1,31 +1,37 @@
import { spawn } from 'child_process';
+import { readFile, unlink } from 'fs/promises';
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { recordUpdateResult } from './updateChecker.js';
-const SCRIPT_PATH = join(PATHS.root, 'scripts', 'portos-update.sh');
+const UPDATE_SH = join(PATHS.root, 'update.sh');
+const UPDATE_PS1 = join(PATHS.root, 'update.ps1');
/**
- * Execute the PortOS update script for a given release tag.
- * Spawns the script detached so it survives the Node process dying.
+ * Execute the PortOS update script (git pull to latest).
+ * Spawns update.sh (or update.ps1 on Windows) detached so it survives
+ * the Node process dying during the PM2 restart phase.
*
- * @param {string} tag - The git tag to update to (e.g. "v1.27.0")
+ * The scripts pull the latest code via `git pull --rebase --autostash` and
+ * write the actual resulting version to `data/update-complete.json`.
+ * The `tag` parameter is used only for logging and the initial API response;
+ * the true post-update version is determined by the script from package.json.
+ *
+ * @param {string} tag - The release tag that triggered the update (for logging)
* @param {function} emit - Callback (step, status, message) for progress
- * @returns {Promise<{success: boolean, failedStep?: string, errorMessage?: string}>}
+ * @returns {Promise<{success: boolean, version?: string, failedStep?: string, errorMessage?: string}>}
*/
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, failedStep: 'starting', errorMessage: msg };
- }
+ const isWindows = process.platform === 'win32';
+ const cmd = isWindows ? 'powershell' : 'bash';
+ const args = isWindows
+ ? ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', UPDATE_PS1]
+ : [UPDATE_SH];
- // The route sets updateInProgress synchronously before calling us,
- // so skip the redundant write here (it's already true)
- emit('starting', 'running', `Starting update to ${tag}...`);
+ emit('starting', 'running', `Starting update (target: ${tag})...`);
return new Promise((resolve) => {
- const child = spawn('bash', [SCRIPT_PATH, tag], {
+ const child = spawn(cmd, args, {
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
cwd: PATHS.root
@@ -40,7 +46,7 @@ export async function executeUpdate(tag, emit) {
buffer += data.toString();
let newlineIdx;
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
- const line = buffer.slice(0, newlineIdx);
+ const line = buffer.slice(0, newlineIdx).replace(/\r$/, '');
buffer = buffer.slice(newlineIdx + 1);
const match = line.match(/STEP:([^:]+):([^:]+):(.+)/);
if (match) {
@@ -66,21 +72,44 @@ export async function executeUpdate(tag, emit) {
child.on('close', async (code, signal) => {
const success = code === 0;
const exitDetail = signal ? `killed by ${signal}` : `exit code ${code}`;
- await recordUpdateResult({
- version: tag.replace(/^v/, ''),
- success,
- completedAt: new Date().toISOString(),
- log: success ? '' : `Process ${exitDetail}`
- }).catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
+ // Record result for both success and failure so updateInProgress gets
+ // cleared even if PM2 restart doesn't kill this process.
+ if (!success) {
+ await recordUpdateResult({
+ version: tag.replace(/^v/, ''),
+ success: false,
+ completedAt: new Date().toISOString(),
+ log: `Process ${exitDetail}`
+ }).catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
+ }
if (success) {
- emit('complete', 'done', `Update to ${tag} complete`);
+ // Read the actual version from the completion marker written by the script.
+ // Always record a success result so updateInProgress gets cleared even if
+ // PM2 restart doesn't kill this process. Falls back to the triggering tag
+ // when the marker isn't readable yet.
+ let actualVersion = tag.replace(/^v/, '');
+ let completedAt = new Date().toISOString();
+ const markerPath = join(PATHS.data, 'update-complete.json');
+ try {
+ const marker = JSON.parse(await readFile(markerPath, 'utf-8'));
+ actualVersion = marker.version || actualVersion;
+ completedAt = marker.completedAt || completedAt;
+ } catch { /* marker may not be readable yet — fall back to triggering tag */ }
+ await recordUpdateResult({
+ version: actualVersion,
+ success: true,
+ completedAt,
+ log: ''
+ }).catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
+ // Remove marker only after result is persisted so boot-time processing
+ // can still recover if this process is killed before recordUpdateResult
+ await unlink(join(PATHS.data, 'update-complete.json')).catch(() => {});
+ emit('complete', 'done', 'Update complete — restarting');
+ resolve({ success: true, version: actualVersion });
} else {
emit(lastStep, 'error', `Update failed at step "${lastStep}" (${exitDetail})`);
+ resolve({ success: false, failedStep: lastStep, errorMessage: `Update failed at step "${lastStep}" (${exitDetail})` });
}
- resolve(success
- ? { success: true }
- : { success: false, failedStep: lastStep, errorMessage: `Update failed at step "${lastStep}" (${exitDetail})` }
- );
});
child.on('error', async (err) => {
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index a7b6807b6b..967e9df2a2 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -6,7 +6,12 @@ vi.mock('child_process', () => ({
}));
vi.mock('../lib/fileUtils.js', () => ({
- PATHS: { root: '/mock' }
+ PATHS: { root: '/mock', data: '/mock/data' }
+}));
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(),
+ unlink: vi.fn().mockResolvedValue(undefined)
}));
vi.mock('./updateChecker.js', () => ({
@@ -14,6 +19,7 @@ vi.mock('./updateChecker.js', () => ({
}));
import { spawn } from 'child_process';
+import { readFile } from 'fs/promises';
import { recordUpdateResult } from './updateChecker.js';
import { executeUpdate } from './updateExecutor.js';
@@ -28,17 +34,27 @@ function createMockChild() {
beforeEach(() => {
vi.clearAllMocks();
+ // Default: marker file not found (tests that need it override this)
+ readFile.mockRejectedValue(new Error('ENOENT'));
});
describe('executeUpdate', () => {
- it('returns failure on Windows', async () => {
+ it('spawns powershell on Windows', async () => {
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
try {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
- const emits = [];
- const result = await executeUpdate('v1.0.0', (...args) => emits.push(args));
- expect(result.success).toBe(false);
- expect(emits[0][1]).toBe('error');
+ const child = createMockChild();
+ spawn.mockReturnValue(child);
+
+ const promise = executeUpdate('v1.0.0', () => {});
+ child.emit('close', 0);
+ await promise;
+
+ expect(spawn).toHaveBeenCalledWith(
+ 'powershell',
+ expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),
+ expect.any(Object)
+ );
} finally {
if (originalPlatformDescriptor) {
Object.defineProperty(process, 'platform', originalPlatformDescriptor);
@@ -54,26 +70,27 @@ describe('executeUpdate', () => {
const promise = executeUpdate('v1.0.0', (...args) => emits.push(args));
// Simulate STEP output
- child.stdout.emit('data', Buffer.from('STEP:git-fetch:running:Fetching tags\n'));
- child.stdout.emit('data', Buffer.from('STEP:git-fetch:done:Tags fetched\n'));
+ child.stdout.emit('data', Buffer.from('STEP:git-pull:running:Pulling latest changes\n'));
+ child.stdout.emit('data', Buffer.from('STEP:git-pull:done:Latest changes pulled\n'));
child.emit('close', 0);
const result = await promise;
expect(result.success).toBe(true);
- // Should have starting + git-fetch running + git-fetch done = 3 step emits
- expect(emits.some(e => e[0] === 'git-fetch' && e[1] === 'running')).toBe(true);
- expect(emits.some(e => e[0] === 'git-fetch' && e[1] === 'done')).toBe(true);
+ expect(emits.some(e => e[0] === 'git-pull' && e[1] === 'running')).toBe(true);
+ expect(emits.some(e => e[0] === 'git-pull' && e[1] === 'done')).toBe(true);
});
- it('records update result on close', async () => {
+ it('records update result on success with tag fallback when marker missing', async () => {
const child = createMockChild();
spawn.mockReturnValue(child);
const promise = executeUpdate('v1.0.0', () => {});
child.emit('close', 0);
- await promise;
+ const result = await promise;
+ expect(result.success).toBe(true);
+ expect(result.version).toBe('1.0.0');
expect(recordUpdateResult).toHaveBeenCalledWith(
expect.objectContaining({ version: '1.0.0', success: true })
);
@@ -93,6 +110,42 @@ describe('executeUpdate', () => {
);
});
+ it('handles CRLF line endings from Windows PowerShell', async () => {
+ const child = createMockChild();
+ spawn.mockReturnValue(child);
+
+ const emits = [];
+ const promise = executeUpdate('v1.0.0', (...args) => emits.push(args));
+
+ // Simulate CRLF output (Windows PowerShell)
+ child.stdout.emit('data', Buffer.from('STEP:git-pull:running:Pulling latest changes\r\n'));
+ child.stdout.emit('data', Buffer.from('STEP:git-pull:done:Latest changes pulled\r\n'));
+
+ child.emit('close', 0);
+ await promise;
+
+ // Messages should not contain trailing \r
+ const pullRunning = emits.find(e => e[0] === 'git-pull' && e[1] === 'running');
+ expect(pullRunning[2]).toBe('Pulling latest changes');
+ expect(pullRunning[2]).not.toMatch(/\r/);
+ });
+
+ it('returns actual version from completion marker and records result on success', async () => {
+ const child = createMockChild();
+ spawn.mockReturnValue(child);
+ readFile.mockResolvedValue(JSON.stringify({ version: '2.0.0', completedAt: '2026-01-01T00:00:00Z' }));
+
+ const promise = executeUpdate('v1.0.0', () => {});
+ child.emit('close', 0);
+ const result = await promise;
+
+ expect(result.success).toBe(true);
+ expect(result.version).toBe('2.0.0');
+ expect(recordUpdateResult).toHaveBeenCalledWith(
+ expect.objectContaining({ version: '2.0.0', success: true })
+ );
+ });
+
it('handles spawn error', async () => {
const child = createMockChild();
spawn.mockReturnValue(child);
diff --git a/update.ps1 b/update.ps1
index bb5fa42876..74acbadbb3 100644
--- a/update.ps1
+++ b/update.ps1
@@ -1,103 +1,190 @@
# PortOS Update Script for Windows PowerShell
$ErrorActionPreference = "Stop"
-Write-Host "===================================" -ForegroundColor Cyan
-Write-Host " PortOS Update" -ForegroundColor Cyan
-Write-Host "===================================" -ForegroundColor Cyan
-Write-Host ""
+$RootDir = Split-Path -Parent $MyInvocation.MyCommand.Path
+Set-Location $RootDir
+New-Item -ItemType Directory -Force -Path "$RootDir\data" | Out-Null
+
+# Log file for external command output — keeps noisy git/npm/node output
+# off the parent pipe so broken-pipe errors don't abort the update
+$UpdateLog = Join-Path $RootDir "data\update.log"
+"" | Set-Content -Path $UpdateLog
+
+# Safe write helper — suppresses broken-pipe IOExceptions when the parent
+# Node process dies mid-update (mirrors the bash SIGPIPE trap)
+function Write-SafeHost {
+ param(
+ [string]$Text,
+ [string]$ForegroundColor = ""
+ )
+ try {
+ if ($ForegroundColor) {
+ Write-Host $Text -ForegroundColor $ForegroundColor
+ } else {
+ Write-Host $Text
+ }
+ } catch {
+ if ($_.Exception -is [System.IO.IOException] -or
+ $_.Exception.InnerException -is [System.IO.IOException] -or
+ $_.Exception.ToString() -like "*The pipe has been ended*") {
+ return
+ }
+ throw
+ }
+}
+
+# Step output helper (parsed by updateExecutor for UI progress)
+function Step {
+ param([string]$Name, [string]$Status, [string]$Message)
+ Write-SafeHost "STEP:${Name}:${Status}:${Message}"
+}
+
+# Run an external command, routing stdout/stderr to the log file so
+# broken-pipe errors from the parent Node process don't abort the update
+function Invoke-Logged {
+ param([Parameter(ValueFromRemainingArguments)]$CmdArgs)
+ $cmd = $CmdArgs[0]
+ $args = @()
+ if ($CmdArgs.Count -gt 1) { $args = $CmdArgs[1..($CmdArgs.Count - 1)] }
+ & $cmd @args >> $UpdateLog 2>&1
+}
+
+Write-SafeHost "===================================" -ForegroundColor Cyan
+Write-SafeHost " PortOS Update" -ForegroundColor Cyan
+Write-SafeHost "===================================" -ForegroundColor Cyan
+Write-SafeHost ""
# Resilient npm install — retries once after cleaning node_modules on failure
function Safe-Install {
param([string]$Dir = ".", [string]$Label = "root")
- Write-Host "📦 Installing deps ($Label)..." -ForegroundColor Yellow
+ Write-SafeHost "📦 Installing deps ($Label)..." -ForegroundColor Yellow
Push-Location $Dir
- npm install 2>&1
+ Invoke-Logged npm install
if ($LASTEXITCODE -eq 0) { Pop-Location; return }
- Write-Host "⚠️ npm install failed for $Label — cleaning node_modules and retrying..." -ForegroundColor Yellow
+ Write-SafeHost "⚠️ npm install failed for $Label — cleaning node_modules and retrying..." -ForegroundColor Yellow
Pop-Location
if (Test-Path "$Dir/node_modules") {
Remove-Item -Recurse -Force "$Dir/node_modules" -ErrorAction SilentlyContinue
}
Push-Location $Dir
- npm install 2>&1
+ Invoke-Logged npm install
if ($LASTEXITCODE -eq 0) { Pop-Location; return }
Pop-Location
- Write-Host "❌ npm install failed for $Label after retry" -ForegroundColor Red
+ Write-SafeHost "❌ npm install failed for $Label after retry" -ForegroundColor Red
exit 1
}
-# Pull latest
-Write-Host "Pulling latest changes..." -ForegroundColor Yellow
-git pull --rebase --autostash
+# Pull latest — ensure we're on a branch first (old updater may have left
+# the repo in detached HEAD after checking out a tag)
+Step "git-pull" "running" "Pulling latest changes..."
+$headRef = git symbolic-ref -q HEAD 2>$null
+if (-not $headRef) {
+ Write-SafeHost "⚠️ Detached HEAD detected — checking out main branch" -ForegroundColor Yellow
+ Invoke-Logged git checkout main
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+}
+Invoke-Logged git pull --rebase --autostash
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-Write-Host ""
+Step "git-pull" "done" "Latest changes pulled"
+Write-SafeHost ""
# Stop PM2 apps to release file locks before updating
-Write-Host "Stopping PortOS apps..." -ForegroundColor Yellow
-npm run pm2:stop 2>$null
-Write-Host ""
+Step "pm2-stop" "running" "Stopping PortOS apps..."
+Invoke-Logged npm run pm2:stop
+Step "pm2-stop" "done" "Apps stopped"
+Write-SafeHost ""
# Update dependencies with retry logic
-Write-Host "Updating dependencies..." -ForegroundColor Yellow
+Step "npm-install" "running" "Installing all dependencies..."
Safe-Install -Dir "." -Label "root"
Safe-Install -Dir "client" -Label "client"
Safe-Install -Dir "server" -Label "server"
-Write-Host ""
+Write-SafeHost ""
# Verify critical dependencies exist
if (-not (Test-Path "client/node_modules/vite/bin/vite.js")) {
- Write-Host "❌ Critical dependency missing: client/node_modules/vite" -ForegroundColor Red
- Write-Host " Try running: npm run install:all"
+ Write-SafeHost "❌ Critical dependency missing: client/node_modules/vite" -ForegroundColor Red
+ Write-SafeHost " Try running: npm run install:all"
exit 1
}
+Step "npm-install" "done" "Dependencies installed"
# Run setup (data dirs + browser deps)
-Write-Host "Ensuring data & browser setup..." -ForegroundColor Yellow
-npm run setup
+Write-SafeHost "Ensuring data & browser setup..." -ForegroundColor Yellow
+Invoke-Logged npm run setup
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-Write-Host ""
+Write-SafeHost ""
# Ghostty sync (if installed)
-node scripts/setup-ghostty.js
-Write-Host ""
+Invoke-Logged node scripts/setup-ghostty.js
+Write-SafeHost ""
+
+# Run data migrations
+Step "migrations" "running" "Running data migrations..."
+$migrationsScript = Join-Path $RootDir "scripts\run-migrations.js"
+if (Test-Path $migrationsScript) {
+ Invoke-Logged node $migrationsScript
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+}
+Step "migrations" "done" "Migrations complete"
# Check for slash-do (optional, used by the PR Reviewer schedule task)
$slashDoFound = Get-Command slash-do -ErrorAction SilentlyContinue
if (-not $slashDoFound) {
- Write-Host "slash-do is not installed. It is used by the PR Reviewer schedule task." -ForegroundColor Yellow
+ Write-SafeHost "slash-do is not installed. It is used by the PR Reviewer schedule task." -ForegroundColor Yellow
if ([Environment]::UserInteractive) {
$reply = Read-Host "Install slash-do now? [y/N]"
if ($reply -match "^[Yy]$") {
- Write-Host "Installing slash-do..." -ForegroundColor Yellow
- npm install -g slash-do@latest 2>&1
+ Write-SafeHost "Installing slash-do..." -ForegroundColor Yellow
+ Invoke-Logged npm install -g slash-do@latest
if ($LASTEXITCODE -ne 0) {
- Write-Host "⚠️ Failed to install slash-do. Continuing without it." -ForegroundColor Red
+ Write-SafeHost "⚠️ Failed to install slash-do. Continuing without it." -ForegroundColor Red
}
} else {
- Write-Host "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
+ Write-SafeHost "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
}
} else {
- Write-Host "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
+ Write-SafeHost "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
}
- Write-Host ""
+ Write-SafeHost ""
}
# Build UI assets for production serving
-Write-Host "Building UI assets..." -ForegroundColor Yellow
-npm run build
+Step "build" "running" "Building client..."
+Invoke-Logged npm run build
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-Write-Host ""
+Step "build" "done" "Client built"
+Write-SafeHost ""
-# Restart PM2 apps
-Write-Host "Restarting PortOS..." -ForegroundColor Yellow
-npm run pm2:restart
-if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-Write-Host ""
+# Write completion marker atomically before restart so server reads it on boot
+$Tag = (Get-Content package.json -Raw | ConvertFrom-Json).version
+if (-not $Tag) {
+ Write-SafeHost "❌ Failed to determine package version from package.json" -ForegroundColor Red
+ exit 1
+}
+$completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
+$markerObj = @{ version = $Tag; completedAt = $completedAt }
+$marker = $markerObj | ConvertTo-Json -Compress
+$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
+[System.IO.File]::WriteAllText("$RootDir\data\update-complete.json.tmp", $marker, $utf8NoBom)
+Move-Item -Force "$RootDir\data\update-complete.json.tmp" "$RootDir\data\update-complete.json"
+
+# Restart PM2 apps — remove marker if restart fails so it isn't misread on boot
+Step "restart" "running" "Restarting PortOS..."
+Invoke-Logged npm run pm2:restart
+if ($LASTEXITCODE -ne 0) {
+ if (Test-Path "$RootDir\data\update-complete.json") {
+ Remove-Item -Force "$RootDir\data\update-complete.json"
+ }
+ exit $LASTEXITCODE
+}
+Step "restart" "done" "PortOS restarted"
+Write-SafeHost ""
-Write-Host "===================================" -ForegroundColor Green
-Write-Host " ✅ Update Complete!" -ForegroundColor Green
-Write-Host "===================================" -ForegroundColor Green
-Write-Host ""
+Write-SafeHost "===================================" -ForegroundColor Green
+Write-SafeHost " ✅ Update Complete!" -ForegroundColor Green
+Write-SafeHost "===================================" -ForegroundColor Green
+Write-SafeHost ""
diff --git a/update.sh b/update.sh
index 9ef2e7866f..3e6e9f331c 100755
--- a/update.sh
+++ b/update.sh
@@ -1,10 +1,41 @@
#!/bin/bash
-set -e
+set -euo pipefail
-echo "==================================="
-echo " PortOS Update"
-echo "==================================="
-echo ""
+# Ignore SIGPIPE: when PM2 restarts the server mid-update (watch detects
+# git changes), the parent Node process dies and our stdout pipe breaks.
+trap '' PIPE
+
+ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
+cd "$ROOT_DIR"
+mkdir -p "$ROOT_DIR/data"
+
+# Log file for external command output — keeps noisy git/npm/node output
+# off the parent pipe so broken-pipe errors don't abort the update
+UPDATE_LOG="$ROOT_DIR/data/update.log"
+: > "$UPDATE_LOG"
+
+# Safe echo — swallows EPIPE so broken stdout doesn't trip set -e
+log() {
+ echo "$@" 2>/dev/null || true
+}
+
+# Step output helper (parsed by updateExecutor for UI progress)
+step() {
+ local name="$1" status="$2" message="$3"
+ log "STEP:$name:$status:$message"
+}
+
+# Run an external command, routing stdout/stderr to the log file so
+# broken-pipe errors from the parent Node process don't abort the update.
+# Returns the command's exit code.
+run() {
+ "$@" >> "$UPDATE_LOG" 2>&1
+}
+
+log "==================================="
+log " PortOS Update"
+log "==================================="
+log ""
# Resilient npm install — retries once after cleaning node_modules on failure
# Handles ENOTEMPTY and other transient npm bugs
@@ -13,85 +44,120 @@ safe_install() {
local label="${dir}"
[ "$dir" = "." ] && label="root"
- echo "📦 Installing deps ($label)..."
- if (cd "$dir" && npm install 2>&1); then
+ log "📦 Installing deps ($label)..."
+ if (cd "$dir" && run npm install); then
return 0
fi
- echo "⚠️ npm install failed for $label — cleaning node_modules and retrying..."
+ log "⚠️ npm install failed for $label — cleaning node_modules and retrying..."
rm -rf "$dir/node_modules"
- if (cd "$dir" && npm install 2>&1); then
+ if (cd "$dir" && run npm install); then
return 0
fi
- echo "❌ npm install failed for $label after retry"
+ log "❌ npm install failed for $label after retry"
return 1
}
-# Pull latest
-echo "Pulling latest changes..."
-git pull --rebase --autostash
-echo ""
+# Pull latest — ensure we're on a branch first (old updater may have left
+# the repo in detached HEAD after checking out a tag)
+step "git-pull" "running" "Pulling latest changes..."
+if ! git symbolic-ref -q HEAD >/dev/null 2>&1; then
+ log "⚠️ Detached HEAD detected — checking out main branch"
+ run git checkout main
+fi
+run git pull --rebase --autostash
+step "git-pull" "done" "Latest changes pulled"
+log ""
# Stop PM2 apps to release file locks before updating
-echo "Stopping PortOS apps..."
-npm run pm2:stop 2>/dev/null || true
-echo ""
+step "pm2-stop" "running" "Stopping PortOS apps..."
+run npm run pm2:stop || true
+step "pm2-stop" "done" "Apps stopped"
+log ""
# Update dependencies with retry logic
-echo "Updating dependencies..."
+step "npm-install" "running" "Installing all dependencies..."
safe_install .
safe_install client
safe_install server
-echo ""
+log ""
# Verify critical dependencies exist
if [ ! -f "client/node_modules/vite/bin/vite.js" ]; then
- echo "❌ Critical dependency missing: client/node_modules/vite"
- echo " Try running: npm run install:all"
+ log "❌ Critical dependency missing: client/node_modules/vite"
+ log " Try running: npm run install:all"
exit 1
fi
+step "npm-install" "done" "Dependencies installed"
# Run setup (data dirs + browser deps)
-echo "Ensuring data & browser setup..."
-npm run setup
-echo ""
+log "Ensuring data & browser setup..."
+run npm run setup
+log ""
# Ghostty sync (if installed)
-node scripts/setup-ghostty.js
-echo ""
+run node scripts/setup-ghostty.js || true
+log ""
+
+# Run data migrations
+step "migrations" "running" "Running data migrations..."
+if [ -f "$ROOT_DIR/scripts/run-migrations.js" ]; then
+ run node "$ROOT_DIR/scripts/run-migrations.js"
+fi
+step "migrations" "done" "Migrations complete"
# Check for slash-do (optional, used by the PR Reviewer schedule task)
if ! command -v slash-do >/dev/null 2>&1; then
- echo "slash-do is not installed. It is used by the PR Reviewer schedule task."
+ log "slash-do is not installed. It is used by the PR Reviewer schedule task."
if [ -t 0 ]; then
read -p "Install slash-do now? [y/N] " -n 1 -r
- echo ""
+ log ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
- echo "Installing slash-do..."
- if ! npm install -g slash-do@latest; then
- echo "⚠️ Failed to install slash-do. Continuing without it."
+ log "Installing slash-do..."
+ if ! run npm install -g slash-do@latest; then
+ log "⚠️ Failed to install slash-do. Continuing without it."
fi
else
- echo "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
+ log "Skipping slash-do install. You can install later with: npm install -g slash-do@latest"
fi
else
- echo "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
+ log "Skipping slash-do prompt (non-interactive). Install later with: npm install -g slash-do@latest"
fi
- echo ""
+ log ""
fi
# Build UI assets for production serving
-echo "Building UI assets..."
-npm run build
-echo ""
-
-# Restart PM2 apps
-echo "Restarting PortOS..."
-npm run pm2:restart
-echo ""
-
-echo "==================================="
-echo " ✅ Update Complete!"
-echo "==================================="
-echo ""
+step "build" "running" "Building client..."
+run npm run build
+step "build" "done" "Client built"
+log ""
+
+# Determine post-update version from package.json (fail if unreadable)
+TAG=$(node -e 'const pkg = JSON.parse(require("fs").readFileSync("package.json","utf8")); if (typeof pkg.version !== "string") process.exit(1); process.stdout.write(pkg.version.trim());')
+if [ -z "$TAG" ]; then
+ log "❌ Failed to determine package version from package.json"
+ exit 1
+fi
+
+# Write completion marker atomically via Node (version passed as env var to avoid injection)
+TAG="$TAG" ROOT_DIR="$ROOT_DIR" node -e '
+ const fs = require("fs");
+ const path = require("path");
+ const marker = JSON.stringify({ version: process.env.TAG, completedAt: new Date().toISOString() });
+ fs.writeFileSync(path.join(process.env.ROOT_DIR, "data", "update-complete.json.tmp"), marker);
+' && mv "$ROOT_DIR/data/update-complete.json.tmp" "$ROOT_DIR/data/update-complete.json"
+
+# Restart PM2 apps — remove marker if restart fails so it isn't misread on boot
+step "restart" "running" "Restarting PortOS..."
+if ! run npm run pm2:restart; then
+ rm -f "$ROOT_DIR/data/update-complete.json"
+ exit 1
+fi
+step "restart" "done" "PortOS restarted"
+log ""
+
+log "==================================="
+log " ✅ Update Complete!"
+log "==================================="
+log ""