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: refresh updater panels when update and activity state changes (#8551)
[._.]/ Adam Eivy48c3cc09c813
diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.jsxindex ca6b85bf99..a5bab4dc07 100644--- a/client/src/components/apps/tabs/AutoUpdatePanel.jsx+++ b/client/src/components/apps/tabs/AutoUpdatePanel.jsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';import { AlertTriangle, Bot, Check, Clock, GitBranch, Loader, Tag } from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { useSocketResource } from '../../../hooks/useSocketResource';import { formatDateTime, timeAgo } from '../../../utils/formatters';// Why the updater is standing by, in the user's words rather than the@@ -20,6 +20,8 @@ const SKIP_LABELS = {'runtime-persistence-unavailable': 'Could not save the updater state',};+const STATUS_EVENTS = ['portos:auto-update:changed', 'portos:update:checked', 'system:activity'];+const CHANNELS = [{ id: 'release', label: 'Releases', icon: Tag, hint: 'Same as “Update Now” — updates when a newer GitHub release is published.' },{ id: 'main', label: 'origin/main', icon: GitBranch, hint: 'Same as App Management’s “Update app” — updates whenever origin’s default branch moves ahead.' },@@ -34,10 +36,9 @@ const CHANNELS = [* sitting behind says so here.*/export default function AutoUpdatePanel() {- // Polls on its own rather than riding the Update tab's /status refetch: this- // payload walks git status and the activity snapshot, so it is deliberately- // the slower of the two.- const { data: status, refetch } = useAutoRefetch(() => api.getAutoUpdateStatus({ silent: true }), 15000);+ const { data: status, refetch, updateData } = useSocketResource(+ () => api.getAutoUpdateStatus({ silent: true }), { events: STATUS_EVENTS }+ );const config = status?.config;const runtime = status?.runtime;const repo = status?.repo;@@ -50,8 +51,8 @@ export default function AutoUpdatePanel() {// Re-seed when the SERVER's value changes — compared against the last config// it sent, not against the draft. Comparing against the draft would read the- // user's half-typed interval as staleness and overwrite it on the next 15s- // poll, which is the opposite of what this effect is for.+ // user's half-typed interval as staleness and overwrite it on the next+ // invalidation, which is the opposite of what this effect is for.const lastServerConfig = useRef(null);useEffect(() => {if (!config) return;@@ -72,7 +73,7 @@ export default function AutoUpdatePanel() {next.minIntervalHours = Math.min(bounds.max, Math.max(bounds.min, Number(next.minIntervalHours) || bounds.min));setDraft(next);setSaving(true);- const saved = await api.patchSettingsSlice('autoUpdate', next).catch((err) => {+ const saved = await api.patchSettingsSlice('autoUpdate', next, { silent: true }).catch((err) => {toast.error(`Could not save automatic updates: ${err.message}`);return null;});@@ -81,6 +82,7 @@ export default function AutoUpdatePanel() {setDraft(config);return;}+ updateData(previous => ({ ...previous, config: saved.autoUpdate || next }));refetch();};diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.test.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.test.jsxindex 649b101ec0..b32ea3e48f 100644--- a/client/src/components/apps/tabs/AutoUpdatePanel.test.jsx+++ b/client/src/components/apps/tabs/AutoUpdatePanel.test.jsx@@ -1,17 +1,20 @@-import { render, screen } from '@testing-library/react';+import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import AutoUpdatePanel from './AutoUpdatePanel';const { mockPatch, mockGetStatus } = vi.hoisted(() => ({ mockPatch: vi.fn(), mockGetStatus: vi.fn() }));vi.mock('../../../services/api', () => ({ patchSettingsSlice: mockPatch, getAutoUpdateStatus: mockGetStatus }));vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));-vi.mock('../../../hooks/useAutoRefetch', () => ({- useAutoRefetch: (fetchFn) => {- fetchFn();- return { data: mockGetStatus.mock.results.at(-1)?.value, refetch: vi.fn() };+const handlers = new Map();+vi.mock('../../../services/socket', () => ({+ default: {+ on: (event, handler) => handlers.set(event, handler),+ off: (event, handler) => { if (handlers.get(event) === handler) handlers.delete(event); },},}));+afterEach(() => { cleanup(); vi.useRealTimers(); });+const status = (overrides = {}) => ({config: { enabled: true, channel: 'release', minIntervalHours: 6, resolveBlockersWithAgent: true },@@ -29,17 +32,18 @@ beforeEach(() => {});describe('AutoUpdatePanel', () => {- it('renders nothing until the server has sent an effective config', () => {+ it('renders nothing until the server has sent an effective config', async () => {mockGetStatus.mockReturnValue(undefined);const { container } = render(<AutoUpdatePanel />);+ await act(async () => {});expect(container).toBeEmptyDOMElement();});it('saves a channel change through the settings slice', async () => {showing();render(<AutoUpdatePanel />);- await userEvent.click(screen.getByLabelText(/origin\/main/));- expect(mockPatch).toHaveBeenCalledWith('autoUpdate', expect.objectContaining({ channel: 'main', enabled: true }));+ await userEvent.click(await screen.findByLabelText(/origin\/main/));+ expect(mockPatch).toHaveBeenCalledWith('autoUpdate', expect.objectContaining({ channel: 'main', enabled: true }), { silent: true });});// An unattended updater that simply never runs is indistinguishable from a@@ -50,25 +54,74 @@ describe('AutoUpdatePanel', () => {runtime: { lastRunAt: null, lastSkip: { reason: 'busy', detail: '2 video renders queued', at: new Date().toISOString() } },});render(<AutoUpdatePanel />);- expect(screen.getByText(/Busy: 2 video renders queued/)).toBeInTheDocument();+ expect(await screen.findByText(/Busy: 2 video renders queued/)).toBeInTheDocument();expect(screen.getByText(/Waiting for the system to go idle/)).toBeInTheDocument();});- it('surfaces a checkout that is not ready to update', () => {+ it('surfaces a checkout that is not ready to update', async () => {showing({repo: { ready: false, needsAgent: true, branch: 'feature/x', defaultBranch: 'main', summary: 'the working tree has uncommitted changes' },});render(<AutoUpdatePanel />);- expect(screen.getByText(/the working tree has uncommitted changes/)).toBeInTheDocument();+ expect(await screen.findByText(/the working tree has uncommitted changes/)).toBeInTheDocument();expect(screen.getByText(/A CoS agent will be queued to resolve it/)).toBeInTheDocument();});- it('hides the configuration while the feature is off', () => {+ it('hides the configuration while the feature is off', async () => {showing({config: { enabled: false, channel: 'release', minIntervalHours: 6, resolveBlockersWithAgent: true },});render(<AutoUpdatePanel />);expect(screen.queryByLabelText(/origin\/main/)).not.toBeInTheDocument();- expect(screen.getByLabelText(/Off/)).toBeInTheDocument();+ expect(await screen.findByLabelText(/Off/)).toBeInTheDocument();+ });+});++it('refreshes on events and recovery once, never periodically, and cleans up', async () => {+ vi.useFakeTimers();+ showing();+ const view = render(<AutoUpdatePanel />);+ await act(async () => {});+ expect(mockGetStatus).toHaveBeenCalledTimes(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(60000); });+ expect(mockGetStatus).toHaveBeenCalledTimes(1);+ showing({ runtime: { lastSkip: { reason: 'cooldown', detail: '60 minutes left' } } });+ await act(async () => {+ handlers.get('portos:auto-update:changed')({});+ handlers.get('system:activity')({});});+ expect(mockGetStatus).toHaveBeenCalledTimes(2);+ expect(screen.getByText(/60 minutes left/)).toBeInTheDocument();+ await act(async () => { handlers.get('connect')(); });+ expect(mockGetStatus).toHaveBeenCalledTimes(3);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ await act(async () => { handlers.get('system:activity')({}); });+ expect(mockGetStatus).toHaveBeenCalledTimes(3);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ document.dispatchEvent(new Event('visibilitychange'));+ });+ expect(mockGetStatus).toHaveBeenCalledTimes(4);+ view.unmount();+ expect(handlers.size).toBe(0);+ await act(async () => { await vi.advanceTimersByTimeAsync(60000); });+ expect(mockGetStatus).toHaveBeenCalledTimes(4);+});++it('keeps a successful save ahead of an older pending status response', async () => {+ showing();+ render(<AutoUpdatePanel />);+ await screen.findByLabelText(/origin\/main/);+ let finishOld;+ mockGetStatus.mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }));+ await act(async () => { handlers.get('system:activity')({}); });+ const saved = { ...status().config, channel: 'main' };+ mockPatch.mockResolvedValue({ autoUpdate: saved });+ mockGetStatus.mockReturnValue(status({ config: saved }));+ await userEvent.click(screen.getByLabelText(/origin\/main/));+ expect(screen.getByLabelText(/origin\/main/)).toBeChecked();+ await act(async () => { finishOld(status()); });+ expect(screen.getByLabelText(/origin\/main/)).toBeChecked();});diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex 4760a41b9b..bcc890bded 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -8,9 +8,11 @@ import AutoUpdatePanel from './AutoUpdatePanel';import * as api from '../../../services/api';import socket from '../../../services/socket';import { formatDateTime, formatDateNumeric, formatTimeOfDaySeconds } from '../../../utils/formatters';-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { useSocketResource } from '../../../hooks/useSocketResource';import { usePortosRestartWatch } from '../../../hooks/usePortosRestartWatch';+const STATUS_EVENTS = ['portos:update:checked', 'portos:update:available', 'portos:auto-update:changed', 'system:activity'];+const STEP_LABELS = {starting: 'Starting update','git-pull': 'Pulling latest changes',@@ -38,8 +40,9 @@ function StepIndicator({ status }) {}export default function UpdateTab() {- const [status, setStatus] = useState(null);- const [loading, setLoading] = useState(true);+ const { data: status, loading, refetch: fetchStatus, updateData: setStatus } = useSocketResource(+ () => api.getUpdateStatus({ silent: true }), { events: STATUS_EVENTS }+ );const [checking, setChecking] = useState(false);const [updating, setUpdating] = useState(false);const [steps, setSteps] = useState([]);@@ -59,17 +62,6 @@ export default function UpdateTab() {},});- const fetchStatus = useCallback(async () => {- const data = await api.getUpdateStatus().catch(() => null);- if (data) setStatus(data);- setLoading(false);- return data;- }, []);-- useEffect(() => {- fetchStatus();- }, [fetchStatus]);-// Step frames for the activity list. The restart handoff these frames end in// is the shared watch's job, not this component's.useEffect(() => {@@ -91,19 +83,6 @@ export default function UpdateTab() {}, []);- // Keep the status fresh while there's an update/reconcile surface on screen,- // so the agent block appears AND clears without a manual re-check: if an agent- // starts (from a schedule or another tab) while the buttons are showing, the- // next poll suppresses them; when the last agent finishes, it restores them.- // Gated to only run when there's something actionable (agents live, or an- // update/reconcile is available) and no update is already underway.- useAutoRefetch(fetchStatus, 4000, {- enabled: ((status?.activeCosAgents || 0) > 0 ||- !!status?.installState?.outOfSync ||- !!status?.updateAvailable) && !updating && !polling,- pollOnly: true- });-const handleCheck = async () => {setChecking(true);const result = await api.checkForUpdate().catch(() => null);@@ -113,8 +92,7 @@ export default function UpdateTab() {// `fromStatus` lets callers (e.g. handleSyncForkAndUpdate) pass the freshly// fetched status object instead of relying on the closure capture — `setStatus`- // only schedules a render and the awaited fetchStatus() return value is the- // single source of truth for the just-loaded state.+ // only schedules a render; the action passes its fresh response directly.const runUpdate = useCallback(async (opts = {}, fromStatus = null) => {const s = fromStatus || status;// Record the version and uptime of the still-running server, so even an@@ -158,7 +136,9 @@ export default function UpdateTab() {} else {toast.success(`Synced ${synced.fullName} from ${synced.source}`);}- const fresh = await fetchStatus();+ const fresh = await api.getUpdateStatus({ silent: true }).catch(() => null);+ if (!fresh) return;+ setStatus(fresh);await runUpdate(extraOpts, fresh);};diff --git a/client/src/components/apps/tabs/UpdateTab.test.jsx b/client/src/components/apps/tabs/UpdateTab.test.jsxindex 709692ea92..ea8326bbde 100644--- a/client/src/components/apps/tabs/UpdateTab.test.jsx+++ b/client/src/components/apps/tabs/UpdateTab.test.jsx@@ -29,6 +29,8 @@ vi.mock('../../../services/api', () => ({syncPortosFork: vi.fn(),}));+vi.mock('./AutoUpdatePanel', () => ({ default: () => null }));+const UpdateTab = (await import('./UpdateTab')).default;const OUT_OF_SYNC_STATUS = {@@ -270,11 +272,7 @@ describe('UpdateTab — active CoS agent suppression', () => {expect(screen.getByRole('button', { name: 'Sync Fork Only' })).toBeTruthy();});- it('suppresses restart buttons when an agent starts while the update surface is showing (4s poll)', async () => {- // Codex P2: tab loads with 0 agents and an available update, then a scheduled- // task (or another browser tab) starts an agent. The poll — enabled whenever- // there's an actionable update surface — picks it up and suppresses "Update- // Now" instead of leaving a button that 409s on click.+ it('suppresses restart buttons when an agent starts while the update surface is showing (activity event)', async () => {let agentCount = 0;mockGetUpdateStatus.mockReset().mockImplementation(async () => ({currentVersion: '2.24.0',@@ -286,28 +284,19 @@ describe('UpdateTab — active CoS agent suppression', () => {vi.useFakeTimers();render(<UpdateTab />);- // Initially updatable — button present, no notice.await act(async () => { await vi.advanceTimersByTimeAsync(0); });expect(screen.getByRole('button', { name: 'Update Now' })).toBeTruthy();expect(screen.queryByText(/Update paused/i)).toBeNull();- // An agent starts; the next poll observes it.agentCount = 1;- await act(async () => { await vi.advanceTimersByTimeAsync(4000); });+ await act(async () => { handlers.get('system:activity')({}); });vi.useRealTimers();expect(screen.queryByRole('button', { name: 'Update Now' })).toBeNull();expect(screen.getByText(/Update paused — CoS agents running/i)).toBeTruthy();});- it('auto-clears the paused notice when the last agent finishes (4s status poll)', async () => {- // Pins the notice's "this notice clears automatically" claim: while agents- // are live the tab polls status every 4s (useAutoRefetch), so when the last- // agent finishes the block lifts without the user re-checking.- // Fake timers must be active BEFORE render so they own the poll interval the- // effect schedules; and we drive re-renders with advanceTimersByTimeAsync- // (flushes microtasks) instead of findBy/waitFor, which use real timers and- // would hang against fake ones.+ it('auto-clears the paused notice when the last agent finishes (activity event)', async () => {let agentCount = 1;mockGetUpdateStatus.mockReset().mockImplementation(async () => ({...OUT_OF_SYNC_STATUS,@@ -316,17 +305,14 @@ describe('UpdateTab — active CoS agent suppression', () => {vi.useFakeTimers();render(<UpdateTab />);- // Flush the on-mount status fetch → blocked while the one agent runs.await act(async () => { await vi.advanceTimersByTimeAsync(0); });expect(screen.getByText(/Update paused — CoS agents running/i)).toBeTruthy();expect(screen.queryByRole('button', { name: 'Reconcile Now' })).toBeNull();- // The agent finishes; the next 4s poll observes activeCosAgents: 0.agentCount = 0;- await act(async () => { await vi.advanceTimersByTimeAsync(4000); });+ await act(async () => { handlers.get('system:activity')({}); });vi.useRealTimers();- // Notice cleared, reconcile action restored — no manual re-check needed.expect(screen.queryByText(/Update paused/i)).toBeNull();expect(screen.getByRole('button', { name: 'Reconcile Now' })).toBeTruthy();});@@ -360,3 +346,31 @@ describe('UpdateTab — last update log', () => {expect(pre.className).toContain('overflow-y-auto');});});++it('reads once per recovery, coalesces events, never polls, and releases listeners', async () => {+ vi.useFakeTimers();+ mockGetUpdateStatus.mockReset().mockResolvedValue(OUT_OF_SYNC_STATUS);+ const view = render(<UpdateTab />);+ await act(async () => {});+ expect(mockGetUpdateStatus).toHaveBeenCalledTimes(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(60000); });+ expect(mockGetUpdateStatus).toHaveBeenCalledTimes(1);+ await act(async () => {+ handlers.get('portos:update:checked')({});+ handlers.get('portos:auto-update:changed')({});+ });+ expect(mockGetUpdateStatus).toHaveBeenCalledTimes(2);+ await act(async () => { handlers.get('connect')(); });+ expect(mockGetUpdateStatus).toHaveBeenCalledTimes(3);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ document.dispatchEvent(new Event('visibilitychange'));+ });+ expect(mockGetUpdateStatus).toHaveBeenCalledTimes(4);+ view.unmount();+ expect(handlers.size).toBe(0);+ vi.useRealTimers();+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 1d2ccd3b68..bff178868c 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -54,7 +54,7 @@ export const undismissHealthWarning = (type, options = {}) => request(`/system/h});// Update-export const getUpdateStatus = () => request('/update/status');+export const getUpdateStatus = (options) => request('/update/status', options);export const checkForUpdate = () => request('/update/check', { method: 'POST' });// Automatic-update config + what the scheduler is currently waiting on. Its own// route because it walks git status, which /update/status must not do on thediff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 2ffd97d2d1..b834e0af9d 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -26,6 +26,11 @@ const input = (schema, summary) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'portos:auto-update:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate updater status after runtime, configuration or external git ref changes.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'brain:changed': {direction: 'server-to-client',summary: 'Invalidate Brain summary/settings after a persisted change.',diff --git a/server/routes/update.js b/server/routes/update.jsindex b33bba401d..67b267d9f7 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -56,8 +56,8 @@ router.get('/status', asyncHandler(async (req, res) => {// renders, from lib/systemIdle.js).//// Its OWN route rather than a block on /status, and the three service imports-// are deferred, for one reason each: /status is polled every few seconds while-// this tab is open and must not drag a git status walk along at that cadence,+// are deferred: activity invalidations of /status must not drag a git status+// walk into the cheaper update status read,// and a static import of the activity/readiness graph would pull the whole CoS// + git subtree into every suite that mounts this router (see "Import scoping"// in server/AGENTS.md). `sharedSchemas` is already in this module's static@@ -74,8 +74,7 @@ router.get('/auto', asyncHandler(async (req, res) => {]);const config = storableAutoUpdateConfig(settings?.autoUpdate);// The two expensive halves answer "what is the scheduler waiting for", which- // is not a question while the scheduler is off — and this route is polled- // every 15s by an open Update tab on an install where the feature ships OFF.+ // is not a question while the scheduler is off (the shipped default).// No fetch either way: refreshing origin refs is the scheduler's own tick,// not a network hop every viewer of this tab pays for.const [repo, processing] = config.enableddiff --git a/server/services/autoUpdateScheduler.js b/server/services/autoUpdateScheduler.jsindex 767ffe75e7..fdaccf8400 100644--- a/server/services/autoUpdateScheduler.js+++ b/server/services/autoUpdateScheduler.js@@ -34,6 +34,10 @@* one that can occur is the repair agent in step 4, which is itself switchable.*/+import { watch } from 'chokidar';+import { join, resolve } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { execGit } from '../lib/execGit.js';import { schedule, cancel } from './eventScheduler.js';import { getSettings, getSettingsWithStatus, settingsEvents } from './settings.js';import { getSystemActivity } from './activeProcessing.js';@@ -67,6 +71,43 @@ let corruptRetryTimer = null;// Update page sees the automatic run stream like any other.let ioRef = null;+// Payload-free invalidations: never broadcast configuration, repo paths or+// activity records. A short fixed window bounds bursts without starving reads.+let statusTimer = null;+let configSignature = null;+let repoWatcher = null;+let watcherStart = null;++function invalidateStatus() {+ if (!ioRef || statusTimer) return;+ statusTimer = setTimeout(() => {+ statusTimer = null;+ try {+ ioRef?.emit('portos:auto-update:changed', {});+ } catch (err) {+ console.error(`❌ Auto-update status notify failed: ${err.message}`);+ }+ }, 100);+ statusTimer.unref?.();+}++// Git operations performed outside PortOS have no service event. Watch only+// committed ref metadata, including worktree/common-dir layouts. Exclude index:+// git status itself can refresh it, which would make a read/notify feedback loop.+// Working-tree-only edits reconcile on activity, scheduler ticks and tab show.+async function watchRepoChanges() {+ const [{ stdout: gitDir }, { stdout: commonDir }] = await Promise.all([+ execGit(['rev-parse', '--absolute-git-dir'], PATHS.root),+ execGit(['rev-parse', '--git-common-dir'], PATHS.root),+ ]);+ const roots = [...new Set([gitDir.trim(), resolve(PATHS.root, commonDir.trim())])];+ repoWatcher = watch(roots.flatMap(root => [+ join(root, 'HEAD'), join(root, 'refs'), join(root, 'packed-refs'),+ ]), { ignoreInitial: true, persistent: false, ignored: /\.lock$/ });+ repoWatcher.on('all', invalidateStatus);+ repoWatcher.on('error', err => console.error(`❌ Auto-update repo watcher failed: ${err.message}`));+}+/*** When the clock for the minimum interval starts.*@@ -138,6 +179,7 @@ const failingRuntimeWrites = new Set();async function writeRuntime(patch, operation) {return updateChecker.recordAutoUpdateRuntime(patch).then(() => {+ invalidateStatus();if (failingRuntimeWrites.delete(operation)) {console.log(`✅ Auto-update runtime write recovered (${operation})`);}@@ -371,6 +413,11 @@ export async function syncAutoUpdateSchedule(settings) {}const current = settings;const config = resolveAutoUpdateConfig(current?.autoUpdate);+ const nextConfigSignature = JSON.stringify(config);+ if (configSignature !== nextConfigSignature) {+ configSignature = nextConfigSignature;+ invalidateStatus();+ }// Only the enabled flag shapes the REGISTRATION; the channel and the interval// are re-read inside the handler, so changing either takes effect on the next// tick without a re-register.@@ -436,13 +483,26 @@ settingsEvents.on('settings:invalidated', () => {* its progress to whoever is watching, then registers the poll if the feature* is on. Later enable/disable edits are picked up by the subscription above.*/-export function startAutoUpdateScheduler(io) {+export async function startAutoUpdateScheduler(io) {ioRef = io || null;+ if (!watcherStart) {+ watcherStart = watchRepoChanges().catch(err => {+ watcherStart = null;+ console.error(`❌ Auto-update repo watcher unavailable: ${err.message}`);+ });+ }+ await watcherStart;return syncAutoUpdateSchedule();}/** Test-only: drop the cached registration signature. */export function __resetAutoUpdateSchedulerForTests() {+ if (statusTimer) clearTimeout(statusTimer);+ statusTimer = null;+ configSignature = null;+ repoWatcher?.close();+ repoWatcher = null;+ watcherStart = null;registrationSignature = null;lastLoggedSkip = null;ioRef = null;diff --git a/server/services/autoUpdateScheduler.test.js b/server/services/autoUpdateScheduler.test.jsindex da46cab5b0..36cff5d7c0 100644--- a/server/services/autoUpdateScheduler.test.js+++ b/server/services/autoUpdateScheduler.test.js@@ -1,6 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const deps = vi.hoisted(() => ({+ watch: vi.fn(),+ git: vi.fn(),settings: vi.fn(),settingsWithStatus: vi.fn(),processing: vi.fn(),@@ -16,6 +18,9 @@ const deps = vi.hoisted(() => ({cancel: vi.fn(),}));+vi.mock('chokidar', () => ({ watch: deps.watch }));+vi.mock('../lib/execGit.js', () => ({ execGit: deps.git }));+vi.mock('./eventScheduler.js', () => ({ schedule: deps.schedule, cancel: deps.cancel }));vi.mock('./settings.js', () => ({getSettings: deps.settings,@@ -36,7 +41,7 @@ vi.mock('./updateChecker.js', () => ({recordAutoUpdateRuntime: deps.recordRuntime,}));-const { runAutoUpdateTick, syncAutoUpdateSchedule, updateBaselineAt, repairDispatchDue, __resetAutoUpdateSchedulerForTests } =+const { startAutoUpdateScheduler, runAutoUpdateTick, syncAutoUpdateSchedule, updateBaselineAt, repairDispatchDue, __resetAutoUpdateSchedulerForTests } =await import('./autoUpdateScheduler.js');const HOUR = 60 * 60 * 1000;@@ -533,3 +538,55 @@ describe('repair-dispatch cooldown', () => {expect(repairDispatchDue({}, MIN_INTERVAL_MS, Date.now())).toBe(true);});});+++describe('updater status invalidation', () => {+ afterEach(() => {+ __resetAutoUpdateSchedulerForTests();+ vi.useRealTimers();+ });++ it('coalesces persisted runtime/config changes and external refs without polling status', async () => {+ vi.useFakeTimers();+ const listeners = new Map();+ const watcher = { on: vi.fn((event, handler) => { listeners.set(event, handler); return watcher; }), close: vi.fn() };+ deps.watch.mockReturnValue(watcher);+ deps.git.mockResolvedValue({ stdout: '.git' });+ const io = { emit: vi.fn() };+ await startAutoUpdateScheduler(io);+ await vi.advanceTimersByTimeAsync(100);+ expect(io.emit).toHaveBeenCalledWith('portos:auto-update:changed', {});+ io.emit.mockClear();++ // A channel/interval edit must invalidate even though registration still+ // has enabled:true. An unrelated save must remain silent.+ const changed = { autoUpdate: { enabled: true, channel: 'main', minIntervalHours: 12 } };+ await syncAutoUpdateSchedule(changed);+ await syncAutoUpdateSchedule(changed);+ await vi.advanceTimersByTimeAsync(100);+ expect(io.emit).toHaveBeenCalledTimes(1);+ await syncAutoUpdateSchedule(changed);+ await vi.advanceTimersByTimeAsync(100);+ expect(io.emit).toHaveBeenCalledTimes(1);+ io.emit.mockClear();++ deps.gateState.mockResolvedValue({+ runtime: { armedAt: iso(Date.now()) }, lastUpdateResult: null, updateInProgress: false,+ });+ await runAutoUpdateTick();+ await runAutoUpdateTick();+ await vi.advanceTimersByTimeAsync(100);+ expect(io.emit).toHaveBeenCalledTimes(1);+ expect(deps.status).not.toHaveBeenCalled();+ expect(deps.readRepo).not.toHaveBeenCalled();+ io.emit.mockClear();++ listeners.get('all')('change', 'HEAD');+ listeners.get('all')('change', 'refs/heads/main');+ await vi.advanceTimersByTimeAsync(100);+ expect(io.emit).toHaveBeenCalledTimes(1);+ expect(deps.watch.mock.calls[0][0].every(path => !path.endsWith('index'))).toBe(true);+ __resetAutoUpdateSchedulerForTests();+ expect(watcher.close).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex 7b9382caeb..e43a20fa35 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -393,6 +393,7 @@ export async function ignoreVersion(version) {if (!state.ignoredVersions.includes(version)) {state.ignoredVersions.push(version);await saveState(state);+ noteSystemActivity('update', 'ignored');}return state;});@@ -406,6 +407,7 @@ export async function clearIgnored() {const state = await loadState();state.ignoredVersions = [];await saveState(state);+ noteSystemActivity('update', 'ignored-cleared');return state;});}