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
address review: keep updater on main through restart, respect mediaModels deletes, persist autonomousJobs snapshot updates
Adam Eivyb4e006799a54
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 4bc12b8980..9b4c26be1f 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -159,18 +159,29 @@ const upgradeImageEntries = (list) => {export const isFlux2 = (model) => model?.runner === 'flux2';-// Append video models whose id is in DEFAULT_REGISTRY but missing from the-// user's saved list. Lets us roll out new pipelines (e.g. the dgrauet ltx2-// runtime) to existing installs without forcing users to hand-edit-// data/media-models.json. Preserves any user customisations for ids they-// already have (we only ADD new entries; we don't overwrite existing).-const appendMissingVideoEntries = (userList, defaults) => {- if (!Array.isArray(userList)) return defaults;- if (!Array.isArray(defaults)) return userList;- const haveIds = new Set(userList.map((e) => e?.id).filter((id) => typeof id === 'string'));- const missing = defaults.filter((e) => typeof e?.id === 'string' && !haveIds.has(e.id));- if (!missing.length) return userList;- return [...userList, ...missing];+// Append video models that are genuinely new in this release (not in+// _shippedDefaults) to the user's list, while respecting deletions the user+// already made. Returns both the merged entry list and the newly-added ids so+// the caller can record them in _shippedDefaults.+//+// Semantics:+// - id already in userList → keep as-is (user customisations intact)+// - id in shippedIds but not userList → user explicitly deleted it; skip+// - id NOT in shippedIds → genuinely new built-in; add + record+const appendNewlyShippedVideoEntries = (userList, defaultList, shippedIds) => {+ const safeList = Array.isArray(userList) ? userList : [];+ const safeDefaults = Array.isArray(defaultList) ? defaultList : [];+ const userIds = new Set(safeList.map((e) => e?.id).filter((id) => typeof id === 'string'));+ const result = [...safeList];+ const newlyShipped = [];+ for (const def of safeDefaults) {+ if (typeof def?.id !== 'string') continue;+ if (userIds.has(def.id)) continue; // already present — keep user copy+ if (shippedIds.has(def.id)) continue; // user deleted it; don't re-add+ result.push(def);+ newlyShipped.push(def.id);+ }+ return { entries: result, newlyShipped };};// Existing installs predate the `runtime` field on video entries — fill it@@ -188,9 +199,58 @@ const backfillRuntime = (list) => {});};+// Build the initial shippedIds set for one platform on first encounter+// (no _shippedDefaults field yet).+//+// When the user has an array for this platform we treat the union of their ids+// and the default ids as "already shipped" — this preserves any deletions they+// made before _shippedDefaults was introduced, without re-adding removed entries.+//+// When the platform key is absent from their registry (e.g. the whole `video`+// section is missing), we return an empty set so the defaults are treated as+// genuinely new and get added as on a fresh install.+const bootstrapShippedIds = (userList, defaultList) => {+ if (!Array.isArray(userList)) return new Set(); // missing key → treat as fresh+ const safeDefaults = Array.isArray(defaultList) ? defaultList : [];+ const ids = new Set();+ for (const e of userList) if (typeof e?.id === 'string') ids.add(e.id);+ for (const e of safeDefaults) if (typeof e?.id === 'string') ids.add(e.id);+ return ids;+};+const normalizeRegistry = (parsed) => {const safe = isPlainObject(parsed) ? parsed : {};const safeVideo = isPlainObject(safe.video) ? safe.video : {};++ // _shippedDefaults tracks which built-in video ids have ever been delivered+ // to this install, so we can distinguish "user deleted it" from "genuinely+ // new in this release".+ const shippedVideo = isPlainObject(safe._shippedDefaults?.video) ? safe._shippedDefaults.video : null;+ const isBootstrap = shippedVideo === null;++ const shippedMacosIds = isBootstrap+ ? bootstrapShippedIds(safeVideo.macos, DEFAULT_REGISTRY.video.macos)+ : new Set(arrayOrDefault(shippedVideo.macos, []));+ const shippedWindowsIds = isBootstrap+ ? bootstrapShippedIds(safeVideo.windows, DEFAULT_REGISTRY.video.windows)+ : new Set(arrayOrDefault(shippedVideo.windows, []));++ const macosResult = appendNewlyShippedVideoEntries(+ safeVideo.macos,+ DEFAULT_REGISTRY.video.macos,+ shippedMacosIds,+ );+ const windowsResult = appendNewlyShippedVideoEntries(+ safeVideo.windows,+ DEFAULT_REGISTRY.video.windows,+ shippedWindowsIds,+ );++ const updatedShippedVideo = {+ macos: [...shippedMacosIds, ...macosResult.newlyShipped],+ windows: [...shippedWindowsIds, ...windowsResult.newlyShipped],+ };+return {...DEFAULT_REGISTRY,...safe,@@ -199,8 +259,12 @@ const normalizeRegistry = (parsed) => {video: {...DEFAULT_REGISTRY.video,...safeVideo,- macos: backfillRuntime(appendMissingVideoEntries(safeVideo.macos, DEFAULT_REGISTRY.video.macos)),- windows: backfillRuntime(appendMissingVideoEntries(safeVideo.windows, DEFAULT_REGISTRY.video.windows)),+ macos: backfillRuntime(macosResult.entries),+ windows: backfillRuntime(windowsResult.entries),+ },+ _shippedDefaults: {+ ...(safe._shippedDefaults || {}),+ video: updatedShippedVideo,},};};@@ -213,13 +277,32 @@ export const loadMediaModels = () => {// here aborts server startup. Permissions, broken symlink, transient I/O// all surface from readFileSync; malformed JSON from JSON.parse.let parsed = DEFAULT_REGISTRY;+ let readOk = false;try {const raw = readFileSync(REGISTRY_FILE, 'utf-8');parsed = JSON.parse(raw);+ readOk = true;} catch (err) {console.log(`⚠️ Failed to load ${REGISTRY_FILE} (${err.message}) — using built-in defaults`);}cached = normalizeRegistry(parsed);+ // Persist _shippedDefaults back to disk whenever it was absent or gained new+ // ids (bootstrap run or a new built-in model shipped in this release). This+ // ensures user deletions survive the next server restart.+ if (readOk) {+ const parsedShipped = isPlainObject(parsed._shippedDefaults?.video)+ ? parsed._shippedDefaults.video+ : null;+ const normalizedShipped = cached._shippedDefaults.video;+ const changed =+ parsedShipped === null ||+ normalizedShipped.macos.length !== (parsedShipped.macos?.length ?? 0) ||+ normalizedShipped.windows.length !== (parsedShipped.windows?.length ?? 0);+ if (changed) {+ writeFileSync(REGISTRY_FILE, JSON.stringify(cached, null, 2) + '\n');+ console.log(`📝 Updated media model registry _shippedDefaults: ${REGISTRY_FILE}`);+ }+ }return cached;};diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex ce3d9b90c9..ce11ff4c4c 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -260,4 +260,153 @@ describe('mediaModels registry', () => {expect(getDefaultVideoModelId()).toBe('works');logSpy.mockRestore();});++ // _shippedDefaults — editable-registry contract tests++ it('fresh install: all default video models present; _shippedDefaults populated', async () => {+ // No file exists yet → seedIfMissing writes DEFAULT_REGISTRY, then+ // normalizeRegistry runs over it and sets _shippedDefaults.+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ // All built-in macos models should be present+ const { DEFAULT_VIDEO_MODEL_IDS } = await import('./mediaModels.js').then(async (m) => {+ // We don't export the ids directly, so read them from the registry itself+ const r = m.loadMediaModels();+ return { DEFAULT_VIDEO_MODEL_IDS: r.video.macos.map((e) => e.id) };+ });+ for (const id of DEFAULT_VIDEO_MODEL_IDS) {+ expect(reg.video.macos.some((e) => e.id === id)).toBe(true);+ }+ // _shippedDefaults should be populated+ expect(reg._shippedDefaults?.video?.macos?.length).toBeGreaterThan(0);+ // Disk should now contain _shippedDefaults+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));+ expect(onDisk._shippedDefaults?.video?.macos?.length).toBeGreaterThan(0);+ logSpy.mockRestore();+ });++ it('user-deleted built-in video model is NOT re-added on subsequent load', async () => {+ const platformKey = process.platform === 'win32' ? 'windows' : 'macos';+ const otherKey = process.platform === 'win32' ? 'macos' : 'windows';+ // Simulate a registry that already has _shippedDefaults (post-bootstrap)+ // but is missing one model the user deleted (ltx2_unified).+ const deletedId = 'ltx2_unified';+ const remainingMacos = [+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta (~48 GB)', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4 (~22 GB)', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ { id: 'ltx23_dgrauet_q8', name: 'LTX-2.3 dgrauet Q8', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ ];+ const shippedMacosIds = [deletedId, ...remainingMacos.map((e) => e.id)];+ writeFileSync(registryFile, JSON.stringify({+ video: {+ [platformKey]: platformKey === 'macos' ? remainingMacos : [{ id: 'ltx_video', name: 'LTX', runtime: 'mlx_video', steps: 25, guidance: 3.0 }],+ [otherKey]: [],+ defaultMacos: 'ltx23_distilled_q4',+ defaultWindows: 'ltx_video',+ },+ image: [],+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],+ selectedTextEncoder: 't',+ _shippedDefaults: {+ video: {+ macos: shippedMacosIds,+ windows: ['ltx_video'],+ },+ },+ }));+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ // The deleted model must NOT be back+ expect(reg.video.macos.some((e) => e.id === deletedId)).toBe(false);+ // The shipped id must still be tracked+ expect(reg._shippedDefaults.video.macos).toContain(deletedId);+ logSpy.mockRestore();+ });++ it('new built-in id not in _shippedDefaults is added AND recorded', async () => {+ const platformKey = process.platform === 'win32' ? 'windows' : 'macos';+ const otherKey = process.platform === 'win32' ? 'macos' : 'windows';+ // Simulate a registry that pre-dates a newly-shipped model: _shippedDefaults+ // exists but does NOT include 'ltx23_dgrauet_q8' (as if it shipped later).+ const existingMacos = [+ { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'mlx_video', steps: 30, guidance: 3.0 },+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Q4', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ ];+ // _shippedDefaults does NOT include ltx23_dgrauet_q8+ const shippedMacosIds = existingMacos.map((e) => e.id);+ writeFileSync(registryFile, JSON.stringify({+ video: {+ [platformKey]: platformKey === 'macos' ? existingMacos : [{ id: 'ltx_video', name: 'LTX', runtime: 'mlx_video', steps: 25, guidance: 3.0 }],+ [otherKey]: [],+ defaultMacos: 'ltx23_distilled_q4',+ defaultWindows: 'ltx_video',+ },+ image: [],+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],+ selectedTextEncoder: 't',+ _shippedDefaults: {+ video: {+ macos: shippedMacosIds,+ windows: ['ltx_video'],+ },+ },+ }));+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ // ltx23_dgrauet_q8 is a current DEFAULT_REGISTRY entry not yet shipped →+ // should be added to the user's list+ expect(reg.video.macos.some((e) => e.id === 'ltx23_dgrauet_q8')).toBe(true);+ // And should now be recorded in _shippedDefaults+ expect(reg._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');+ // Persisted to disk+ const onDisk = JSON.parse(readFileSync(registryFile, 'utf-8'));+ expect(onDisk._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');+ logSpy.mockRestore();+ });++ it('user deletes a model that was newly added; deletion survives next load', async () => {+ const platformKey = process.platform === 'win32' ? 'windows' : 'macos';+ const otherKey = process.platform === 'win32' ? 'macos' : 'windows';+ // _shippedDefaults includes ltx23_dgrauet_q8 (it was added in a prior+ // load), but the user has now removed it from their video list.+ const userMacos = [+ { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'mlx_video', steps: 30, guidance: 3.0 },+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Q4', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ // ltx23_dgrauet_q8 intentionally absent+ ];+ const shippedMacosIds = [...userMacos.map((e) => e.id), 'ltx23_dgrauet_q8'];+ writeFileSync(registryFile, JSON.stringify({+ video: {+ [platformKey]: platformKey === 'macos' ? userMacos : [{ id: 'ltx_video', name: 'LTX', runtime: 'mlx_video', steps: 25, guidance: 3.0 }],+ [otherKey]: [],+ defaultMacos: 'ltx23_distilled_q4',+ defaultWindows: 'ltx_video',+ },+ image: [],+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],+ selectedTextEncoder: 't',+ _shippedDefaults: {+ video: {+ macos: shippedMacosIds,+ windows: ['ltx_video'],+ },+ },+ }));+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ // Deletion must be respected — model NOT re-added+ expect(reg.video.macos.some((e) => e.id === 'ltx23_dgrauet_q8')).toBe(false);+ // The id stays in _shippedDefaults so future loads also honour the deletion+ expect(reg._shippedDefaults.video.macos).toContain('ltx23_dgrauet_q8');+ logSpy.mockRestore();+ });});diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 055006fbf7..fe0bb0579e 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -461,10 +461,9 @@ async function initJobs() {return initial}- const jobCountBefore = loaded.jobs.length- const merged = mergeWithDefaults(loaded)+ const { data: merged, dirty } = mergeWithDefaults(loaded)const migrated = await migrateScriptsState(merged)- if (!migrated && merged.jobs.length !== jobCountBefore) {+ if (migrated || dirty) {await saveJobs(merged)}return merged@@ -523,7 +522,8 @@ async function loadJobs() {await initPromiseconst loaded = await readJSONFile(JOBS_FILE, null)if (!loaded) return createDefaultJobsData()- return mergeWithDefaults(loaded)+ const { data } = mergeWithDefaults(loaded)+ return data}/**@@ -691,11 +691,15 @@ function applyAdditiveFields(existing, defaultJob) {}/**- * Merge loaded data with defaults (add any missing default jobs)+ * Merge loaded data with defaults (add any missing default jobs).+ * Returns { data, dirty } where dirty is true if any structural or additive change+ * was made that requires the caller to persist the result.*/function mergeWithDefaults(loaded) {// Migration: remove jobs moved to Schedule system+ const countBefore = loaded.jobs.lengthloaded.jobs = loaded.jobs.filter(j => j.id !== 'job-pr-reviewer' && j.id !== 'job-jira-sprint-manager')+ let dirty = loaded.jobs.length !== countBeforeconst existingById = new Map(loaded.jobs.map(j => [j.id, j]))const now = new Date().toISOString()@@ -713,25 +717,27 @@ function mergeWithDefaults(loaded) {createdAt: now,updatedAt: now})- } else {- let changed = false- // Structural fields: always sync — these are code contracts, not user prefs- for (const field of JOB_STRUCTURAL_FIELDS) {- if (Object.hasOwn(defaultJob, field) && existing[field] !== defaultJob[field]) {- existing[field] = defaultJob[field]- changed = true- }- }- // Additive fields: snapshot-aware merge — propagates updates to untouched fields,- // preserves user customizations- if (applyAdditiveFields(existing, defaultJob)) changed = true- if (changed) {- existing.updatedAt = now+ dirty = true+ continue+ }+ let changed = false+ // Structural fields: always sync — these are code contracts, not user prefs+ for (const field of JOB_STRUCTURAL_FIELDS) {+ if (Object.hasOwn(defaultJob, field) && existing[field] !== defaultJob[field]) {+ existing[field] = defaultJob[field]+ changed = true}}+ // Additive fields: snapshot-aware merge — propagates updates to untouched fields,+ // preserves user customizations+ if (applyAdditiveFields(existing, defaultJob)) changed = true+ if (changed) {+ existing.updatedAt = now+ dirty = true+ }}- return loaded+ return { data: loaded, dirty }}/**@@ -1542,5 +1548,6 @@ export {executeShellJob,getAllowedCommands,validateCommand,- syncSkillTemplatesFromSample+ syncSkillTemplatesFromSample,+ initJobs}diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.jsindex 505ed1166c..1a55a55493 100644--- a/server/services/autonomousJobs.test.js+++ b/server/services/autonomousJobs.test.js@@ -39,9 +39,10 @@ import {getJobStats,INTERVAL_OPTIONS,isScriptJob,- executeScriptJob+ executeScriptJob,+ initJobs} from './autonomousJobs.js'-import { readJSONFile } from '../lib/fileUtils.js'+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js'import { cosEvents } from './cosEvents.js'import { checkAndPrompt } from './autobiography.js'@@ -542,6 +543,119 @@ describe('autonomousJobs', () => {})})+ describe('initJobs save-gating', () => {+ it('persists when shipped-default update reaches an untouched built-in job', async () => {+ // Job has scheduledTime matching snapshot → untouched, default ships new value → dirty+ readJSONFile.mockResolvedValue({+ version: 1,+ lastUpdated: '2025-01-01T00:00:00.000Z',+ jobs: [+ {+ id: 'job-datadog-error-monitor',+ name: 'DataDog Error Monitor',+ description: 'Monitors errors',+ category: 'datadog-error-monitor',+ interval: 'daily',+ intervalMs: 86400000,+ scheduledTime: '06:00',+ enabled: false,+ priority: 'MEDIUM',+ autonomyLevel: 'manager',+ promptTemplate: 'Default datadog prompt',+ lastRun: null,+ runCount: 0,+ createdAt: '2025-01-01T00:00:00.000Z',+ updatedAt: '2025-01-01T00:00:00.000Z',+ _shippedDefaults: { scheduledTime: '06:00' }+ }+ ]+ })++ atomicWrite.mockClear()+ const data = await initJobs()++ // The in-memory value is updated to the new shipped default+ const datadog = data.jobs.find(j => j.id === 'job-datadog-error-monitor')+ expect(datadog.scheduledTime).toBe('08:00')+ expect(datadog._shippedDefaults.scheduledTime).toBe('08:00')++ // The updated data was persisted to disk+ expect(atomicWrite).toHaveBeenCalled()+ const [, savedData] = atomicWrite.mock.calls[0]+ const savedDatadog = savedData.jobs.find(j => j.id === 'job-datadog-error-monitor')+ expect(savedDatadog.scheduledTime).toBe('08:00')+ expect(savedDatadog._shippedDefaults.scheduledTime).toBe('08:00')+ })++ it('does not persist when no changes are needed', async () => {+ // Construct a payload that exactly matches all shipped defaults so mergeWithDefaults is a no-op.+ // Use an unrecognized ID so it gets added as a new job — but then use a second call+ // to simulate a restart where nothing changed.+ // Simplest approach: provide a data set where all existing jobs already match defaults exactly.+ readJSONFile.mockResolvedValue({+ version: 1,+ lastUpdated: '2025-01-01T00:00:00.000Z',+ jobs: [] // no existing jobs; only new ones will be added (dirty = true on first call)+ })++ // First call seeds defaults → dirty, saves+ atomicWrite.mockClear()+ await initJobs()+ const firstSaveCount = atomicWrite.mock.calls.length+ expect(firstSaveCount).toBeGreaterThan(0)++ // Second call with the same data that was just "saved" — nothing changed+ // Simulate the re-read returning the exact same merged data (all snapshots bootstrapped)+ const savedData = atomicWrite.mock.calls[0][1]+ readJSONFile.mockResolvedValue(JSON.parse(JSON.stringify(savedData)))++ atomicWrite.mockClear()+ await initJobs()++ // No further saves needed — data is already up to date+ expect(atomicWrite).not.toHaveBeenCalled()+ })++ it('persists when user-edited field leaves snapshot intact on a different field', async () => {+ // User changed scheduledTime (preserves '09:00'), but priority is missing entirely → dirty+ readJSONFile.mockResolvedValue({+ version: 1,+ lastUpdated: '2025-01-01T00:00:00.000Z',+ jobs: [+ {+ id: 'job-datadog-error-monitor',+ name: 'DataDog Error Monitor',+ description: 'Monitors errors',+ category: 'datadog-error-monitor',+ interval: 'daily',+ intervalMs: 86400000,+ scheduledTime: '09:00',+ enabled: false,+ autonomyLevel: 'manager',+ promptTemplate: 'Default datadog prompt',+ lastRun: null,+ runCount: 0,+ createdAt: '2025-01-01T00:00:00.000Z',+ updatedAt: '2025-01-01T00:00:00.000Z',+ _shippedDefaults: { scheduledTime: '06:00' }+ // No priority — brand-new field → dirty+ }+ ]+ })++ atomicWrite.mockClear()+ const data = await initJobs()++ // User's scheduledTime must still be '09:00'+ const datadog = data.jobs.find(j => j.id === 'job-datadog-error-monitor')+ expect(datadog.scheduledTime).toBe('09:00')+ // New priority field is populated+ expect(datadog.priority).toBe('MEDIUM')+ // Data was persisted because a new field was added+ expect(atomicWrite).toHaveBeenCalled()+ })+ })+describe('getAllJobs', () => {it('returns all jobs from storage', async () => {const jobs = await getAllJobs()diff --git a/update.ps1 b/update.ps1index 13e635814c..7fcb9f2c0d 100644--- a/update.ps1+++ b/update.ps1@@ -95,13 +95,17 @@ function Safe-Install {}# Pull latest — always switch to main (detached HEAD or feature branch both-# need to land on main before pulling, or the version won't advance). If the-# user has uncommitted edits on a non-main branch, stash them first so the-# checkout doesn't abort or carry edits onto main, then restore on the way back.+# need to land on main before pulling, or the version won't advance). The+# rest of the script (install, build, restart) runs on main so the app+# starts on the freshly-pulled revision. Local edits on the original branch+# are stashed first so checkout doesn't abort, and we leave them in the+# stash list afterward — the user can restore with `git stash pop` after+# 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..."$headRef = git symbolic-ref -q HEAD 2>$null$currentBranch = if ($headRef) { $headRef -replace "refs/heads/", "" } else { "" }-$stashed = $false+$stashedForBranch = ""if ($currentBranch -ne "main") {$hasChanges = $falsegit diff --quiet 2>$null@@ -115,9 +119,10 @@ if ($currentBranch -ne "main") {if ($untracked) { $hasChanges = $true }}if ($hasChanges) {- Write-SafeHost "⚠️ Stashing local changes from '$(if ($currentBranch) { $currentBranch } else { 'detached HEAD' })' before switching to main" -ForegroundColor Yellow+ $branchLabel = if ($currentBranch) { $currentBranch } else { "detached HEAD" }+ Write-SafeHost "⚠️ Stashing local changes from '$branchLabel' so checkout can proceed" -ForegroundColor YellowInvoke-Logged git stash push -u -m "portos-update-$([int][double]::Parse((Get-Date -UFormat %s)))"- if ($LASTEXITCODE -eq 0) { $stashed = $true }+ if ($LASTEXITCODE -eq 0) { $stashedForBranch = $branchLabel }}if (-not $currentBranch) {$detachedCommit = git rev-parse --short HEAD@@ -130,18 +135,6 @@ if ($currentBranch -ne "main") {}Invoke-Logged git pull --rebase --autostashif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }-if ($stashed) {- if ($currentBranch) {- Write-SafeHost "⚠️ Returning to '$currentBranch' and restoring stashed changes" -ForegroundColor Yellow- Invoke-Logged git checkout $currentBranch- Invoke-Logged git stash pop- if ($LASTEXITCODE -ne 0) {- Write-SafeHost "⚠️ Could not restore stashed changes — see 'git stash list'" -ForegroundColor Yellow- }- } else {- Write-SafeHost "⚠️ Was on detached HEAD; stashed changes preserved in 'git stash' (run 'git stash pop' manually)" -ForegroundColor Yellow- }-}Step "git-pull" "done" "Latest changes pulled"Write-SafeHost ""@@ -277,3 +270,9 @@ Write-SafeHost "===================================" -ForegroundColor GreenWrite-SafeHost " ✅ Update Complete!" -ForegroundColor GreenWrite-SafeHost "===================================" -ForegroundColor GreenWrite-SafeHost ""++if ($stashedForBranch) {+ Write-SafeHost "ℹ️ Your local changes from '$stashedForBranch' were stashed for the update." -ForegroundColor Cyan+ Write-SafeHost " To restore them: git checkout '$stashedForBranch'; git stash pop" -ForegroundColor Cyan+ Write-SafeHost " The stash entry is at the top of 'git stash list'." -ForegroundColor Cyan+}diff --git a/update.sh b/update.shindex 95763c18ed..ca8c3dc59e 100755--- a/update.sh+++ b/update.sh@@ -60,31 +60,27 @@ safe_install() {}# Pull latest — always switch to main (detached HEAD or feature branch both-# need to land on main before pulling, or the version won't advance). If the-# user has uncommitted edits on a non-main branch, stash them first so the-# checkout doesn't abort or carry edits onto main, then restore on the way back.+# need to land on main before pulling, or the version won't advance). The+# rest of the script (install, build, restart) runs on main so the app+# starts on the freshly-pulled revision. Local edits on the original branch+# are stashed first so checkout doesn't abort, and we leave them in the+# stash list afterward — the user can restore with `git stash pop` after+# 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..."current_branch=$(git symbolic-ref -q --short HEAD 2>/dev/null || echo "")-stashed=0+stashed_for_branch=""if [ "$current_branch" != "main" ]; thenif ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then- log "⚠️ Stashing local changes from '${current_branch:-detached HEAD}' before switching to main"+ log "⚠️ Stashing local changes from '${current_branch:-detached HEAD}' so checkout can proceed"if run git stash push -u -m "portos-update-$(date +%s)"; then- stashed=1+ stashed_for_branch="${current_branch:-detached HEAD}"fifilog "⚠️ On branch '${current_branch:-detached HEAD}' — switching to main for update"run git checkout mainfirun git pull --rebase --autostash-if [ "$stashed" = "1" ]; then- if [ -n "$current_branch" ]; then- log "⚠️ Returning to '$current_branch' and restoring stashed changes"- run git checkout "$current_branch" && (run git stash pop || log "⚠️ Could not restore stashed changes — see 'git stash list'")- else- log "⚠️ Was on detached HEAD; stashed changes preserved in 'git stash' (run 'git stash pop' manually)"- fi-fistep "git-pull" "done" "Latest changes pulled"log ""@@ -202,3 +198,9 @@ log "==================================="log " ✅ Update Complete!"log "==================================="log ""++if [ -n "$stashed_for_branch" ]; then+ log "ℹ️ Your local changes from '$stashed_for_branch' were stashed for the update."+ log " To restore them: git checkout '$stashed_for_branch' && git stash pop"+ log " The stash entry is at the top of 'git stash list'."+fi