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
clean-reinstall workspaces whose package.json changed on update
[._.]/ Adam Eivybfe0a7416b19
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 714131f5af..9d6de5c64c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,7 @@## Fixed+- **Updating across a major dependency bump no longer breaks the UI** — when an update changed a workspace's `package.json` (e.g. the React 18 → 19 bump), the updater ran an in-place `npm install` over the old `node_modules`. Because the client/server lockfiles are per-install and gitignored, that could leave a half-upgraded, duplicated dependency tree (a stray `react@18` lingering beside `react@19`) — the build succeeded but the app threw "Invalid hook call" at runtime and rendered a blank page. The updater now detects which workspaces' `package.json` the pull actually changed and does a clean reinstall (wiping `node_modules` and the stale gitignored lockfile) for only those, resolving the tree from scratch; unchanged workspaces keep their fast incremental install. Both `update.sh` and `update.ps1` (Windows) got the fix, and the same guard now covers the manual `git pull` + `npm start` path — startup remembers each workspace's `package.json` hash and clean-reinstalls when it changes.- **De-watermarked images now label correctly in the gallery lightbox** — after removing the visible Gemini / Nano-Banana ✦ sparkle, the resulting variant was meant to read "Watermark removed from …" in the lightbox lineage row and group as "Watermark removed". But the `watermarkRemoved` flag the server stamps on the variant was dropped during image normalization, so through the real gallery path (Image Gen, History, Collections) the variant fell through to the generic "Cleaned from …" label instead. The flag now survives normalization, so the honest lineage label and variant grouping fire as intended.- **Database page works on Windows** — the Database page's Start/Fix/Status actions invoke the `db.sh` manager through bash; on Windows the script's native path (`H:\…\db.sh`) was passed with backslashes, which bash collapsed into a bogus path (exit 127, "No such file or directory"), so the page reported the Docker database as stopped even while it was running. The path is now normalized to forward slashes, which Git Bash accepts on Windows. A second Windows-only failure in the per-backend export path (spawning `mkdir -p`, which isn't a real executable on Windows) was also fixed by using Node's filesystem API instead. Mac/Linux behavior is unchanged.- **Database page works on Windows (follow-up: use Git Bash, not WSL)** — even after the path was forward-slashed, Start/Fix/Status still failed with exit 127 on machines that have **both** Git Bash and WSL installed: the server (launched by PM2) resolved a bare `bash` to WSL's `C:\Windows\System32\bash.exe`, which mounts drives at `/mnt/h/…` and genuinely cannot see a `H:/…` drive path — and would run `db.sh` against Linux tools even if it could. PortOS now resolves the interpreter explicitly, preferring **Git Bash** (the correct Windows interpreter), with a `PORTOS_BASH` override for non-standard installs. Mac/Linux behavior is unchanged (bare `bash`).diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.jsindex ba088f46ed..114f1afe56 100644--- a/scripts/ensure-deps.js+++ b/scripts/ensure-deps.js@@ -3,20 +3,82 @@* Runs npm install only for workspaces with missing node_modules.* Handles ENOTEMPTY npm bug by retrying with clean node_modules.*/-import { existsSync, rmSync } from 'fs';+import { existsSync, rmSync, readFileSync, writeFileSync, mkdirSync } from 'fs';import { execFileSync } from 'child_process';+import { createHash } from 'crypto';import { join, dirname } from 'path';import { fileURLToPath } from 'url';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';+// Persisted package.json hashes (per workspace) from the last successful install.+// A changed hash means the manifest moved since we last resolved the tree, so an+// in-place `npm install` over the existing node_modules could leave a stale /+// duplicated tree (e.g. a react@18 copy lingering beside react@19 after a major+// bump) — which builds fine but throws "Invalid hook call" at runtime. When the+// hash changes we wipe node_modules first and reinstall from scratch instead.+// This mirrors update.sh's pull-diff clean-reinstall for the manual+// `git pull` + `npm start` path, which has no pull context to diff against.+const HASH_FILE = join(ROOT, 'data', 'deps-hashes.json');+const WORKSPACES = [{ dir: ROOT, label: 'root' },{ dir: join(ROOT, 'client'), label: 'client' },- { dir: join(ROOT, 'server'), label: 'server' }+ { dir: join(ROOT, 'server'), label: 'server' },+ { dir: join(ROOT, 'autofixer'), label: 'autofixer' }];+function pkgHash(dir) {+ const pkgPath = join(dir, 'package.json');+ if (!existsSync(pkgPath)) return null;+ return createHash('sha256').update(readFileSync(pkgPath)).digest('hex');+}++function loadHashes() {+ try {+ return JSON.parse(readFileSync(HASH_FILE, 'utf8'));+ } catch {+ return {};+ }+}++function saveHashes(hashes) {+ try {+ mkdirSync(dirname(HASH_FILE), { recursive: true });+ writeFileSync(HASH_FILE, JSON.stringify(hashes, null, 2));+ } catch (err) {+ // Non-fatal — the worst case is we re-evaluate the hash next boot.+ console.error(`⚠️ Could not persist deps hashes: ${err.message ?? err}`);+ }+}++// True only when the lockfile is gitignored (the per-install client/server+// locks). A tracked root lockfile is kept — it's consistent with package.json.+function lockfileIsGitignored(dir) {+ try {+ execFileSync('git', ['check-ignore', '-q', join(dir, 'package-lock.json')], {+ cwd: ROOT,+ stdio: 'ignore',+ windowsHide: true+ });+ return true;+ } catch {+ return false;+ }+}++function cleanWorkspaceDeps(dir) {+ try {+ rmSync(join(dir, 'node_modules'), { recursive: true, force: true });+ } catch { /* best effort */ }+ if (lockfileIsGitignored(dir)) {+ try {+ rmSync(join(dir, 'package-lock.json'), { force: true });+ } catch { /* best effort */ }+ }+}+function install(dir, label) {try {execFileSync(NPM, ['install'], { cwd: dir, stdio: 'inherit', windowsHide: true });@@ -40,13 +102,33 @@ function install(dir, label) {}}+const storedHashes = loadHashes();+let hashesDirty = false;let needed = false;+for (const { dir, label } of WORKSPACES) {- if (!existsSync(join(dir, 'node_modules'))) {- console.log(`📦 Missing node_modules for ${label} — installing...`);+ const currentHash = pkgHash(dir);+ const nodeModulesMissing = !existsSync(join(dir, 'node_modules'));+ const storedHash = storedHashes[label];+ // Only treat as "deps changed" when we have a baseline to compare against —+ // a first run (no stored hash) seeds the baseline without a needless wipe.+ const depsChanged = storedHash != null && currentHash != null && storedHash !== currentHash;++ if (nodeModulesMissing || depsChanged) {+ if (depsChanged && !nodeModulesMissing) {+ console.log(`🧹 ${label} package.json changed since last install — clean reinstall...`);+ cleanWorkspaceDeps(dir);+ } else {+ console.log(`📦 Missing node_modules for ${label} — installing...`);+ }if (!install(dir, label)) process.exit(1);needed = true;}++ if (currentHash != null && storedHashes[label] !== currentHash) {+ storedHashes[label] = currentHash;+ hashesDirty = true;+ }}// Verify critical packages exist even if node_modules dirs were present@@ -79,4 +161,6 @@ for (const [dir, { label, pkgs }] of criticalByDir) {}}+if (hashesDirty) saveHashes(storedHashes);+if (needed) console.log('✅ Dependencies verified');diff --git a/update.ps1 b/update.ps1index 492ef12d62..b20020f7c1 100644--- a/update.ps1+++ b/update.ps1@@ -71,10 +71,49 @@ Write-SafeHost " PortOS Update" -ForegroundColor CyanWrite-SafeHost "===================================" -ForegroundColor CyanWrite-SafeHost ""+# Which workspaces' package.json this update touched (populated after the pull+# below). When the pulled update changed a workspace's manifest, an in-place+# `npm install` over a node_modules tree resolved for the PREVIOUS major+# versions can leave a duplicated/stale tree (e.g. a stray react@18 copy beside+# react@19) — which builds fine but throws "Invalid hook call" at runtime. A+# from-scratch reinstall is the only reliable fix for a major dependency bump.+$script:DepsChangedFiles = @()+$script:DepsChangedUnknown = $false++function Test-WorkspaceDepsChanged {+ param([string]$Dir)+ if ($script:DepsChangedUnknown) { return $true }+ $rel = if ($Dir -eq ".") { "package.json" } else { ($Dir -replace '^\./', '') + "/package.json" }+ return $script:DepsChangedFiles -contains $rel+}++# Wipe a workspace's installed deps so the next `npm install` resolves the tree+# from scratch. node_modules is always removed; the lockfile is removed ONLY+# when it's gitignored (the per-install client/server/autofixer locks) — a+# tracked root lock was just pulled and is already consistent with the new+# package.json, so keep it for reproducible resolution.+function Clear-WorkspaceDeps {+ param([string]$Dir)+ if (Test-Path "$Dir/node_modules") {+ Remove-Item -Recurse -Force "$Dir/node_modules" -ErrorAction SilentlyContinue+ }+ git check-ignore -q "$Dir/package-lock.json" 2>$null+ if ($LASTEXITCODE -eq 0 -and (Test-Path "$Dir/package-lock.json")) {+ Remove-Item -Force "$Dir/package-lock.json" -ErrorAction SilentlyContinue+ }+}+# Resilient npm install — retries once after cleaning node_modules on failurefunction Safe-Install {param([string]$Dir = ".", [string]$Label = "root")+ # Force a clean reinstall when this update changed the workspace's deps —+ # never trust an in-place install across a dependency-manifest change.+ if (Test-WorkspaceDepsChanged -Dir $Dir) {+ Write-SafeHost "🧹 $Label package.json changed in this update — clean reinstall (wiping node_modules)" -ForegroundColor Yellow+ Clear-WorkspaceDeps -Dir $Dir+ }+Write-SafeHost "📦 Installing deps ($Label)..." -ForegroundColor YellowPush-Location $DirInvoke-Logged npm install@@ -82,12 +121,7 @@ function Safe-Install {Write-SafeHost "⚠️ npm install failed for $Label — cleaning node_modules + package-lock.json and retrying..." -ForegroundColor YellowPop-Location- if (Test-Path "$Dir/node_modules") {- Remove-Item -Recurse -Force "$Dir/node_modules" -ErrorAction SilentlyContinue- }- if (Test-Path "$Dir/package-lock.json") {- Remove-Item -Force "$Dir/package-lock.json" -ErrorAction SilentlyContinue- }+ Clear-WorkspaceDeps -Dir $DirPush-Location $DirInvoke-Logged npm installif ($LASTEXITCODE -eq 0) { Pop-Location; return }@@ -106,6 +140,9 @@ function Safe-Install {# the update completes (we don't auto-pop because the rest of the script# needs to keep running with main's contents).Step "git-pull" "running" "Pulling latest changes..."+# Record the revision we're updating FROM (before any branch switch) so we can+# tell afterward which workspaces' package.json the pull changed → clean reinstall.+$prePullSha = git rev-parse HEAD 2>$null$originUrl = git remote get-url origin 2>$nullif ($originUrl) {# Redact any embedded credentials (https://user:token@host/...) before logging@@ -155,6 +192,23 @@ if ($currentBranch -ne "main") {Invoke-Logged git pull --rebase --autostashif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }Step "git-pull" "done" "Latest changes pulled"++# Determine which workspaces' package.json this update touched, so Safe-Install+# can force a clean reinstall for them (see Test-WorkspaceDepsChanged). If the+# from-revision is unknown/unreachable (fresh clone, unrelated history), treat+# deps as changed everywhere — a clean reinstall is the conservative default.+if ($prePullSha) {+ git cat-file -e "$prePullSha^{commit}" 2>$null+ if ($LASTEXITCODE -eq 0) {+ $diff = git diff --name-only $prePullSha HEAD 2>$null+ if ($diff) { $script:DepsChangedFiles = @($diff) }+ } else {+ $script:DepsChangedUnknown = $true+ }+} else {+ $script:DepsChangedUnknown = $true+}+$global:LASTEXITCODE = 0Write-SafeHost ""# Update submodules (slash-do and any others)diff --git a/update.sh b/update.shindex 09a0eba590..c633611986 100755--- a/update.sh+++ b/update.sh@@ -37,6 +37,35 @@ log " PortOS Update"log "==================================="log ""+# Wipe a workspace's installed deps so the next `npm install` resolves the tree+# from scratch. node_modules is always removed; the lockfile is removed ONLY+# when it's gitignored (the per-install client/server/autofixer locks) — a+# tracked root lock was just pulled and is already consistent with the new+# package.json, so keep it for reproducible resolution.+clean_workspace_deps() {+ local dir="$1"+ rm -rf "$dir/node_modules"+ if git check-ignore -q "$dir/package-lock.json" 2>/dev/null; then+ rm -f "$dir/package-lock.json"+ fi+}++# Whether the pulled update changed this workspace's package.json. When it did,+# an in-place `npm install` over a node_modules tree resolved for the PREVIOUS+# major versions can leave a duplicated/stale tree (e.g. a stray react@18 copy+# beside react@19) — which builds fine but throws "Invalid hook call" at+# runtime. A from-scratch reinstall is the only reliable fix for a major bump.+# DEPS_CHANGED_FILES / DEPS_CHANGED_UNKNOWN are populated after the pull below.+DEPS_CHANGED_FILES=""+DEPS_CHANGED_UNKNOWN=0+workspace_deps_changed() {+ local dir="$1"+ [ "$DEPS_CHANGED_UNKNOWN" = "1" ] && return 0+ local rel="package.json"+ [ "$dir" != "." ] && rel="${dir#./}/package.json"+ printf '%s\n' "$DEPS_CHANGED_FILES" | grep -qx "$rel"+}+# Resilient npm install — retries once after cleaning node_modules on failure# Handles ENOTEMPTY and other transient npm bugssafe_install() {@@ -44,14 +73,20 @@ safe_install() {local label="${dir}"[ "$dir" = "." ] && label="root"+ # Force a clean reinstall when this update changed the workspace's deps —+ # never trust an in-place install across a dependency-manifest change.+ if workspace_deps_changed "$dir"; then+ log "🧹 $label package.json changed in this update — clean reinstall (wiping node_modules)"+ clean_workspace_deps "$dir"+ fi+log "📦 Installing deps ($label)..."if (cd "$dir" && run npm install); thenreturn 0filog "⚠️ npm install failed for $label — cleaning node_modules + package-lock.json and retrying..."- rm -rf "$dir/node_modules"- rm -f "$dir/package-lock.json"+ clean_workspace_deps "$dir"if (cd "$dir" && run npm install); thenreturn 0fi@@ -69,6 +104,9 @@ safe_install() {# the update completes (we don't auto-pop because the rest of the script# needs to keep running with main's contents).step "git-pull" "running" "Pulling latest changes..."+# Record the revision we're updating FROM (before any branch switch) so we can+# tell afterward which workspaces' package.json the pull changed → clean reinstall.+pre_pull_sha=$(git rev-parse HEAD 2>/dev/null || echo "")origin_url=$(git remote get-url origin 2>/dev/null || echo "")if [ -n "$origin_url" ]; then# Redact any embedded credentials (https://user:token@host/...) before logging@@ -97,6 +135,16 @@ if [ "$current_branch" != "main" ]; thenfirun git pull --rebase --autostashstep "git-pull" "done" "Latest changes pulled"++# Determine which workspaces' package.json this update touched, so safe_install+# can force a clean reinstall for them (see workspace_deps_changed). If the+# from-revision is unknown/unreachable (fresh clone, unrelated history), treat+# deps as changed everywhere — a clean reinstall is the conservative default.+if [ -n "$pre_pull_sha" ] && git cat-file -e "${pre_pull_sha}^{commit}" 2>/dev/null; then+ DEPS_CHANGED_FILES=$(git diff --name-only "$pre_pull_sha" HEAD 2>/dev/null || echo "")+else+ DEPS_CHANGED_UNKNOWN=1+filog ""# Update submodules (slash-do and any others)