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
auto-update PortOS unattended, but only in a window where nothing is running
[._.]/ Adam Eivy72483ed40687
diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.jsxnew file mode 100644index 0000000000..ebeb957972--- /dev/null+++ b/client/src/components/apps/tabs/AutoUpdatePanel.jsx@@ -0,0 +1,205 @@+import { useEffect, 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 { formatDateTime, timeAgo } from '../../../utils/formatters';++// Why the updater is standing by, in the user's words rather than the+// scheduler's reason codes. The server sends both; only the detail is rendered+// free-form, and it is generated prose (counts and nouns), never record content.+const SKIP_LABELS = {+ cooldown: 'Waiting out the minimum interval',+ busy: 'Waiting for the system to go idle',+ 'repo-not-ready': 'Waiting on the checkout',+ 'up-to-date': 'Nothing to update to',+ 'update-in-progress': 'An update is already running',+ 'status-unavailable': 'Could not read the update status',+ 'activity-unknown': 'Could not read the activity snapshot',+ 'launch-failed': 'The last launch was refused',+};++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.' },+];++/**+ * Automatic updates — the configuration plus a live account of what the+ * scheduler is currently waiting for.+ *+ * The status half is deliberately verbose: an unattended updater that simply+ * never runs is indistinguishable from a broken one, so every gate it is+ * 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 config = status?.config;+ const runtime = status?.runtime;+ const repo = status?.repo;+ const activity = status?.activity;+ const [draft, setDraft] = useState(config || null);+ const [saving, setSaving] = useState(false);++ // Re-seed from the server whenever it sends a different effective config, so+ // a change made on another screen (or another device) is not overwritten by a+ // stale draft the next time this one saves.+ useEffect(() => {+ if (config) setDraft((prev) => (prev && JSON.stringify(prev) === JSON.stringify(config) ? prev : config));+ }, [config]);++ if (!draft) return null;++ const save = async (patch) => {+ const next = { ...draft, ...patch };+ setDraft(next);+ setSaving(true);+ const saved = await api.patchSettingsSlice('autoUpdate', next).catch((err) => {+ toast.error(`Could not save automatic updates: ${err.message}`);+ return null;+ });+ setSaving(false);+ if (!saved) {+ setDraft(config);+ return;+ }+ refetch?.();+ };++ const blockers = activity?.blockers || [];+ const skip = runtime?.lastSkip;++ return (+ <div className="p-4 rounded-lg border border-port-border bg-port-card">+ <div className="flex items-start justify-between gap-3">+ <div>+ <div className="text-sm text-white font-medium flex items-center gap-2">+ <Clock size={15} className="text-port-accent" /> Automatic updates+ </div>+ <div className="text-xs text-gray-400 mt-1">+ Runs the update for you — but only once the install is completely idle: no render running or queued,+ no CoS agent, no Persistent Mind turn, no app operation.+ </div>+ </div>+ <label className="flex items-center gap-2 text-xs text-gray-300 shrink-0" htmlFor="auto-update-enabled">+ <input+ id="auto-update-enabled"+ type="checkbox"+ checked={draft.enabled}+ disabled={saving}+ onChange={(e) => save({ enabled: e.target.checked })}+ className="h-4 w-4 accent-port-accent"+ />+ {draft.enabled ? 'On' : 'Off'}+ {saving ? <Loader size={12} className="animate-spin text-port-accent" /> : null}+ </label>+ </div>++ {draft.enabled && (+ <div className="mt-4 space-y-4">+ <fieldset>+ <legend className="text-xs text-gray-500 uppercase tracking-wide mb-2">Update from</legend>+ <div className="flex flex-col gap-2 sm:flex-row">+ {CHANNELS.map(({ id, label, icon: Icon, hint }) => (+ <label+ key={id}+ htmlFor={`auto-update-channel-${id}`}+ className={`flex-1 cursor-pointer rounded-lg border p-3 ${draft.channel === id ? 'border-port-accent/60 bg-port-accent/5' : 'border-port-border bg-port-bg'}`}+ >+ <span className="flex items-center gap-2 text-sm text-white">+ <input+ id={`auto-update-channel-${id}`}+ type="radio"+ name="auto-update-channel"+ value={id}+ checked={draft.channel === id}+ disabled={saving}+ onChange={() => save({ channel: id })}+ className="accent-port-accent"+ />+ <Icon size={14} className="text-gray-400" /> {label}+ </span>+ <span className="mt-1 block text-xs text-gray-400">{hint}</span>+ </label>+ ))}+ </div>+ </fieldset>++ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <label htmlFor="auto-update-interval" className="text-sm text-gray-300">+ Wait at least+ </label>+ <input+ id="auto-update-interval"+ type="number"+ min={1}+ max={720}+ value={draft.minIntervalHours}+ disabled={saving}+ onChange={(e) => setDraft({ ...draft, minIntervalHours: Number(e.target.value) })}+ onBlur={(e) => {+ const hours = Math.min(720, Math.max(1, Number(e.target.value) || 1));+ if (hours !== config.minIntervalHours) save({ minIntervalHours: hours });+ }}+ className="w-24 px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white"+ />+ <span className="text-sm text-gray-300">hours after the last update before looking for a window.</span>+ </div>++ <label className="flex items-start gap-2 text-xs text-gray-300" htmlFor="auto-update-agent">+ <input+ id="auto-update-agent"+ type="checkbox"+ checked={draft.resolveBlockersWithAgent}+ disabled={saving}+ onChange={(e) => save({ resolveBlockersWithAgent: e.target.checked })}+ className="mt-0.5 h-4 w-4 accent-port-accent"+ />+ <span>+ <span className="text-gray-200">Queue a CoS agent when the checkout needs judgement.</span>+ <span className="block text-gray-500">+ Switching to the default branch and restoring auto-generated lockfiles happens without one.+ Uncommitted work, an unpushed commit, or an interrupted rebase does not — that queues an agent to resolve it.+ </span>+ </span>+ </label>++ <div className="rounded-lg border border-port-border bg-port-bg p-3 space-y-2">+ <div className="text-xs text-gray-500 uppercase tracking-wide">Right now</div>+ {repo && !repo.ready ? (+ <div className="flex items-start gap-2 text-xs text-port-warning">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />+ <span>+ Checkout not ready — {repo.summary || `on ${repo.branch || 'an unknown branch'}, expected a clean ${repo.defaultBranch || 'default branch'}`}.+ {repo.needsAgent && draft.resolveBlockersWithAgent ? ' A CoS agent is queued to resolve it.' : ''}+ </span>+ </div>+ ) : null}+ {activity ? (+ <div className="flex items-start gap-2 text-xs">+ {activity.idle+ ? <><Check size={13} className="mt-0.5 shrink-0 text-port-success" /><span className="text-gray-300">System is idle.</span></>+ : <><Bot size={13} className="mt-0.5 shrink-0 text-port-accent" /><span className="text-gray-300">Busy: {blockers.map(b => b.label).join(', ')}.</span></>}+ </div>+ ) : null}+ {skip ? (+ <div className="text-xs text-gray-400">+ {SKIP_LABELS[skip.reason] || skip.reason}+ {skip.detail ? ` — ${skip.detail}` : ''}+ {skip.at ? ` (checked ${timeAgo(skip.at)})` : ''}+ </div>+ ) : null}+ {runtime?.lastRunAt ? (+ <div className="text-xs text-gray-500">Last automatic run started {formatDateTime(runtime.lastRunAt)}.</div>+ ) : (+ <div className="text-xs text-gray-500">No automatic update has run yet.</div>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.test.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.test.jsxnew file mode 100644index 0000000000..a33cbce769--- /dev/null+++ b/client/src/components/apps/tabs/AutoUpdatePanel.test.jsx@@ -0,0 +1,74 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { 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 status = (overrides = {}) => ({+ config: { enabled: true, channel: 'release', minIntervalHours: 6, resolveBlockersWithAgent: true },+ runtime: { lastRunAt: null, lastSkip: null },+ repo: { ready: true, branch: 'main', defaultBranch: 'main' },+ activity: { idle: true, blockers: [] },+ ...overrides,+});+const showing = (overrides) => mockGetStatus.mockReturnValue(status(overrides));++beforeEach(() => {+ mockPatch.mockReset();+ mockGetStatus.mockReset();+ mockPatch.mockResolvedValue({});+});++describe('AutoUpdatePanel', () => {+ it('renders nothing until the server has sent an effective config', () => {+ mockGetStatus.mockReturnValue(undefined);+ const { container } = render(<AutoUpdatePanel />);+ 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 }));+ });++ // An unattended updater that simply never runs is indistinguishable from a+ // broken one, so whatever gate it is sitting behind has to be on screen.+ it('says what the scheduler is waiting for', async () => {+ showing({+ activity: { idle: false, blockers: [{ kind: 'media-queued:video', label: '2 video renders queued', count: 2 }] },+ 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(screen.getByText(/Waiting for the system to go idle/)).toBeInTheDocument();+ });++ it('surfaces a checkout that is not ready to update', () => {+ 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(screen.getByText(/A CoS agent is queued to resolve it/)).toBeInTheDocument();+ });++ it('hides the configuration while the feature is off', () => {+ showing({+ config: { enabled: false, channel: 'release', minIntervalHours: 6, resolveBlockersWithAgent: true },+ });+ render(<AutoUpdatePanel />);+ expect(screen.queryByLabelText(/origin\/main/)).not.toBeInTheDocument();+ expect(screen.getByLabelText(/Off/)).toBeInTheDocument();+ });+});diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex 7b7e63aef1..4760a41b9b 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -4,6 +4,7 @@ import toast from '../../ui/Toast';import BrailleSpinner from '../../BrailleSpinner';import MarkdownOutput from '../../cos/MarkdownOutput';import Banner from '../../ui/Banner';+import AutoUpdatePanel from './AutoUpdatePanel';import * as api from '../../../services/api';import socket from '../../../services/socket';import { formatDateTime, formatDateNumeric, formatTimeOfDaySeconds } from '../../../utils/formatters';@@ -499,6 +500,9 @@ export default function UpdateTab() {<Banner tone="error" size="md" icon={AlertTriangle}>{updateError}</Banner>)}+ {/* Automatic updates — configuration plus what the scheduler is waiting on */}+ <AutoUpdatePanel />+{/* Last Update Result */}{status?.lastUpdateResult && (<div>diff --git a/client/src/components/dashboard/ActiveProcessingWidget.jsx b/client/src/components/dashboard/ActiveProcessingWidget.jsxindex 23bbc58a0c..1bf4a8a656 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.jsx@@ -1,6 +1,6 @@import { memo } from 'react';import { Link } from 'react-router';-import { AudioLines, Bot, Cpu, ExternalLink, Film, Image as ImageIcon, Layers3, X } from 'lucide-react';+import { AudioLines, Bot, Brain, Cpu, ExternalLink, Film, Image as ImageIcon, Layers3, Package, X } from 'lucide-react';import * as api from '../../services/api';import { useAutoRefetch } from '../../hooks/useAutoRefetch';@@ -19,6 +19,10 @@ export const sameProcessingSnapshot = (a, b) => {&& a.gpu?.status === b.gpu?.status&& a.gpu?.laneBusy === b.gpu?.laneBusy&& a.gpu?.gpus?.[0]?.utilizationPercent === b.gpu?.gpus?.[0]?.utilizationPercent+ && a.mind?.thinking === b.mind?.thinking+ && a.mind?.queued === b.mind?.queued+ && a.mind?.status === b.mind?.status+ && (a.appOperations || []).length === (b.appOperations || []).length&& a.jobs?.length === b.jobs?.length&& (a.extras?.imageTo3d || []).length === (b.extras?.imageTo3d || []).length&& (a.jobs || []).every((job, index) => job?.id === b.jobs[index]?.id@@ -57,6 +61,31 @@ function JobRow({ job, onCancel }) {);}+/** A non-cancellable lane (mind, agents, app operations, 3D) as one linked row. */+function LaneRow({ to, icon: Icon, label, detail }) {+ return (+ <Link to={to} className="mt-1.5 flex items-center gap-2 rounded-lg border border-port-border bg-port-bg/60 px-2.5 py-2 text-xs text-gray-300 hover:border-port-accent/50">+ <Icon size={14} className="text-port-accent" />+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {detail ? <span className="shrink-0 font-mono text-gray-500">{detail}</span> : null}+ <ExternalLink size={13} className="shrink-0 text-gray-500" />+ </Link>+ );+}++// `activity` is derived server-side (server/lib/systemIdle.js) so the widget and+// the unattended auto-updater cannot disagree about what "idle" means — one of+// them renders the verdict, the other refuses to restart the install on it.+// The local fallback covers a snapshot from a peer/older server that predates it.+const localActivity = (data) => {+ const jobs = data?.jobs || [];+ const running = jobs.filter((job) => job.status !== 'queued').length + (data?.extras?.imageTo3d || []).length+ + (data?.agents?.active || 0) + (data?.mind?.thinking ? 1 : 0) + (data?.appOperations || []).length;+ const queued = jobs.length - jobs.filter((job) => job.status !== 'queued').length+ + (data?.agents?.queued || 0) + (data?.mind?.queued || 0);+ return { idle: running === 0 && queued === 0, activeCount: running, queuedCount: queued, blockers: [] };+};+function ActiveProcessingWidget() {const { data } = useAutoRefetch(() => api.getActiveProcessing({ silent: true }), 3000, {compare: sameProcessingSnapshot,@@ -65,21 +94,44 @@ function ActiveProcessingWidget() {const jobs = data?.jobs || [];const gpu = data?.gpu;const imageTo3d = data?.extras?.imageTo3d || [];+ const mind = data?.mind;+ const appOperations = data?.appOperations || [];const activeAgents = data?.agents?.active || 0;- const activeCount = jobs.length + imageTo3d.length + activeAgents;- const idle = activeCount === 0;+ const activity = data ? (data.activity || localActivity(data)) : null;+ const idle = !activity || activity.idle;+ const runningJobs = jobs.filter((job) => job.status !== 'queued').length;return (- <div className="h-full rounded-xl border border-port-border bg-port-card p-4">+ // @container on the widget's OWN root: a dashboard cell is ~250px wide on a+ // 2560px screen, so a viewport breakpoint here would pin the four-up metric+ // row into the narrowest column. See the dashboard AGENTS.md.+ <div className="@container h-full rounded-xl border border-port-border bg-port-card p-4"><div className="mb-3 flex items-start justify-between gap-3"><div><h3 className="flex items-center gap-2 text-sm font-semibold text-white"><span className={`relative flex h-6 w-6 items-center justify-center rounded-lg ${idle ? 'bg-port-border/60 text-gray-400' : 'bg-port-accent/15 text-port-accent'}`}><Cpu size={15} />{!idle ? <span className="absolute -right-0.5 -top-0.5 h-2 w-2 animate-ping rounded-full bg-port-accent" /> : null}</span> Live activity</h3><p className="mt-1 text-[11px] text-gray-500">What PortOS is working on right now</p></div>- <span className={`rounded-full px-2 py-1 text-[10px] font-medium uppercase tracking-wider ${idle ? 'bg-port-border/60 text-gray-500' : 'bg-port-accent/15 text-port-accent'}`}>{idle ? 'idle' : `${activeCount} active`}</span>+ <span className={`rounded-full px-2 py-1 text-[10px] font-medium uppercase tracking-wider ${idle ? 'bg-port-border/60 text-gray-500' : 'bg-port-accent/15 text-port-accent'}`}>{idle ? 'idle' : `${activity.activeCount} active${activity.queuedCount ? ` · ${activity.queuedCount} queued` : ''}`}</span></div>{!data ? <p className="text-xs text-gray-500">Checking render lanes…</p> : <>- {!idle ? <div className="mb-3 grid grid-cols-3 gap-1.5 text-center"><Metric icon={Bot} value={activeAgents} label="agents" /><Metric icon={Layers3} value={jobs.length} label="media" /><Metric icon={Cpu} value={gpu?.laneBusy ? 'busy' : 'ready'} label="GPU" /></div> : null}+ {!idle ? <div className="mb-3 grid grid-cols-2 gap-1.5 text-center @xs:grid-cols-4"><Metric icon={Bot} value={activeAgents} label="agents" /><Metric icon={Layers3} value={runningJobs} label="rendering" /><Metric icon={Brain} value={mind?.thinking ? 'yes' : 'no'} label="thinking" /><Metric icon={Cpu} value={gpu?.laneBusy ? 'busy' : 'ready'} label="GPU" /></div> : null}{idle ? <Link to="/system-resources/overview" className="flex items-center justify-between rounded-lg border border-port-border bg-port-bg px-3 py-3 text-xs text-gray-400 transition-colors hover:border-port-accent/50 hover:text-gray-200"><span>Nothing is running</span><span>GPU {gpu?.status === 'available' ? 'ready' : gpu?.status || 'unknown'} →</span></Link> : null}<div className="space-y-1.5">{jobs.map((job) => <JobRow key={job.id} job={job} onCancel={cancel} />)}</div>- {imageTo3d.map((item) => <Link key={`3d-${item.id}`} to="/3d" className="mt-1.5 flex items-center gap-2 rounded-lg border border-port-border bg-port-bg/60 px-2.5 py-2 text-xs text-gray-300 hover:border-port-accent/50"><Layers3 size={14} className="text-port-accent" /><span className="min-w-0 flex-1 truncate">Image-to-3D · {item.name}</span><ExternalLink size={13} className="text-gray-500" /></Link>)}- {activeAgents ? <Link to="/cos/agents" className="mt-1.5 flex items-center gap-2 rounded-lg border border-port-border bg-port-bg/60 px-2.5 py-2 text-xs text-gray-300 hover:border-port-accent/50"><Bot size={14} className="text-port-accent" /><span className="min-w-0 flex-1">Chief of Staff agents</span><span className="font-mono text-gray-500">{activeAgents} active{data.agents.queued ? ` · ${data.agents.queued} queued` : ''}</span><ExternalLink size={13} className="text-gray-500" /></Link> : null}+ {imageTo3d.map((item) => <LaneRow key={`3d-${item.id}`} to="/3d" icon={Layers3} label={`Image-to-3D · ${item.name}`} />)}+ {/* Counts and lifecycle only — never what the mind is thinking ABOUT. */}+ {mind?.thinking || mind?.queued ? (+ <LaneRow+ to="/cos/mind"+ icon={Brain}+ label={mind.thinking ? 'Persistent Mind is thinking' : 'Persistent Mind has queued work'}+ detail={[mind.thinking ? elapsed(mind.thinkingSince) : null, mind.queued ? `${mind.queued} queued` : null].filter(Boolean).join(' · ')}+ />+ ) : null}+ {activeAgents || data.agents?.queued ? (+ <LaneRow+ to="/cos/agents"+ icon={Bot}+ label="Chief of Staff agents"+ detail={`${activeAgents} active${data.agents.queued ? ` · ${data.agents.queued} queued` : ''}`}+ />+ ) : null}+ {appOperations.map((op) => <LaneRow key={`op-${op.appId}-${op.type}`} to="/apps" icon={Package} label={`${op.appName} · ${op.type}`} />)}{!idle && gpu?.status === 'available' && gpu.gpus?.length ? <div className="mt-3 text-[11px] text-gray-500">GPU {gpu.gpus[0]?.utilizationPercent == null ? 'utilization unknown' : `${Math.round(gpu.gpus[0]?.utilizationPercent)}% utilized`}</div> : null}</>}</div>diff --git a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx b/client/src/components/dashboard/ActiveProcessingWidget.test.jsxindex deb23c529b..2db51e4502 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.test.jsx@@ -43,9 +43,12 @@ describe('ActiveProcessingWidget', () => {],extras: { imageTo3d: [{ id: 'model-1', name: 'Example mesh' }] },agents: { active: 2, queued: 1 },+ mind: { trusted: true, thinking: false, queued: 0 },});renderWidget();- expect(screen.getByText('5 active')).toBeInTheDocument();+ // Running and queued are counted separately now: a queued render is real+ // work waiting on the user, not part of the "active" tally.+ expect(screen.getByText('4 active · 2 queued')).toBeInTheDocument();expect(screen.getByText('Example image')).toBeInTheDocument();expect(screen.getByText('Example track')).toBeInTheDocument();expect(screen.getByRole('link', { name: 'Open image activity' })).toHaveAttribute('href', '/media/image');@@ -54,6 +57,35 @@ describe('ActiveProcessingWidget', () => {expect(screen.getByText('50%')).toBeInTheDocument();});+ // Counts and lifecycle only — the widget must never render what the mind is+ // thinking about, and the snapshot never carries it.+ it('surfaces a thinking Persistent Mind as its own lane', () => {+ mockGetActiveProcessing.mockReturnValue({+ gpu: { status: 'available' },+ jobs: [],+ extras: {},+ agents: {},+ mind: { trusted: true, thinking: true, queued: 2, thinkingSince: new Date().toISOString() },+ activity: { idle: false, activeCount: 1, queuedCount: 2, blockers: [{ kind: 'mind-thinking', label: 'Persistent Mind is thinking', count: 1 }] },+ });+ renderWidget();+ expect(screen.getByRole('link', { name: /Persistent Mind is thinking/ })).toHaveAttribute('href', '/cos/mind');+ expect(screen.getByText('1 active · 2 queued')).toBeInTheDocument();+ });++ it('shows a running app operation as activity', () => {+ mockGetActiveProcessing.mockReturnValue({+ gpu: { status: 'available' },+ jobs: [],+ extras: {},+ agents: {},+ appOperations: [{ appId: 'example', appName: 'Example App', type: 'update' }],+ activity: { idle: false, activeCount: 1, queuedCount: 0, blockers: [{ kind: 'app-operations', label: '1 app operation running', count: 1 }] },+ });+ renderWidget();+ expect(screen.getByRole('link', { name: /Example App · update/ })).toHaveAttribute('href', '/apps');+ });+it('cancels a live job from its row', async () => {mockGetActiveProcessing.mockReturnValue({gpu: { status: 'available' },diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 8c81df764e..df7135b428 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -50,6 +50,10 @@ export const undismissHealthWarning = (type, options = {}) => request(`/system/h// Updateexport const getUpdateStatus = () => request('/update/status');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 the+// Update tab's poll interval.+export const getAutoUpdateStatus = (options) => request('/update/auto', options);export const ignoreUpdateVersion = (version) => request('/update/ignore', {method: 'POST',body: JSON.stringify({ version })diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.mdindex 3237540f3a..da7f1210e1 100644--- a/docs/SELF_UPDATE.md+++ b/docs/SELF_UPDATE.md@@ -2,7 +2,7 @@How PortOS notices a new release and updates itself. PortOS is distributed software — many people run it, and a large share run it from a **personal fork**, so every step here is fork-aware. Breaking that assumption produces silent no-op updates.-Code: `server/services/updateChecker.js`, `server/services/portosSelfUpdate.js`, `server/services/updateExecutor.js`, `server/services/appUpdater.js`, `server/routes/update.js`, `server/lib/gitRemote.js`, `server/lib/detachedSpawn.js`, `update.sh` / `update.ps1`, `scripts/verify-server-health.js`, `client/src/components/apps/tabs/UpdateTab.jsx`, `client/src/hooks/usePortosRestartWatch.js`, `client/src/hooks/useAppOperation.js`.+Code: `server/services/updateChecker.js`, `server/services/portosSelfUpdate.js`, `server/services/updateExecutor.js`, `server/services/appUpdater.js`, `server/routes/update.js`, `server/lib/gitRemote.js`, `server/lib/detachedSpawn.js`, `update.sh` / `update.ps1`, `scripts/verify-server-health.js`, `client/src/components/apps/tabs/UpdateTab.jsx`, `client/src/hooks/usePortosRestartWatch.js`, `client/src/hooks/useAppOperation.js`. The unattended, idle-gated variant is a section of its own below.## Release polling always targets upstream@@ -112,6 +112,76 @@ The probe tries the loopback HTTP mirror (`:5553`) first, then the API port over**When the probe still fails after the recovery, the scripts say so and exit non-zero** — the closing banner reads "Update applied, but PortOS is DOWN" instead of "Update Complete". The script outlives the server it restarts, so its exit status and the tail of `data/update.log` are the only signals a wrapper, a CI job, or an operator still has; printing a success banner over a confirmed-headless install is how the failure went unnoticed for hours in the first place.+## Automatic updates (unattended, idle-gated)++OFF by default. **Update tab → Automatic updates** turns it on; the config lives in+`settings.autoUpdate` and resolves through `resolveAutoUpdateConfig` in+`server/lib/sharedSchemas.js` (the schema, the scheduler, and the settings GET all read+that one resolver, so a sparse slice cannot mean different things to different readers).++Code: `server/services/autoUpdateScheduler.js`, `server/services/updateRepoReadiness.js`,+`server/lib/systemIdle.js`, `server/services/appUpdateRunner.js`,+`client/src/components/apps/tabs/AutoUpdatePanel.jsx`, `GET /api/update/auto`.++**It runs the SAME action the matching button runs, through the same service.** There is no+second update implementation, so every preflight refusal, the update lock, and the+never-await-the-launcher rule apply unchanged:++| Channel | Dispatches | Equivalent to |+|---|---|---|+| `release` | `startPortosSelfUpdate({ mode: 'release' })` | Update page → "Update Now" |+| `main` | `runAppUpdate({ appId: PORTOS_APP_ID })` | App Management → Git tab → "Update app" |++`runAppUpdate` is the extracted body of the `app:update` socket handler (claim → PortOS+preflight → `appUpdater.updateApp` → ledger row → apps-changed broadcast); the socket+handler now only routes the two refusals that belong to the person who clicked.++### Every gate must pass on the same tick++A 5-minute interval poll (`eventScheduler`, id `portos-auto-update`, registered only while+the feature is on) checks, in order:++1. **Cooldown** — `minIntervalHours` (default 6) since the last update. The baseline is the+ most recent of the scheduler's own `lastRunAt`, the last recorded update result (so a+ MANUAL update also resets the clock), and the `armedAt` stamped on the first tick after+ the feature was switched on. `lastRunAt` is written at the LAUNCH, not at a completion+ this process does not live to see — `update.sh` pm2-deletes the server partway through,+ and without that stamp the restarted server would find the interval elapsed and fire a+ second update.+2. **Something to update to** — a newer release tag (`release`), or origin's default branch+ ahead of this checkout / `installState.outOfSync` (`main`). Nothing to do is a no-op.+3. **Checkout readiness** (`updateRepoReadiness.js`) — see below.+4. **System idle** (`lib/systemIdle.js`) — no render running **or queued**, no CoS agent or+ queued task, no Persistent Mind turn or queued message, no app operation, no update+ already in flight. An unreadable Persistent Mind state counts as busy, matching the+ update path's own `PERSISTENT_MIND_STATE_UNTRUSTED` refusal.++`summarizeSystemActivity` is the ONE definition of idle: the dashboard's Live activity+widget renders the verdict the updater refuses on, so the two cannot disagree about a+window in which PortOS may restart itself. Every skip is recorded to+`data/update.json` (`autoUpdate.lastSkip`) and rendered in the panel — an unattended+updater that simply never runs is otherwise indistinguishable from a broken one.++### Checkout readiness: repair mechanically, escalate judgement++Both update paths MOVE the checkout (`update.sh` switches to `main` and stashes;+`updateDefaultBranch` checks out, fast-forwards, then falls back to `pull --rebase+--autostash`). Unattended, a stash nobody is told about reads as lost work. So the updater+refuses until the checkout is on the default branch and clean.++Two remedies run without asking, because neither can destroy work:++- **switch to the default branch** from a CLEAN feature branch (the commits stay on the+ branch ref), and+- **restore modified auto-generated lockfiles** (`npm install` rewrites them; the update+ reinstalls anyway). Restored by explicit path, never `-- .`.++Everything else — uncommitted work, a local commit not on origin, an interrupted+rebase/merge, conflict markers — queues ONE high-priority CoS task (deduped on a constant+first line, `useWorktree: false`) and waits. That agent then counts as activity, so the+update lands in the first idle window after it finishes. The escalation is switchable+(`resolveBlockersWithAgent`), since it costs a provider call.+## Syncing a fork`POST /api/update/sync-fork` shells out to:diff --git a/server/lib/README.md b/server/lib/README.mdindex d47afcd332..f299c6056b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -32,7 +32,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. || `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. || `taskDataInputCatalog.js` | Pure catalog and persisted ids for deterministic context sources that scheduled agent tasks can preload before dispatch. |-| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): `anchorUserExclude` / `anchorUserExcludes` prepend the rsync root anchor (`/`) to any user pattern that is not already anchored and is not deliberately `*`/`**`-led, and `isSafeExcludePattern` (defined as `anchorUserExclude(x) !== null`, so the two can never disagree) rejects a `..` segment, a NUL, or a pattern longer than `EXCLUDE_PATTERN_MAX_LENGTH` once anchored — one rule shared by `backupConfigSchema` and `services/backup.js#computeEffectiveExcludes`, since an unanchored `cache/` is an rsync filter that matches at EVERY depth. Mirrored to `client/src/lib/backupExcludes.js`. |+| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): `anchorUserExclude` / `anchorUserExcludes` prepend the rsync root anchor (`/`) to any user pattern that is not already anchored and is not deliberately `*`/`**`-led, and `isSafeExcludePattern` (defined as `anchorUserExclude(x) !== null`, so the two can never disagree) rejects a `..` segment, a NUL, or a pattern longer than `EXCLUDE_PATTERN_MAX_LENGTH` once anchored — one rule shared by `backupConfigSchema` and `services/backup.js#computeEffectiveExcludes`, since an unanchored `cache/` is an rsync filter that matches at EVERY depth. Mirrored to `client/src/lib/backupExcludes.js`. Also `resolveAutoUpdateConfig(settings.autoUpdate)` + the channel/interval constants — same sparse-slice rule for the automatic self-update: omitted `enabled` means OFF, omitted `channel` means `release`, `minIntervalHours` clamps into `[1, 720]`, `resolveBlockersWithAgent` defaults on — shared by `autoUpdateSettingsSchema`, `services/autoUpdateScheduler.js`, and the settings GET projection. || `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets) plus `mediaJobExecutionLane({ kind, mode, remote })` / `MEDIA_JOB_EXECUTION_LANES` — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules. || `imageGenCapabilities.js` | Per-backend image-gen capability literals, a dependency-free leaf beside `generationModes.js`: `EDIT_INCAPABLE_IMAGE_MODES`/`isEditCapableMode` and the derived `I2I_CAPABLE_MODES`, the shipped defaults (`CODEX_IMAGEGEN_DEFAULT_MODEL`/`_EFFORT`, `AGY_IMAGEGEN_DEFAULT_MODEL`, `AGY_IMAGEGEN_IMAGE_MODEL`), the `AGY_`/`GROK_ASPECT_RATIOS` alphabets, and `IMAGE_GEN_PROVIDER_CAPABILITIES` (`supportsModelOverride`, `maxInputImages`, `promptRequiredWithInputImage`) with its `supportsCloudModelOverride`/`maxInputImages`/`cloudPromptRequired` readers. The `services/imageGen/*` modules re-export these, and `client/src/lib/imageGenModes.js` imports them instead of copying them (#6590). || `imageRuntimeRemedies.js` | Local image-runtime vocabulary, a dependency-free leaf beside `imageGenCapabilities.js`: `IMAGE_RUNTIME_READINESS` (ready/unavailable/unknown), `IMAGE_RUNTIME` + `IMAGE_RUNTIME_LABELS` (the shared torch venv vs. the configurable mflux interpreter), `IMAGE_RUNTIME_REMEDY` (the one action that fixes each unavailable state), and `IMAGE_RUNTIME_UNAVAILABLE_CODE`. `services/imageGen/localRuntime.js` builds the diagnosis from these, `services/imageGen/local.js` tags its pre-flight render refusal with the same remedy, and `client/src/lib/imageGenModes.js` re-exports them so no component hand-copies a remedy kind. |@@ -529,6 +529,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| Module | Purpose ||---|---|| `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. |+| `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. || `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. || `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. || `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` / cached `getCudaComputeCapability()` are a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH` and SGLang provider filtering; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e787ea3e1b..4c2e347bcd 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -517,6 +517,7 @@ export * from './vaultCrypto.js';// === Model & config ===export * from './backupConfig.js';+export * from './systemIdle.js';export * from './browserConfig.js';export * from './buildId.js';export * from './buildIdentity.js';diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.jsindex c664c4f6e0..2f22a5eec3 100644--- a/server/lib/sharedSchemas.js+++ b/server/lib/sharedSchemas.js@@ -188,3 +188,59 @@ export function anchorUserExcludes(patterns) {const list = Array.isArray(patterns) ? patterns : [];return [...new Set(list.map(anchorUserExclude).filter(Boolean))];}++// ── Automatic PortOS self-update (Update tab) ───────────────────────────────+//+// The EFFECTIVE configuration, resolved from the sparse `settings.autoUpdate`+// slice. Sparse because the settings store keeps what the user actually set: an+// install that only ever ticked the checkbox stores `{ enabled: true }`, and+// every reader has to agree on what the omitted fields mean. One resolver, read+// by `autoUpdateSettingsSchema` at the PUT boundary, by+// `services/autoUpdateScheduler.js`, and by the settings GET projection — so an+// omitted `channel` can never mean `release` in one and `main` in another. Same+// rule, and the same home, as the backup-exclude anchoring above (#6632 is the+// lesson from getting it wrong for the backup schedule).++/**+ * Which update action the scheduler performs. Each is EXACTLY the action a+ * button already performs, dispatched through the same service:+ *+ * - `release` — the Update page's "Update Now": `startPortosSelfUpdate` in+ * `release` mode, gated on a newer GitHub release tag.+ * - `main` — App Management's Git tab "Update app" for the PortOS record:+ * `runAppUpdate`, which advances the checkout onto origin's default branch+ * and then runs the same update script. Gated on origin actually being+ * ahead, so it does not reinstall the same revision every interval.+ */+export const AUTO_UPDATE_CHANNELS = ['release', 'main'];+export const DEFAULT_AUTO_UPDATE_CHANNEL = 'release';+/** Hours to wait after the last update before starting to look for a window. */+export const DEFAULT_AUTO_UPDATE_MIN_INTERVAL_HOURS = 6;+export const AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN = 1;+export const AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX = 24 * 30;++/**+ * @param {object} [raw] - the stored `settings.autoUpdate` slice.+ * @returns {{enabled: boolean, channel: 'release'|'main', minIntervalHours: number, minIntervalMs: number, resolveBlockersWithAgent: boolean}}+ */+export function resolveAutoUpdateConfig(raw) {+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const channel = AUTO_UPDATE_CHANNELS.includes(source.channel) ? source.channel : DEFAULT_AUTO_UPDATE_CHANNEL;+ const requested = Number(source.minIntervalHours);+ const minIntervalHours = Number.isFinite(requested)+ ? Math.min(AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX, Math.max(AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN, requested))+ : DEFAULT_AUTO_UPDATE_MIN_INTERVAL_HOURS;+ return {+ // OFF unless explicitly on. An install that has never seen this feature must+ // not start restarting itself because it upgraded into the code.+ enabled: source.enabled === true,+ channel,+ minIntervalHours,+ minIntervalMs: minIntervalHours * 60 * 60 * 1000,+ // Whether a checkout that no script may safely repair (uncommitted work, an+ // interrupted rebase) queues a CoS agent to resolve it. Defaults ON because+ // an unattended updater that silently stops forever is worse than one that+ // asks for help — but it is a switch, since that help costs a provider call.+ resolveBlockersWithAgent: source.resolveBlockersWithAgent !== false,+ };+}diff --git a/server/lib/systemIdle.js b/server/lib/systemIdle.jsnew file mode 100644index 0000000000..ae4ee5819f--- /dev/null+++ b/server/lib/systemIdle.js@@ -0,0 +1,116 @@+/**+ * "Is this install doing anything right now?" — the single definition of system+ * idleness, derived from the `/api/system/processing` snapshot.+ *+ * Two very different consumers need the SAME answer, which is why this is a+ * pure leaf rather than a field the widget computes for itself:+ *+ * - the dashboard's Live activity widget, which renders what is running; and+ * - the unattended auto-updater (`services/autoUpdateScheduler.js`), which+ * restarts the whole install and therefore may only fire when nothing is+ * in flight.+ *+ * If the two ever disagreed, the widget would read "idle" while the updater+ * refused (or, far worse, the updater would restart PortOS out from under work+ * the widget was still drawing). So the widget renders `blockers` verbatim and+ * the updater refuses on the same list.+ *+ * QUEUED WORK IS ACTIVE. A render sitting at position 3 has a user waiting on+ * it; restarting into a new source revision mid-queue is the same disruption as+ * killing the running one.+ *+ * Every label here is GENERIC prose — a count and a noun. Nothing in this+ * module may echo a prompt, a record name, an app name, or any other content+ * out of the snapshot: the blocker list is rendered in the UI and written into+ * the auto-update runtime record on disk.+ */++/** Media kinds the queue runs, mapped to the noun a blocker line uses. */+const MEDIA_NOUNS = {+ image: 'image render',+ video: 'video render',+ audio: 'audio render',+ training: 'training run',+};++const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;++const mediaNoun = (kind) => MEDIA_NOUNS[kind] || 'media job';++/**+ * Count jobs by kind for one queue status, newest-agnostic (order-independent).+ * @returns {Map<string, number>}+ */+function countByKind(jobs, status) {+ const counts = new Map();+ for (const job of jobs) {+ if (job?.status !== status) continue;+ const kind = typeof job.kind === 'string' ? job.kind : 'media';+ counts.set(kind, (counts.get(kind) || 0) + 1);+ }+ return counts;+}++/**+ * Reduce a processing snapshot to an idle verdict plus the list of things+ * keeping it busy.+ *+ * @param {object} snapshot - a `getActiveProcessing()` result. Missing slices+ * are read as "nothing there" rather than throwing, so a partially-degraded+ * snapshot still yields a usable verdict — EXCEPT for the deliberate+ * `trusted: false` signals below, which are blockers in their own right.+ * @returns {{idle: boolean, activeCount: number, queuedCount: number, blockers: Array<{kind: string, label: string, count: number}>}}+ */+export function summarizeSystemActivity(snapshot) {+ const blockers = [];+ const add = (kind, label, count) => blockers.push({ kind, label, count });++ const jobs = Array.isArray(snapshot?.jobs) ? snapshot.jobs : [];+ for (const [kind, count] of countByKind(jobs, 'running')) {+ add(`media-running:${kind}`, `${plural(count, mediaNoun(kind))} running`, count);+ }+ for (const [kind, count] of countByKind(jobs, 'queued')) {+ add(`media-queued:${kind}`, `${plural(count, mediaNoun(kind))} queued`, count);+ }++ const imageTo3d = Array.isArray(snapshot?.extras?.imageTo3d) ? snapshot.extras.imageTo3d.length : 0;+ if (imageTo3d > 0) add('image-to-3d', `${plural(imageTo3d, 'image-to-3D build')} running`, imageTo3d);++ const activeAgents = Number(snapshot?.agents?.active) || 0;+ if (activeAgents > 0) add('agents-running', `${plural(activeAgents, 'CoS agent')} running`, activeAgents);+ const queuedAgents = Number(snapshot?.agents?.queued) || 0;+ if (queuedAgents > 0) add('agents-queued', `${plural(queuedAgents, 'CoS task')} queued`, queuedAgents);++ const mind = snapshot?.mind;+ // An unreadable Persistent Mind state is NOT an idle one: the update path+ // refuses on the same condition (`persistentMindStateUntrustedError`), so+ // reading it as "nothing queued" here would let the updater march up to a+ // refusal it could have seen coming.+ if (mind && mind.trusted === false) {+ add('mind-unreadable', 'Persistent Mind state unreadable', 1);+ } else if (mind) {+ if (mind.thinking) add('mind-thinking', 'Persistent Mind is thinking', 1);+ const queuedMessages = Number(mind.queued) || 0;+ if (queuedMessages > 0) add('mind-queued', `${plural(queuedMessages, 'Persistent Mind message')} queued`, queuedMessages);+ }++ const appOperations = Array.isArray(snapshot?.appOperations) ? snapshot.appOperations : [];+ if (appOperations.length > 0) {+ add('app-operations', `${plural(appOperations.length, 'app operation')} running`, appOperations.length);+ }++ if (snapshot?.update?.inProgress) add('update-in-progress', 'An update is already running', 1);++ const activeCount = jobs.filter((job) => job?.status === 'running').length+ + imageTo3d + activeAgents + (mind?.thinking ? 1 : 0) + appOperations.length;+ const queuedCount = jobs.filter((job) => job?.status === 'queued').length+ + queuedAgents + (Number(mind?.queued) || 0);++ return { idle: blockers.length === 0, activeCount, queuedCount, blockers };+}++/** One-line human summary of a blocker list, for a log line or a status row. */+export function describeActivityBlockers(blockers) {+ if (!Array.isArray(blockers) || blockers.length === 0) return 'system idle';+ return blockers.map((blocker) => blocker.label).join(', ');+}diff --git a/server/lib/systemIdle.test.js b/server/lib/systemIdle.test.jsnew file mode 100644index 0000000000..88f876b9ae--- /dev/null+++ b/server/lib/systemIdle.test.js@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest';+import { describeActivityBlockers, summarizeSystemActivity } from './systemIdle.js';++const snapshot = (overrides = {}) => ({+ jobs: [],+ extras: { imageTo3d: [] },+ agents: { active: 0, queued: 0 },+ mind: { trusted: true, thinking: false, queued: 0, status: 'idle' },+ appOperations: [],+ update: { inProgress: false },+ ...overrides,+});++describe('system idle verdict', () => {+ it('reports idle only when nothing is running or queued anywhere', () => {+ expect(summarizeSystemActivity(snapshot())).toMatchObject({ idle: true, activeCount: 0, queuedCount: 0, blockers: [] });+ });++ // The whole point of the module: a render waiting at position 3 has a user+ // waiting on it, so restarting the install mid-queue is the same disruption+ // as killing the running one.+ it('treats queued work as activity, not as an idle window', () => {+ const verdict = summarizeSystemActivity(snapshot({+ jobs: [{ id: 'v1', kind: 'video', status: 'queued' }],+ }));+ expect(verdict.idle).toBe(false);+ expect(verdict.queuedCount).toBe(1);+ expect(verdict.blockers).toEqual([{ kind: 'media-queued:video', label: '1 video render queued', count: 1 }]);+ });++ it('names each busy lane separately so the reason is actionable', () => {+ const verdict = summarizeSystemActivity(snapshot({+ jobs: [+ { id: 'i1', kind: 'image', status: 'running' },+ { id: 'i2', kind: 'image', status: 'running' },+ { id: 'a1', kind: 'audio', status: 'queued' },+ ],+ extras: { imageTo3d: [{ id: 'mesh-1' }] },+ agents: { active: 1, queued: 2 },+ mind: { trusted: true, thinking: true, queued: 3 },+ appOperations: [{ appId: 'example', appName: 'Example App', type: 'update' }],+ }));+ expect(verdict.idle).toBe(false);+ expect(verdict.blockers.map(b => b.label)).toEqual([+ '2 image renders running',+ '1 audio render queued',+ '1 image-to-3D build running',+ '1 CoS agent running',+ '2 CoS tasks queued',+ 'Persistent Mind is thinking',+ '3 Persistent Mind messages queued',+ '1 app operation running',+ ]);+ expect(verdict.activeCount).toBe(2 + 1 + 1 + 1 + 1);+ expect(verdict.queuedCount).toBe(1 + 2 + 3);+ });++ // An unreadable Persistent Mind state is exactly what the update path itself+ // refuses on (PERSISTENT_MIND_STATE_UNTRUSTED). Reading it as "nothing+ // queued" would march the updater up to a refusal it could have foreseen.+ it('refuses to read an unreadable Persistent Mind state as an idle one', () => {+ const verdict = summarizeSystemActivity(snapshot({ mind: { trusted: false } }));+ expect(verdict.idle).toBe(false);+ expect(verdict.blockers).toEqual([{ kind: 'mind-unreadable', label: 'Persistent Mind state unreadable', count: 1 }]);+ });++ it('counts an update already in flight as activity', () => {+ expect(summarizeSystemActivity(snapshot({ update: { inProgress: true } })).idle).toBe(false);+ });++ // A degraded snapshot (a slice that failed to load) must still produce a+ // usable verdict rather than throwing inside the scheduler's tick.+ it('reads missing slices as absent rather than throwing', () => {+ expect(summarizeSystemActivity({}).idle).toBe(true);+ expect(summarizeSystemActivity(undefined).idle).toBe(true);+ });++ it('describes a blocker list as one line', () => {+ expect(describeActivityBlockers([])).toBe('system idle');+ expect(describeActivityBlockers([{ label: 'a' }, { label: 'b' }])).toBe('a, b');+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex a0521fbe6c..9be257c8ed 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -13,6 +13,7 @@ import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';import {grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSnapshotSource, isSafeSubdirFilter, csvIdsParam,EXCLUDE_PATTERN_MAX_LENGTH, isSafeExcludePattern,+ AUTO_UPDATE_CHANNELS, AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN, AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX,} from './sharedSchemas.js';import { PR_COMPLETION_VALUES } from './prDisposition.js';import { EFFORT_LEVELS } from './providerModels.js';@@ -922,6 +923,21 @@ export const backupConfigSchema = z.object({disabledDefaultExcludes: z.array(z.string()).optional().default([])});+// Automatic PortOS self-update (Update tab). Stored under the top-level+// `autoUpdate` key and OFF by default — an install must never start restarting+// itself merely because it upgraded into this code. The accepted interpretation+// of a sparse slice (omitted channel, omitted interval) is `sharedSchemas.js`'s+// `resolveAutoUpdateConfig`, which the scheduler and the settings GET both read+// through, so this boundary schema cannot drift away from it.+export const autoUpdateSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ channel: z.enum(AUTO_UPDATE_CHANNELS).optional(),+ // Hours to wait after the last update before looking for an idle window.+ minIntervalHours: z.number().min(AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN).max(AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX).optional(),+ // Whether a checkout no script may safely repair queues a CoS agent.+ resolveBlockersWithAgent: z.boolean().optional(),+}).strict();+// Scheduled Series Autopilot (#2174). Machine-local per-series cron schedules// that fire `startSeriesAutopilot` unattended — the AI Provider Usage Policy's// sanctioned "scheduled automation" exception. Stored under the top-leveldiff --git a/server/routes/settings.js b/server/routes/settings.jsindex 4632f0f41e..328a155434 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -21,10 +21,11 @@ import { isGitHubRepoUrl } from '../lib/repoUrl.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';import { resolveBackupConfig } from '../lib/backupConfig.js';+import { resolveAutoUpdateConfig } from '../lib/sharedSchemas.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -177,13 +178,25 @@ const projectEffectiveBackup = (safe) => {};};+// Same reasoning for the auto-update slice: an install that only ticked the+// checkbox stores `{ enabled: true }`, and the Update tab would otherwise have to+// re-derive what an omitted channel/interval means — the mistake #6632 made for+// the backup schedule. The resolver is the scheduler's own.+// Only the STORABLE fields are projected: the resolver also derives+// `minIntervalMs`, and echoing it here would come straight back on the next+// save and be rejected by the strict schema.+const projectEffectiveAutoUpdate = (safe) => {+ const { minIntervalMs: _derived, ...effective } = resolveAutoUpdateConfig(safe.autoUpdate);+ return { ...safe, autoUpdate: { ...safe.autoUpdate, ...effective } };+};+// Single sanitizer every settings response (GET load + PUT save) runs through,// so a leak can't reappear on one path after being closed on the other: strip// the top-level `secrets` hierarchy, redact external tokens (#1821), decorate// server-authoritative bounds, then resolve the sparse backup schedule.const sanitizeSettingsForResponse = (settings) => {const { secrets, ...safe } = settings;- return projectEffectiveBackup(decorateBounds(redactExternalTokens(safe)));+ return projectEffectiveAutoUpdate(projectEffectiveBackup(decorateBounds(redactExternalTokens(safe))));};// GET /api/settings@@ -369,6 +382,9 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.backup !== undefined) {validateRequest(backupConfigSchema.partial(), req.body.backup);}+ if (req.body?.autoUpdate !== undefined) {+ validateRequest(autoUpdateSettingsSchema, req.body.autoUpdate);+ }if (req.body?.sharingDisplayName !== undefined || req.body?.sharingBio !== undefined) {validateRequest(sharingSettingsPatchSchema.partial(), {sharingDisplayName: req.body.sharingDisplayName,diff --git a/server/routes/update.js b/server/routes/update.jsindex 5398ffd34d..ecac11e0c5 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -44,6 +44,41 @@ router.get('/status', asyncHandler(async (req, res) => {res.json({ ...status, activeCosAgents, persistentMindImages });}));+// GET /api/update/auto — everything the Update tab needs to explain what the+// unattended updater is doing: the effective config, its own runtime record,+// whether the checkout is in a state it may run against, and the live idle+// verdict (the SAME `activity` object the dashboard's Live activity widget+// renders, from lib/systemIdle.js).+//+// Its OWN route rather than a block on /status, and lazily imported, 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, 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).+router.get('/auto', asyncHandler(async (req, res) => {+ const [{ getSettings }, { checkUpdateRepoReadiness }, { getActiveProcessing }, { resolveAutoUpdateConfig }] =+ await Promise.all([+ import('../services/settings.js'),+ import('../services/updateRepoReadiness.js'),+ import('../services/activeProcessing.js'),+ import('../lib/sharedSchemas.js'),+ ]);+ const [settings, runtime, repo, processing] = await Promise.all([+ getSettings().catch(() => null),+ updateChecker.getAutoUpdateRuntime(),+ // No fetch here: refreshing origin refs is the scheduler's own tick, not a+ // network hop every viewer of this tab pays for.+ checkUpdateRepoReadiness({ fetch: false }).catch(() => null),+ getActiveProcessing().catch(() => null),+ ]);+ res.json({+ config: resolveAutoUpdateConfig(settings?.autoUpdate),+ runtime,+ repo,+ activity: processing?.activity ?? null,+ });+}));+// POST /api/update/check — triggers manual check. `manual: true` bypasses the// unattended scheduler's gh backoff — a user who explicitly asked for a check// must get a real attempt, not a silent rejection from a cooldown thediff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex 40f5eead62..b18a35623a 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -1,14 +1,45 @@import { getCudaCapability, getCudaUtilization } from '../lib/cudaCapability.js';+import { summarizeSystemActivity } from '../lib/systemIdle.js';import { listJobs, getRunningJob } from './mediaJobQueue/index.js';import { sanitizeJob } from './mediaJobQueue/sanitizeJob.js';import { listGeneratingModelSummaries } from './imageTo3d/models.js';import { getLoadedModels } from './ollamaManager.js';+import { listActiveAppOperations } from './appOperations.js';+import { readPersistentMindStateForSafetyCheck } from './cosState.js';+import { isUpdateInProgress } from './updateChecker.js';import * as cos from './cos.js';const LIVE_STATUSES = new Set(['queued', 'running']);+/**+ * What the Persistent Mind is doing, WITHOUT any of what it is thinking about.+ *+ * Counts and lifecycle only: a queued message's text, its attachments, and the+ * turn's own content never appear here. This rides the same `/api/system/+ * processing` payload the dashboard polls every few seconds, and a mind's+ * messages are the most personal records on the install.+ *+ * `trusted: false` (unreadable state) is deliberately NOT collapsed into "idle".+ * `summarizeSystemActivity` treats it as a blocker, matching the update path's+ * own `PERSISTENT_MIND_STATE_UNTRUSTED` refusal.+ */+function summarizeMind(snapshot) {+ if (!snapshot?.trusted) return { trusted: false, status: 'unknown', thinking: false, queued: 0 };+ const mind = snapshot.persistentMind;+ const activeTurn = mind?.activeTurn || null;+ return {+ trusted: true,+ enabled: mind?.enabled === true,+ started: mind?.started === true,+ status: typeof mind?.status === 'string' ? mind.status : 'disabled',+ thinking: Boolean(activeTurn),+ thinkingSince: activeTurn?.startedAt || null,+ queued: Array.isArray(mind?.queuedMessages) ? mind.queuedMessages.length : 0,+ };+}+export async function getActiveProcessing() {- const [capability, jobs, models, loadedModels, pendingTaskIds, agents] = await Promise.all([+ const [capability, jobs, models, loadedModels, pendingTaskIds, agents, mindState] = await Promise.all([getCudaCapability(),Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),listGeneratingModelSummaries().catch(() => []),@@ -17,6 +48,9 @@ export async function getActiveProcessing() {// `null` = the read FAILED, distinct from `[]` = read fine, no agents. The// counts below degrade differently for the two, so they must stay separable.cos.getAgents().catch(() => null),+ // Same contract one layer down: the reader reports `trusted: false` rather+ // than an empty mind, so an unreadable state cannot read as an idle one.+ readPersistentMindStateForSafetyCheck().catch(() => ({ trusted: false, persistentMind: null })),]);const cosStatus = agents === null ? await cos.getStatus().catch(() => null) : null;const utilization = capability.status === 'available' ? await getCudaUtilization() : { status: capability.status, gpus: [] };@@ -35,7 +69,7 @@ export async function getActiveProcessing() {const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));const pendingTasks = pendingTaskIds.filter((id) => !claimedTaskIds.has(id)).length;const gpuBusy = Boolean(getRunningJob());- return {+ const snapshot = {updatedAt: new Date().toISOString(),gpu: {status: capability.status,@@ -57,5 +91,14 @@ export async function getActiveProcessing() {active: runningAgents ? runningAgents.length : (cosStatus?.activeAgents || 0),queued: pendingTasks,},+ mind: summarizeMind(mindState),+ // An App Management update/standardize holds a checkout and restarts PM2+ // processes — activity in exactly the sense that matters to a caller+ // deciding whether it may restart the install.+ appOperations: listActiveAppOperations(),+ update: { inProgress: isUpdateInProgress() },};+ // Derived here, once, so the widget and the auto-updater cannot disagree+ // about what "idle" means. See lib/systemIdle.js.+ return { ...snapshot, activity: summarizeSystemActivity(snapshot) };}diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.jsindex b85000e1ea..03a9a91842 100644--- a/server/services/activeProcessing.test.js+++ b/server/services/activeProcessing.test.js@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const deps = vi.hoisted(() => ({capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), tasks: vi.fn(), status: vi.fn(), agents: vi.fn(),+ mind: vi.fn(), operations: vi.fn(), updating: vi.fn(),}));vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: deps.capability, getCudaUtilization: deps.utilization }));vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob: deps.running }));@@ -9,12 +10,18 @@ vi.mock('./mediaJobQueue/sanitizeJob.js', () => ({ sanitizeJob: (job) => ({ id:vi.mock('./imageTo3d/models.js', () => ({ listGeneratingModelSummaries: deps.models }));vi.mock('./ollamaManager.js', () => ({ getLoadedModels: deps.loaded }));vi.mock('./cos.js', () => ({ getPendingTaskIds: deps.tasks, getStatus: deps.status, getAgents: deps.agents }));+vi.mock('./cosState.js', () => ({ readPersistentMindStateForSafetyCheck: deps.mind }));+vi.mock('./appOperations.js', () => ({ listActiveAppOperations: deps.operations }));+vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: deps.updating }));const { getActiveProcessing } = await import('./activeProcessing.js');describe('active processing snapshot', () => {beforeEach(() => {Object.values(deps).forEach((mock) => mock.mockReset());+ deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: true, started: true, status: 'idle', queuedMessages: [], activeTurn: null } });+ deps.operations.mockReturnValue([]);+ deps.updating.mockReturnValue(false);});it('reports sanitized audio work, GPU utilization, and non-media extras', async () => {@@ -58,6 +65,66 @@ describe('active processing snapshot', () => {});});+// The snapshot is what the dashboard renders AND what the unattended updater+// refuses on, so the Persistent Mind slice must say whether the mind is busy+// without saying anything about what it is busy WITH.+describe('persistent mind and idle verdict', () => {+ beforeEach(() => {+ Object.values(deps).forEach((mock) => mock.mockReset());+ deps.operations.mockReturnValue([]);+ deps.updating.mockReturnValue(false);+ deps.capability.mockResolvedValue({ status: 'absent', gpus: [] });+ deps.jobs.mockReturnValue([]);+ deps.running.mockReturnValue(null);+ deps.models.mockResolvedValue([]);+ deps.loaded.mockResolvedValue([]);+ deps.tasks.mockResolvedValue([]);+ deps.agents.mockResolvedValue([]);+ deps.status.mockResolvedValue({ activeAgents: 0 });+ });++ it('reports an active turn as thinking, carrying counts but no message content', async () => {+ deps.mind.mockResolvedValue({+ trusted: true,+ persistentMind: {+ enabled: true, started: true, status: 'thinking',+ activeTurn: { id: 'turn-1', startedAt: '2026-01-01T00:00:00.000Z', wake: { kind: 'message', message: { id: 'm1', text: 'private thought' } } },+ queuedMessages: [{ id: 'm2', text: 'another private message' }],+ },+ });+ const snapshot = await getActiveProcessing();+ expect(snapshot.mind).toEqual({+ trusted: true, enabled: true, started: true, status: 'thinking',+ thinking: true, thinkingSince: '2026-01-01T00:00:00.000Z', queued: 1,+ });+ expect(JSON.stringify(snapshot)).not.toContain('private');+ expect(snapshot.activity.idle).toBe(false);+ });++ it('reports an idle install as idle, with no blockers', async () => {+ deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: true, started: true, status: 'waiting', activeTurn: null, queuedMessages: [] } });+ const snapshot = await getActiveProcessing();+ expect(snapshot.activity).toMatchObject({ idle: true, blockers: [] });+ });++ // An unreadable mind state must not read as an idle one — the update path+ // refuses on exactly that condition.+ it('does not read an unreadable mind state as idle', async () => {+ deps.mind.mockRejectedValue(new Error('state unreadable'));+ const snapshot = await getActiveProcessing();+ expect(snapshot.mind.trusted).toBe(false);+ expect(snapshot.activity.idle).toBe(false);+ });++ it('counts a live app operation as activity', async () => {+ deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: false, started: false, status: 'disabled', activeTurn: null, queuedMessages: [] } });+ deps.operations.mockReturnValue([{ appId: 'example', appName: 'Example App', type: 'update', startedAt: 1 }]);+ const snapshot = await getActiveProcessing();+ expect(snapshot.activity.idle).toBe(false);+ expect(snapshot.activity.blockers.map(b => b.kind)).toContain('app-operations');+ });+});+// The task record keeps its `pending` status until spawnAgentForTask flips it to// `in_progress`, which the server does AFTER registering the agent as running.// A snapshot taken inside that window used to report the one task as both@@ -65,6 +132,9 @@ describe('active processing snapshot', () => {describe('queued agent count', () => {beforeEach(() => {Object.values(deps).forEach((mock) => mock.mockReset());+ deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: true, started: true, status: 'idle', queuedMessages: [], activeTurn: null } });+ deps.operations.mockReturnValue([]);+ deps.updating.mockReturnValue(false);deps.capability.mockResolvedValue({ status: 'absent', gpus: [] });deps.jobs.mockReturnValue([]);deps.running.mockReturnValue(null);diff --git a/server/services/appOperations.js b/server/services/appOperations.jsnew file mode 100644index 0000000000..e6593623fd--- /dev/null+++ b/server/services/appOperations.js@@ -0,0 +1,83 @@+/**+ * In-flight app update/standardize operations, keyed by app id.+ *+ * These run for minutes and outlive the page that dispatched them, so the+ * server owns both the re-entrancy guard and the resumable progress buffer.+ *+ * Extracted from `sockets/apps.js` because the socket handler is no longer the+ * only caller: `services/appUpdateRunner.js` claims the same resource for an+ * unattended auto-update, and `services/activeProcessing.js` reads the registry+ * so a running app operation counts as system activity (an auto-update must not+ * restart PortOS while App Management is mid-deploy of something else).+ */++const activeAppOperations = new Map();++// One operation occupies several keys, so collapse them back to one row.+// repoPath stays server-side: the client only needs to name and render the run.+export const activeOperationsPayload = () => ({+ operations: [...new Set(activeAppOperations.values())].map(({ repoPath: _repoPath, ...op }) => op)+});++/**+ * The live operations as activity rows — id, name, type, age. Same projection+ * as the socket payload; named separately so the activity snapshot does not+ * read as if it were about to emit a socket frame.+ */+export const listActiveAppOperations = () => activeOperationsPayload().operations;++// Two app records may point at the same checkout, so the app id alone doesn't+// identify the resource being mutated — an operation is registered under every+// key that names the resource it is mutating.+const operationKeys = (app) => (app.repoPath && app.repoPath !== app.id ? [app.id, app.repoPath] : [app.id]);++const findConflictingOperation = (app) => operationKeys(app)+ .map(key => activeAppOperations.get(key))+ .find(Boolean);++// Refuse rather than overwrite: a caller that reaches the registry without+// going through claimAppOperation must not be able to silently clobber a live+// run out of the map and orphan its step buffer.+const setOperationKey = (key, operation) => {+ if (activeAppOperations.has(key)) throw new Error(`App operation already in flight for ${key}`);+ activeAppOperations.set(key, operation);+};++/**+ * Claim the resource for this run. The conflict check and the registry write+ * are one synchronous step — an await between them is what let two overlapping+ * dispatches both pass the check, both run, and then delete each other's+ * record (#6638). Callers must claim BEFORE any further await.+ */+export const claimAppOperation = (io, app, type) => {+ const inFlight = findConflictingOperation(app);+ if (inFlight) return { ok: false, inFlight };+ const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now(), repoPath: app.repoPath };+ for (const key of operationKeys(app)) setOperationKey(key, operation);+ io.emit('app:operations:active', activeOperationsPayload());+ return { ok: true, operation };+};++// A PortOS self-update deliberately leaves its operation registered: the+// process is about to be replaced, so the map dies with it. A test driving that+// path has no process boundary, so it needs a way back to an empty set.+export const __resetAppOperations = () => activeAppOperations.clear();++// Clear every key this operation holds, and only the keys pointing at THIS+// operation — a run that already finished must not evict a live sibling.+export const endAppOperation = (io, appId) => {+ const operation = activeAppOperations.get(appId);+ if (!operation) return;+ for (const [key, op] of activeAppOperations) {+ if (op === operation) activeAppOperations.delete(key);+ }+ io.emit('app:operations:active', activeOperationsPayload());+};++// Record a step into the operation's buffer using the same last-write-wins+// per-step semantics the client renders with.+export const recordOperationStep = (operation, frame) => {+ const existing = operation.steps.findIndex(s => s.step === frame.step);+ if (existing >= 0) operation.steps[existing] = frame;+ else operation.steps.push(frame);+};diff --git a/server/services/appUpdateRunner.js b/server/services/appUpdateRunner.jsnew file mode 100644index 0000000000..c0db2a5f1c--- /dev/null+++ b/server/services/appUpdateRunner.js@@ -0,0 +1,121 @@+/**+ * The one implementation of "update a managed app".+ *+ * App Management's Git tab dispatches it over the `app:update` socket event;+ * the unattended auto-updater (`autoUpdateScheduler.js`, channel `main`) calls+ * it directly for the PortOS app record. Both reach THIS function, so an+ * automatic update is byte-for-byte the action the button performs — the+ * operation claim, the PortOS preflight refusals, `appUpdater.updateApp`, the+ * history ledger row, and the apps-changed broadcast, in that order.+ *+ * Refusals are RETURNED, not thrown, because the socket path answers two of+ * them on the dispatching socket rather than the io bus (only the person who+ * clicked needs to hear "already running"), while the scheduler just logs. The+ * progress/complete/error frames that every viewer needs stay on `io` in here.+ */++import * as appsService from './apps.js';+import * as appUpdater from './appUpdater.js';+import { logAction } from './history.js';+import { checkPortosUpdatePreflight } from './updatePreflight.js';+import { claimAppOperation, endAppOperation, recordOperationStep } from './appOperations.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++/**+ * Run a full managed-app update cycle.+ *+ * @param {object} params+ * @param {object} params.io - Socket.IO server for the step/complete/error frames.+ * @param {string} params.appId+ * @param {boolean} [params.syncFork]+ * @param {boolean} [params.acknowledgeFork]+ * @param {boolean} [params.acknowledgePersistentMindImageBackup]+ * @returns {Promise<+ * | {ok: false, reason: 'not-found'}+ * | {ok: false, reason: 'duplicate', inFlight: object}+ * | {ok: false, reason: 'refused', appId: string, code: string|null, message: string}+ * | {ok: true, appId: string, result: object|null, selfUpdateStarted: boolean, failure: Error|null}+ * >}+ */+export async function runAppUpdate({+ io,+ appId,+ syncFork = false,+ acknowledgeFork = false,+ acknowledgePersistentMindImageBackup = false,+}) {+ const app = await appsService.getAppById(appId);+ if (!app) return { ok: false, reason: 'not-found' };++ // Claimed here, immediately after the app record resolves and BEFORE the+ // preflight await below — the claim has to cover every await that precedes+ // the actual update, or two dispatches land inside the gap.+ const claim = claimAppOperation(io, app, 'update');+ if (!claim.ok) return { ok: false, reason: 'duplicate', inFlight: claim.inFlight };+ const operation = claim.operation;+ let operatingAppId = app.id;+ let result = null;++ try {+ // PortOS is itself a managed app, and updating it restarts the whole+ // install — apply the same refusals POST /api/update/execute enforces (a+ // live CoS agent, in-flight Persistent Mind image work, an unacknowledged+ // fork) so App Management can't restart out from under them just because it+ // dispatches through this path instead (#5984).+ if (app.id === PORTOS_APP_ID) {+ const refusal = await checkPortosUpdatePreflight({+ acknowledgeFork,+ acknowledgePersistentMindImageBackup,+ }).then(() => null, (err) => err);+ if (refusal) {+ endAppOperation(io, app.id);+ operatingAppId = null;+ return { ok: false, reason: 'refused', appId: app.id, code: refusal.code || null, message: refusal.message };+ }+ }++ console.log(`⬇️ Update started for ${app.name}`);+ const emit = (step, status, message) => {+ const frame = { appId: app.id, step, status, message, timestamp: Date.now() };+ recordOperationStep(operation, frame);+ io.emit('app:update:step', frame);+ };++ let failure = null;+ result = await appUpdater.updateApp(app, emit, {+ syncFork,+ acknowledgeFork,+ acknowledgePersistentMindImageBackup,+ }).catch(err => {+ failure = err;+ // Refusals raised inside the update (the PortOS launcher's post-lock+ // re-check, say) carry the same acknowledgement codes the pre-check+ // emits above — the panel's retry buttons key on `code`, so dropping it+ // here would leave a refusal the user could have acted on inert.+ io.emit('app:update:error', { appId: app.id, code: err.code || null, message: err.message });+ return null;+ });++ // The ledger and the apps-changed broadcast belong to this path now that it+ // is the only way to update an app — a thrown update still gets a row, with+ // success:false, rather than vanishing from the history.+ await logAction('update', app.id, app.name, { steps: result?.steps ?? [] }, result?.success === true, failure?.message ?? null);+ appsService.notifyAppsChanged('update', app.id);++ if (result?.selfUpdateStarted) {+ // update.sh will `pm2 delete` THIS process partway through, so there is+ // no completion to report and nothing after the restart to clear the+ // operation. Leaving it registered (the map dies with the process) is+ // what keeps the row rendering the script's STEP: frames right up to the+ // moment the server goes down.+ console.log(`♻️ PortOS self-update handed off — update.sh will restart this process`);+ } else if (result) {+ io.emit('app:update:complete', { appId: app.id, success: result.success, steps: result.steps });+ console.log(`✅ Update complete for ${app.name}`);+ }++ return { ok: true, appId: app.id, result, selfUpdateStarted: result?.selfUpdateStarted === true, failure };+ } finally {+ if (operatingAppId && !result?.selfUpdateStarted) endAppOperation(io, operatingAppId);+ }+}diff --git a/server/services/autoUpdateScheduler.js b/server/services/autoUpdateScheduler.jsnew file mode 100644index 0000000000..2379cce15a--- /dev/null+++ b/server/services/autoUpdateScheduler.js@@ -0,0 +1,287 @@+/**+ * Unattended PortOS self-update, gated on the install being completely idle.+ *+ * The contract, in order — every gate must pass on the SAME tick:+ *+ * 1. The feature is on (`settings.autoUpdate.enabled`).+ * 2. At least `minIntervalHours` have passed since the last update landed.+ * Before that the scheduler does not even look; after it, every tick is a+ * chance to go.+ * 3. There is actually something to update to — a newer release tag on the+ * `release` channel, or origin's default branch ahead of this checkout on+ * the `main` channel. Nothing to do is a no-op, not a restart.+ * 4. The checkout is on the default branch and clean, after the mechanical+ * repairs in `updateRepoReadiness.js`. What no script may safely fix+ * queues a CoS agent and waits.+ * 5. The system is idle — no render running or queued, no CoS agent, no+ * Persistent Mind turn or queued message, no app operation+ * (`lib/systemIdle.js`, the same verdict the dashboard's Live activity+ * widget renders).+ *+ * Then it performs EXACTLY the action the matching button performs, through the+ * same service the button reaches. This is not a second update implementation:+ * `release` calls `startPortosSelfUpdate` (what `POST /api/update/execute`+ * calls) and `main` calls `runAppUpdate` (what the `app:update` socket handler+ * calls). Every preflight refusal, lock, and launch rule therefore applies+ * unchanged, including the ones that exist because this process does not+ * survive the script it launches.+ *+ * This is a user-configured scheduled automation — the sanctioned exception in+ * the AI Provider Usage Policy — and it makes no provider call of its own. The+ * one that can occur is the repair agent in step 4, which is itself switchable.+ */++import { schedule, cancel } from './eventScheduler.js';+import { getSettings, settingsEvents } from './settings.js';+import { getActiveProcessing } from './activeProcessing.js';+import { startPortosSelfUpdate } from './portosSelfUpdate.js';+import { runAppUpdate } from './appUpdateRunner.js';+import { prepareUpdateRepo, queueRepoRepairTask } from './updateRepoReadiness.js';+import * as updateChecker from './updateChecker.js';+import { describeActivityBlockers } from '../lib/systemIdle.js';+import { resolveAutoUpdateConfig } from '../lib/sharedSchemas.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++const EVENT_ID = 'portos-auto-update';++/** How often the scheduler looks for an idle window once it is armed. */+const AUTO_UPDATE_POLL_INTERVAL_MS = 5 * 60 * 1000;++// Only confirmed enabled/disabled states are cached; the signature makes an+// unrelated settings save free, exactly as backupScheduler's does.+let registrationSignature = null;++// The Socket.IO server, captured at boot so the scheduler's run emits the same+// `portos:update:*` / `app:update:*` frames a click would — a user watching the+// Update page sees the automatic run stream like any other.+let ioRef = null;++/**+ * When the clock for the minimum interval starts.+ *+ * `lastRunAt` first (this scheduler's own last launch), then the last recorded+ * update result — which covers an update the USER ran, so a manual update also+ * resets the interval rather than leaving an automatic one queued behind it.+ * `armedAt` is the fallback for an install that has never updated: without it+ * the interval would be measured from the epoch and the first tick after+ * enabling would fire immediately.+ */+export function updateBaselineAt(runtime, lastUpdateResult, now = Date.now()) {+ const candidates = [runtime?.lastRunAt, lastUpdateResult?.completedAt, runtime?.armedAt]+ .map((value) => (typeof value === 'string' ? Date.parse(value) : NaN))+ .filter((value) => Number.isFinite(value));+ return candidates.length ? Math.max(...candidates) : now;+}++/** Record the skip and log it once per distinct reason, not once per tick. */+let lastLoggedSkip = null;+async function standDown(reason, detail) {+ const line = detail ? `${reason}: ${detail}` : reason;+ if (line !== lastLoggedSkip) {+ console.log(`🕒 Auto-update standing by — ${line}`);+ lastLoggedSkip = line;+ }+ await updateChecker.recordAutoUpdateRuntime({+ lastSkip: { reason, detail: detail || null, at: new Date().toISOString() },+ }).catch(() => undefined);+ return { ran: false, reason, detail: detail || null };+}++/**+ * Is there anything to update TO on this channel?+ *+ * @returns {Promise<{available: boolean, detail: string}>}+ */+async function updateAvailableFor(channel, status, verdict) {+ if (channel === 'release') {+ if (status.updateAvailable) return { available: true, detail: `release v${status.latestRelease?.version}` };+ return { available: false, detail: 'no newer release' };+ }+ // `main`: origin's default branch is the target, and `verdict.behind` is the+ // count of commits this checkout is missing — measured after a real fetch, so+ // it cannot report a stale "up to date" and skip a real update. An install+ // whose code is ahead of what is RUNNING (a bare `git pull`) has already been+ // updated on disk; `installState.outOfSync` is what catches that, and it+ // needs the same reconcile run.+ if (verdict.behind > 0) return { available: true, detail: `${verdict.behind} commit(s) behind origin/${verdict.defaultBranch}` };+ if (status.installState?.outOfSync) return { available: true, detail: 'install out of sync with the checked-out code' };+ return { available: false, detail: `up to date with origin/${verdict.defaultBranch || 'default'}` };+}++/**+ * One scheduler tick. Exported for the suite and for a "run the check now"+ * caller; it performs at most one update and never throws.+ *+ * @param {object} [options]+ * @param {object} [options.io] - overrides the captured Socket.IO server.+ * @returns {Promise<{ran: boolean, reason?: string, detail?: string|null, channel?: string}>}+ */+export async function runAutoUpdateTick({ io = ioRef } = {}) {+ const settings = await getSettings().catch(() => null);+ const config = resolveAutoUpdateConfig(settings?.autoUpdate);+ if (!config.enabled) return { ran: false, reason: 'disabled' };++ const runtime = await updateChecker.getAutoUpdateRuntime();+ // Stamp the arming point on the first tick after the feature goes on, so the+ // interval has something to measure from on an install that has never+ // updated. Written once — a re-stamp on every boot would move the deadline.+ if (!runtime.armedAt) {+ await updateChecker.recordAutoUpdateRuntime({ armedAt: new Date().toISOString() }).catch(() => undefined);+ }++ const status = await updateChecker.getUpdateStatus().catch(() => null);+ if (!status) return standDown('status-unavailable', 'could not read the update status');+ if (status.updateInProgress) return standDown('update-in-progress', 'an update is already running');++ const now = Date.now();+ const baselineAt = updateBaselineAt(+ { ...runtime, armedAt: runtime.armedAt || new Date(now).toISOString() },+ status.lastUpdateResult,+ now,+ );+ const elapsedMs = now - baselineAt;+ if (elapsedMs < config.minIntervalMs) {+ const remainingMinutes = Math.ceil((config.minIntervalMs - elapsedMs) / 60000);+ return standDown('cooldown', `${remainingMinutes} minute(s) left of the ${config.minIntervalHours}h minimum interval`);+ }++ // Repo readiness runs BEFORE the idle check and before the availability+ // check, because it is the one gate whose remedy takes time: a repair agent+ // queued now is work the idle gate will then wait on, and the next window+ // after it finishes is the one that updates.+ const { verdict, actions } = await prepareUpdateRepo().catch((err) => ({+ verdict: { ready: false, needsAgent: false, reasons: ['git-unreadable'], summary: err.message, repairable: [] },+ actions: [],+ }));+ if (!verdict.ready) {+ if (verdict.needsAgent && config.resolveBlockersWithAgent) {+ const task = await queueRepoRepairTask(verdict);+ if (task?.id && task.id !== runtime.repairTaskId) {+ await updateChecker.recordAutoUpdateRuntime({ repairTaskId: task.id }).catch(() => undefined);+ }+ }+ return standDown('repo-not-ready', verdict.summary || 'the checkout is not on a clean default branch');+ }+ if (actions.length) console.log(`🧹 Auto-update prepared the checkout: ${actions.join(', ')}`);++ const availability = await updateAvailableFor(config.channel, status, verdict);+ if (!availability.available) return standDown('up-to-date', availability.detail);++ // Idle is checked LAST, immediately before the launch, so the window it+ // reports is as close as this can get to the window the update runs in. The+ // update path's own preflight re-checks the agent and Persistent Mind halves+ // under the update lock — this gate is broader (renders, queued work), not a+ // replacement for it.+ const processing = await getActiveProcessing().catch(() => null);+ if (!processing) return standDown('activity-unknown', 'could not read the activity snapshot');+ if (!processing.activity.idle) {+ return standDown('busy', describeActivityBlockers(processing.activity.blockers));+ }++ lastLoggedSkip = null;+ console.log(`⬆️ Auto-update starting (${config.channel} channel) — ${availability.detail}`);+ await updateChecker.recordAutoUpdateRuntime({+ lastAttemptAt: new Date().toISOString(),+ lastSkip: null,+ }).catch(() => undefined);++ const outcome = await launchUpdateFor(config.channel, io).catch((err) => ({ ok: false, message: err.message }));+ if (!outcome.ok) {+ console.error(`❌ Auto-update could not start: ${outcome.message}`);+ await updateChecker.recordAutoUpdateRuntime({ lastOutcome: `failed: ${outcome.message}` }).catch(() => undefined);+ return { ran: false, reason: 'launch-failed', detail: outcome.message, channel: config.channel };+ }++ // `lastRunAt` is stamped at the LAUNCH, not at a completion this process will+ // not live to see: update.sh pm2-deletes this server partway through. Without+ // it, a restart that lands before the update result is recorded would find+ // the interval already elapsed and immediately launch a second update.+ await updateChecker.recordAutoUpdateRuntime({+ lastRunAt: new Date().toISOString(),+ lastOutcome: `started (${config.channel})`,+ }).catch(() => undefined);+ return { ran: true, channel: config.channel, detail: availability.detail };+}++/**+ * Dispatch the channel's action — the SAME service call its button makes.+ * Nothing about the update lifecycle belongs here.+ */+async function launchUpdateFor(channel, io) {+ if (channel === 'release') {+ await startPortosSelfUpdate({ io, mode: 'release' });+ return { ok: true };+ }+ const result = await runAppUpdate({ io, appId: PORTOS_APP_ID });+ if (result.ok) return { ok: true };+ const message = result.reason === 'refused'+ ? result.message+ : result.reason === 'duplicate'+ ? `an ${result.inFlight.type} is already running for ${result.inFlight.appName}`+ : `the ${PORTOS_APP_ID} app record was not found`;+ return { ok: false, message };+}++/**+ * (Re)synchronize the poll registration to match the given settings snapshot.+ * Idempotent — safe at boot and after every settings save. Registering the+ * interval fires nothing until it elapses, so this never updates by itself.+ *+ * @param {object} [settings] - a settings snapshot; re-read when omitted.+ * @returns {Promise<boolean>} whether the poll is registered afterwards.+ */+export async function syncAutoUpdateSchedule(settings) {+ const current = settings || await getSettings().catch(() => null);+ const config = resolveAutoUpdateConfig(current?.autoUpdate);+ // 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.+ const signature = JSON.stringify({ enabled: config.enabled });+ if (signature === registrationSignature) return config.enabled;+ registrationSignature = signature;++ if (!config.enabled) {+ cancel(EVENT_ID);+ console.log('🕒 Automatic updates: off');+ return false;+ }++ schedule({+ id: EVENT_ID,+ type: 'interval',+ intervalMs: AUTO_UPDATE_POLL_INTERVAL_MS,+ handler: () => runAutoUpdateTick().catch(err => {+ // Outside the request lifecycle: an uncaught throw here takes the process+ // down with it, and a scheduler that dies stops updating silently.+ console.error(`❌ Auto-update tick failed: ${err.message}`);+ }),+ metadata: { source: 'autoUpdateScheduler' },+ });+ console.log(`🕒 Automatic updates: on (${config.channel} channel, ${config.minIntervalHours}h minimum interval)`);+ return true;+}++// Re-sync on every settings save rather than from the settings route — keeps+// the HTTP handler decoupled from the update graph (mirrors backupScheduler).+// The signature guard makes unrelated saves free.+settingsEvents.on('settings:updated', (cleaned) => {+ syncAutoUpdateSchedule(cleaned).catch(err =>+ console.error(`❌ Auto-update schedule re-sync failed: ${err.message}`));+});++/**+ * Boot entry point — captures the Socket.IO server so an automatic run streams+ * 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) {+ ioRef = io || null;+ return syncAutoUpdateSchedule();+}++/** Test-only: drop the cached registration signature. */+export function __resetAutoUpdateSchedulerForTests() {+ registrationSignature = null;+ lastLoggedSkip = null;+ ioRef = null;+}diff --git a/server/services/autoUpdateScheduler.test.js b/server/services/autoUpdateScheduler.test.jsnew file mode 100644index 0000000000..0ed6512051--- /dev/null+++ b/server/services/autoUpdateScheduler.test.js@@ -0,0 +1,225 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const deps = vi.hoisted(() => ({+ settings: vi.fn(),+ processing: vi.fn(),+ selfUpdate: vi.fn(),+ appUpdate: vi.fn(),+ prepareRepo: vi.fn(),+ queueRepair: vi.fn(),+ status: vi.fn(),+ runtime: vi.fn(),+ recordRuntime: vi.fn(),+ schedule: vi.fn(),+ cancel: vi.fn(),+}));++vi.mock('./eventScheduler.js', () => ({ schedule: deps.schedule, cancel: deps.cancel }));+vi.mock('./settings.js', () => ({+ getSettings: deps.settings,+ settingsEvents: { on: vi.fn(), emit: vi.fn() },+}));+vi.mock('./activeProcessing.js', () => ({ getActiveProcessing: deps.processing }));+vi.mock('./portosSelfUpdate.js', () => ({ startPortosSelfUpdate: deps.selfUpdate }));+vi.mock('./appUpdateRunner.js', () => ({ runAppUpdate: deps.appUpdate }));+vi.mock('./updateRepoReadiness.js', () => ({+ prepareUpdateRepo: deps.prepareRepo,+ queueRepoRepairTask: deps.queueRepair,+}));+vi.mock('./updateChecker.js', () => ({+ getUpdateStatus: deps.status,+ getAutoUpdateRuntime: deps.runtime,+ recordAutoUpdateRuntime: deps.recordRuntime,+}));++const { runAutoUpdateTick, syncAutoUpdateSchedule, updateBaselineAt, __resetAutoUpdateSchedulerForTests } =+ await import('./autoUpdateScheduler.js');++const HOUR = 60 * 60 * 1000;+const iso = (ms) => new Date(ms).toISOString();++const idleSnapshot = { activity: { idle: true, blockers: [] } };+const readyRepo = { verdict: { ready: true, behind: 3, defaultBranch: 'main', reasons: [], repairable: [] }, actions: [] };++beforeEach(() => {+ Object.values(deps).forEach((mock) => mock.mockReset());+ __resetAutoUpdateSchedulerForTests();+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: true, channel: 'release', minIntervalHours: 6 } });+ deps.runtime.mockResolvedValue({ armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null, repairTaskId: null });+ deps.recordRuntime.mockResolvedValue({});+ deps.status.mockResolvedValue({+ updateInProgress: false,+ updateAvailable: true,+ latestRelease: { version: '9.9.9' },+ lastUpdateResult: null,+ installState: { outOfSync: false },+ });+ deps.prepareRepo.mockResolvedValue(readyRepo);+ deps.processing.mockResolvedValue(idleSnapshot);+ deps.selfUpdate.mockResolvedValue({ started: true, tag: 'v9.9.9' });+ deps.appUpdate.mockResolvedValue({ ok: true });+});++describe('automatic update dispatch', () => {+ // The whole design constraint: an automatic update must be the SAME action+ // the matching button performs, through the same service — not a second+ // implementation that could drift from the preflights and the launch rules.+ it('runs the release channel through the Update page launcher', async () => {+ const io = { emit: vi.fn() };+ await expect(runAutoUpdateTick({ io })).resolves.toMatchObject({ ran: true, channel: 'release' });+ expect(deps.selfUpdate).toHaveBeenCalledWith({ io, mode: 'release' });+ expect(deps.appUpdate).not.toHaveBeenCalled();+ });++ it('runs the main channel through the App Management update runner', async () => {+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: true, channel: 'main', minIntervalHours: 6 } });+ const io = { emit: vi.fn() };+ await expect(runAutoUpdateTick({ io })).resolves.toMatchObject({ ran: true, channel: 'main' });+ expect(deps.appUpdate).toHaveBeenCalledWith({ io, appId: 'portos-default' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ // Stamped at the LAUNCH, not at a completion this process does not live to+ // see — update.sh pm2-deletes the server partway through, and a restart that+ // lands before the result is recorded would otherwise fire a second update.+ it('records the run at launch time', async () => {+ await runAutoUpdateTick({ io: {} });+ expect(deps.recordRuntime).toHaveBeenCalledWith(expect.objectContaining({ lastRunAt: expect.any(String) }));+ });+});++describe('automatic update gates', () => {+ it('does nothing while the feature is off', async () => {+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: false } });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'disabled' });+ expect(deps.status).not.toHaveBeenCalled();+ });++ it('waits out the minimum interval before looking at all', async () => {+ deps.runtime.mockResolvedValue({ armedAt: null, lastRunAt: iso(Date.now() - 2 * HOUR) });+ const result = await runAutoUpdateTick({ io: {} });+ expect(result).toMatchObject({ ran: false, reason: 'cooldown' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ // A user who updated manually an hour ago has reset the clock; an automatic+ // update queued behind that would restart the install for nothing.+ it('measures the interval from a manual update too', async () => {+ deps.runtime.mockResolvedValue({ armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null });+ deps.status.mockResolvedValue({+ updateInProgress: false, updateAvailable: true, latestRelease: { version: '9.9.9' },+ lastUpdateResult: { completedAt: iso(Date.now() - HOUR) },+ });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'cooldown' });+ });++ it('stands down while anything is still running or queued', async () => {+ deps.processing.mockResolvedValue({+ activity: { idle: false, blockers: [{ kind: 'media-queued:video', label: '2 video renders queued', count: 2 }] },+ });+ const result = await runAutoUpdateTick({ io: {} });+ expect(result).toMatchObject({ ran: false, reason: 'busy', detail: '2 video renders queued' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ // An unreadable activity snapshot is not an idle one — the tick must not fall+ // through to a restart because the check itself failed.+ it('stands down when the activity snapshot cannot be read', async () => {+ deps.processing.mockRejectedValue(new Error('unreadable'));+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'activity-unknown' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ it('does not restart the install when there is nothing to update to', async () => {+ deps.status.mockResolvedValue({+ updateInProgress: false, updateAvailable: false, latestRelease: { version: '1.0.0' },+ lastUpdateResult: null, installState: { outOfSync: false },+ });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'up-to-date' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ it('updates on the main channel only while origin is actually ahead', async () => {+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: true, channel: 'main', minIntervalHours: 6 } });+ deps.prepareRepo.mockResolvedValue({ verdict: { ready: true, behind: 0, defaultBranch: 'main' }, actions: [] });+ deps.status.mockResolvedValue({+ updateInProgress: false, updateAvailable: true, latestRelease: { version: '9.9.9' },+ lastUpdateResult: null, installState: { outOfSync: false },+ });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'up-to-date' });+ expect(deps.appUpdate).not.toHaveBeenCalled();+ });+});++describe('checkout readiness gate', () => {+ const notReady = {+ verdict: { ready: false, needsAgent: true, summary: 'the working tree has uncommitted changes', reasons: ['uncommitted-changes'], repairable: [] },+ actions: [],+ };++ it('refuses to update a checkout that is not clean on the default branch', async () => {+ deps.prepareRepo.mockResolvedValue(notReady);+ deps.queueRepair.mockResolvedValue({ id: 'task-1' });+ const result = await runAutoUpdateTick({ io: {} });+ expect(result).toMatchObject({ ran: false, reason: 'repo-not-ready' });+ expect(deps.selfUpdate).not.toHaveBeenCalled();+ });++ it('queues an agent only for what no script may safely repair', async () => {+ deps.prepareRepo.mockResolvedValue(notReady);+ deps.queueRepair.mockResolvedValue({ id: 'task-1' });+ await runAutoUpdateTick({ io: {} });+ expect(deps.queueRepair).toHaveBeenCalledTimes(1);++ // A checkout the mechanical repairs already fixed reaches `ready` and must+ // never wake an agent — that is the entire repairable/blocking split.+ deps.prepareRepo.mockResolvedValue({ verdict: { ready: true, behind: 1, defaultBranch: 'main' }, actions: ['switched to main'] });+ deps.queueRepair.mockClear();+ await runAutoUpdateTick({ io: {} });+ expect(deps.queueRepair).not.toHaveBeenCalled();+ });++ it('leaves the agent unqueued when the user switched that off', async () => {+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: true, minIntervalHours: 6, resolveBlockersWithAgent: false } });+ deps.prepareRepo.mockResolvedValue(notReady);+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ reason: 'repo-not-ready' });+ expect(deps.queueRepair).not.toHaveBeenCalled();+ });+});++describe('poll registration', () => {+ it('registers nothing while the feature is off, and cancels a live poll', async () => {+ deps.settings.mockResolvedValue({ autoUpdate: { enabled: false } });+ await expect(syncAutoUpdateSchedule()).resolves.toBe(false);+ expect(deps.schedule).not.toHaveBeenCalled();+ expect(deps.cancel).toHaveBeenCalledWith('portos-auto-update');+ });++ it('registers one interval poll when enabled, and is idempotent across saves', async () => {+ await expect(syncAutoUpdateSchedule({ autoUpdate: { enabled: true } })).resolves.toBe(true);+ expect(deps.schedule).toHaveBeenCalledTimes(1);+ expect(deps.schedule.mock.calls[0][0]).toMatchObject({ id: 'portos-auto-update', type: 'interval' });+ // Channel/interval are re-read inside the handler, so changing one must not+ // churn the registration.+ await syncAutoUpdateSchedule({ autoUpdate: { enabled: true, channel: 'main', minIntervalHours: 12 } });+ expect(deps.schedule).toHaveBeenCalledTimes(1);+ });+});++describe('interval baseline', () => {+ it('prefers the most recent of the scheduler run, the manual update, and the arming point', () => {+ const now = Date.parse('2026-01-02T00:00:00Z');+ expect(updateBaselineAt(+ { lastRunAt: '2026-01-01T00:00:00Z', armedAt: '2025-12-01T00:00:00Z' },+ { completedAt: '2026-01-01T12:00:00Z' },+ now,+ )).toBe(Date.parse('2026-01-01T12:00:00Z'));+ });++ // Without a baseline the interval would be measured from the epoch and the+ // first tick after enabling would fire immediately.+ it('falls back to now when nothing has ever been recorded', () => {+ const now = 1_000_000;+ expect(updateBaselineAt({}, null, now)).toBe(now);+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex aac4d45d3a..275d8f85aa 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -82,6 +82,7 @@ import { getVoiceConfig } from './voice/config.js';import { reconcile as reconcileVoice } from './voice/bootstrap.js';import { initVoiceTimers } from './voice/timers.js';import { startBackupScheduler } from './backupScheduler.js';+import { startAutoUpdateScheduler } from './autoUpdateScheduler.js';import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';import { startQuotaBurnScheduler } from './quotaBurnRunner.js';import { startMaintenanceRunScheduler } from './maintenanceRun.js';@@ -442,6 +443,11 @@ const startBackgroundServices = ({ spawnerReady, io }) => {registerPostReminderSchedule({ catchUpMissedSlot: true }).catch(err => logBootstrapFailure('❌ POST reminder init failed', err));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => logBootstrapFailure('❌ Backup scheduler init failed', err));+ // Automatic PortOS self-update — OFF by default. When the user turns it on+ // (Update tab), it polls for a window in which the install is completely idle+ // and then runs the SAME update the matching button runs. Registering the+ // poll launches nothing by itself.+ startAutoUpdateScheduler(io).catch(err => logBootstrapFailure('❌ Auto-update scheduler init failed', err));// Initialize Privacy Center opt-out recheck scheduler — OFF by default; only// re-runs the broker scan + opt-out pass when the user opts in via// Settings → Privacy (sanctioned scheduled-automation exception) (#2145).diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex f658aa0ef8..a40db4031e 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -76,7 +76,8 @@ const defaultState = () => ({updateInProgress: false,updateStartedAt: null,lastUpdateResult: null,- lastForkSync: null+ lastForkSync: null,+ autoUpdate: null});/**@@ -316,6 +317,47 @@ export async function getUpdateStatus() {};}+/**+ * The unattended auto-updater's own durable record — what it last did, when,+ * and why it last stood down. Stored beside the rest of the update state+ * because it is read with it (one file read serves `GET /api/update/status`)+ * and because it must survive the restart the update itself causes.+ *+ * Runtime, NOT configuration: the enabled flag, the channel, and the minimum+ * interval live in `settings.autoUpdate`, which is where a user edits them.+ */+export async function getAutoUpdateRuntime() {+ const state = await loadState();+ return normalizeAutoUpdateRuntime(state.autoUpdate);+}++/** Merge a patch into the runtime record. Returns the merged result. */+export async function recordAutoUpdateRuntime(patch) {+ return withLock(async () => {+ const state = await loadState();+ const next = { ...normalizeAutoUpdateRuntime(state.autoUpdate), ...patch };+ state.autoUpdate = next;+ await saveState(state);+ return next;+ });+}++function normalizeAutoUpdateRuntime(raw) {+ const source = isPlainObject(raw) ? raw : {};+ return {+ // When the feature was switched on with no prior update to measure from.+ // Persisted once and never re-stamped, so an install that reboots often+ // still reaches its first automatic update — re-arming on every boot would+ // push the deadline forever out of reach.+ armedAt: typeof source.armedAt === 'string' ? source.armedAt : null,+ lastAttemptAt: typeof source.lastAttemptAt === 'string' ? source.lastAttemptAt : null,+ lastRunAt: typeof source.lastRunAt === 'string' ? source.lastRunAt : null,+ lastOutcome: typeof source.lastOutcome === 'string' ? source.lastOutcome : null,+ lastSkip: isPlainObject(source.lastSkip) ? source.lastSkip : null,+ repairTaskId: typeof source.repairTaskId === 'string' ? source.repairTaskId : null,+ };+}+/*** Add a version to the ignore list.*/diff --git a/server/services/updateRepoReadiness.js b/server/services/updateRepoReadiness.jsnew file mode 100644index 0000000000..c8139502f4--- /dev/null+++ b/server/services/updateRepoReadiness.js@@ -0,0 +1,256 @@+/**+ * "Is this checkout in a state an unattended update may run against?"+ *+ * An update — either channel — moves the checkout: `update.sh` switches to the+ * default branch and stashes whatever was in the way, and the App Management+ * path runs `updateDefaultBranch`, which checks out, fast-forwards, and falls+ * back to `pull --rebase --autostash`. Both are fine when a human is watching+ * and can read the stash instructions. Unattended, they are not: a stash nobody+ * is told about reads as lost work, and a rebase conflict leaves the install+ * half-updated with nothing to notice it.+ *+ * So the auto-updater refuses to start until the checkout is ON the default+ * branch and CLEAN, and this module is what decides that — plus what can be put+ * right mechanically. Two remedies are safe enough to run unattended, because+ * neither can destroy work:+ *+ * - checking out the default branch from a CLEAN feature branch (the commits+ * stay on the branch ref; nothing is discarded), and+ * - restoring modified auto-generated lockfiles (`npm install` rewrites them+ * as a side effect, and the update reinstalls anyway).+ *+ * Everything else — uncommitted work, an unpushed commit, an interrupted+ * rebase/merge, conflict markers — is judgement no script should make on a+ * user's repository. That queues a CoS task instead, which is the same+ * escalation `appUpdater.failWithGitConflict` already uses for a conflicted+ * managed-app pull.+ */++import { existsSync } from 'fs';+import { join, isAbsolute } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { execGit } from '../lib/execGit.js';+import * as gitService from './git.js';+import { classifyWorktreeDirt } from './worktreeManager.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++/** First line of the repair task — stable so `addTask`'s dedup collapses reruns. */+export const REPO_REPAIR_TASK_DESCRIPTION = 'Restore the PortOS checkout to a clean default branch so automatic updates can run';++/** Why a checkout is not ready, ordered most-blocking first for the UI. */+const REASON_LABELS = {+ 'git-unreadable': 'the checkout could not be inspected',+ 'no-default-branch': 'the origin default branch could not be resolved',+ 'merge-in-progress': 'a merge or rebase is in progress',+ 'conflicted-files': 'the working tree has unresolved conflicts',+ 'uncommitted-changes': 'the working tree has uncommitted changes',+ 'unpushed-commits': 'the default branch has local commits that are not on origin',+ 'detached-head': 'HEAD is detached',+ 'wrong-branch': 'the checkout is not on the default branch',+};++const describe = (code) => REASON_LABELS[code] || code;++/** Absolute paths only — a relative path would resolve against the server's cwd. */+const resolveRepoPath = (repoPath) => (isAbsolute(repoPath || '') ? repoPath : PATHS.root);++async function gitDirPath(repoPath) {+ const result = await execGit(['rev-parse', '--absolute-git-dir'], repoPath, { ignoreExitCode: true });+ return result.exitCode === 0 ? result.stdout.trim() : null;+}++/** An interrupted merge/rebase/cherry-pick leaves a marker in the git dir. */+async function interruptedOperation(repoPath) {+ const gitDir = await gitDirPath(repoPath);+ if (!gitDir) return null;+ const markers = [+ ['MERGE_HEAD', 'merge'],+ ['rebase-merge', 'rebase'],+ ['rebase-apply', 'rebase'],+ ['CHERRY_PICK_HEAD', 'cherry-pick'],+ ['REVERT_HEAD', 'revert'],+ ];+ for (const [name, kind] of markers) {+ if (existsSync(join(gitDir, name))) return kind;+ }+ return null;+}++/** How far HEAD and its origin counterpart have diverged. */+async function divergence(repoPath, branch) {+ const counts = await execGit(+ ['rev-list', '--left-right', '--count', `HEAD...refs/remotes/origin/${branch}`],+ repoPath,+ { ignoreExitCode: true },+ );+ if (counts.exitCode !== 0) return { ahead: null, behind: null };+ const [ahead, behind] = counts.stdout.trim().split(/\s+/).map(Number);+ return {+ ahead: Number.isFinite(ahead) ? ahead : null,+ behind: Number.isFinite(behind) ? behind : null,+ };+}++/**+ * Inspect the checkout without touching it.+ *+ * @param {object} [options]+ * @param {string} [options.repoPath] - defaults to this install's root.+ * @param {boolean} [options.fetch] - refresh origin refs first, so `behind`+ * answers "is there anything to update to?" rather than "was there, last+ * time something fetched?". The auto-updater wants this; a status read for+ * the UI does not.+ * @returns {Promise<object>} the readiness verdict.+ */+export async function checkUpdateRepoReadiness({ repoPath = PATHS.root, fetch = false } = {}) {+ const dir = resolveRepoPath(repoPath);+ const base = {+ repoPath: dir, branch: null, defaultBranch: null, clean: null, lockfilePaths: [], dirtyPaths: [],+ ahead: null, behind: null, reasons: [], repairable: [], ready: false, needsAgent: false,+ };++ if (!(await gitService.isRepo(dir).catch(() => false))) {+ return { ...base, reasons: ['git-unreadable'], needsAgent: false };+ }+ if (fetch) await gitService.fetchOrigin(dir).catch(() => undefined);++ const defaultBranch = await gitService.getDefaultBranch(dir, { strict: true }).catch(() => null);+ const branch = await gitService.getBranch(dir).catch(() => null);+ const porcelain = await gitService.getStatusPorcelain(dir).catch(() => null);+ if (branch === null || porcelain === null) {+ return { ...base, defaultBranch, reasons: ['git-unreadable'] };+ }++ const dirt = classifyWorktreeDirt(porcelain);+ const conflicted = porcelain.split('\n').some((line) => /^(DD|AU|UD|UA|DU|AA|UU) /.test(line));+ const interrupted = await interruptedOperation(dir);+ const detached = branch === 'HEAD';+ const onDefaultBranch = Boolean(defaultBranch) && branch === defaultBranch;+ const { ahead, behind } = defaultBranch ? await divergence(dir, defaultBranch) : { ahead: null, behind: null };++ const reasons = [];+ const repairable = [];+ if (!defaultBranch) reasons.push('no-default-branch');+ if (interrupted) reasons.push('merge-in-progress');+ if (conflicted) reasons.push('conflicted-files');+ if (dirt.hasRealChanges) reasons.push('uncommitted-changes');+ else if (!dirt.clean) repairable.push('restore-lockfiles');+ if (detached) reasons.push('detached-head');+ else if (defaultBranch && !onDefaultBranch) {+ // A clean feature branch is a mechanical checkout away from ready; a dirty+ // one is already refused above, so the branch move is never what loses work.+ if (dirt.hasRealChanges || conflicted || interrupted) reasons.push('wrong-branch');+ else repairable.push('checkout-default');+ }+ // Only meaningful ON the default branch: a feature branch is expected to be+ // ahead, and the checkout-default remedy leaves those commits where they are.+ if (onDefaultBranch && ahead > 0) reasons.push('unpushed-commits');++ return {+ repoPath: dir,+ branch,+ defaultBranch,+ onDefaultBranch,+ clean: dirt.clean,+ lockfileOnlyDirt: !dirt.clean && !dirt.hasRealChanges,+ lockfilePaths: dirt.lockfilePaths,+ dirtyPaths: dirt.realChangePaths,+ interrupted,+ ahead,+ behind,+ reasons,+ repairable,+ // Ready means: nothing to refuse AND nothing left to repair. A repairable+ // checkout becomes ready only after `prepareUpdateRepo` actually repairs it.+ ready: reasons.length === 0 && repairable.length === 0,+ // A checkout that is merely repairable must NOT wake an agent — that is the+ // whole point of the repairable/blocking split.+ needsAgent: reasons.length > 0 && !reasons.includes('git-unreadable'),+ summary: reasons.length ? reasons.map(describe).join('; ') : null,+ };+}++/**+ * Apply the mechanical remedies, then re-inspect.+ *+ * Never destroys work: the only discard is a modified auto-generated lockfile,+ * and the only branch move happens from a clean tree.+ *+ * @returns {Promise<{verdict: object, actions: string[]}>} the POST-repair+ * verdict, plus what was actually done (for the log line and the runtime record).+ */+export async function prepareUpdateRepo({ repoPath = PATHS.root } = {}) {+ const dir = resolveRepoPath(repoPath);+ const before = await checkUpdateRepoReadiness({ repoPath: dir, fetch: true });+ if (before.ready || before.repairable.length === 0) return { verdict: before, actions: [] };++ const actions = [];+ if (before.repairable.includes('restore-lockfiles') && before.lockfilePaths.length) {+ // By explicit path, never `-- .`: the classifier proved these specific+ // paths are auto-generated lockfiles, and a pathspec of `.` would discard+ // anything the classifier had not looked at (a file that appeared between+ // the two calls, say) along with them.+ const restore = await execGit(['checkout', '--', ...before.lockfilePaths], dir, { ignoreExitCode: true });+ if (restore.exitCode === 0) actions.push(`restored ${before.lockfilePaths.length} auto-generated lockfile(s)`);+ }+ if (before.repairable.includes('checkout-default') && before.defaultBranch) {+ const checkout = await execGit(['checkout', before.defaultBranch], dir, { ignoreExitCode: true });+ if (checkout.exitCode === 0) actions.push(`switched to ${before.defaultBranch}`);+ }++ // Re-inspect rather than assuming the remedies worked: a checkout can still+ // fail (a permission problem, a hook), and a verdict that claimed otherwise+ // would hand the updater a checkout it never verified.+ const verdict = await checkUpdateRepoReadiness({ repoPath: dir, fetch: false });+ if (actions.length) console.log(`🧹 Auto-update repo prep: ${actions.join(', ')}`);+ return { verdict, actions };+}++/**+ * Queue a CoS agent to resolve what no script should: uncommitted work, an+ * unpushed commit, an interrupted rebase, conflict markers.+ *+ * The first line is constant, so `addTask`'s description+app dedup collapses+ * every subsequent tick onto the one open task instead of queueing an agent per+ * poll. The task store is imported lazily — this module is on the update path,+ * the repair branch is rare, and a static import would pull the whole CoS state+ * graph into that closure.+ *+ * Never rejects: a failed enqueue must not mask the readiness refusal itself.+ *+ * @returns {Promise<{id: string, duplicate?: boolean}|null>}+ */+export async function queueRepoRepairTask(verdict) {+ const context = [+ 'Automatic PortOS updates are configured, but they are held back because this checkout is not in a state an unattended update may run against.',+ '',+ `Repository: ${verdict.repoPath}`,+ `Current branch: ${verdict.branch || 'unknown'}`,+ `Default branch: ${verdict.defaultBranch || 'unknown'}`,+ verdict.interrupted ? `Interrupted operation: ${verdict.interrupted}` : null,+ Number.isFinite(verdict.ahead) ? `Local commits not on origin: ${verdict.ahead}` : null,+ '',+ 'What is blocking the update:',+ ...verdict.reasons.map((code, index) => `${index + 1}. ${describe(code)}`),+ '',+ `Resolve it so the checkout ends up clean on ${verdict.defaultBranch || 'the default branch'}: finish or abort any in-progress `+ + 'rebase/merge, land or park uncommitted work (commit and open a PR, or restore it — never discard it silently), '+ + 'and push or PR any local commits that are not on origin. Do not run the update itself; PortOS resumes automatically '+ + 'once the checkout is clean.',+ '',+ 'Work in the primary checkout, not a worktree — the state that needs fixing is there.',+ ].filter((line) => line !== null).join('\n');++ return import('./cosTaskStore.js')+ .then(({ addTask }) => addTask({+ description: REPO_REPAIR_TASK_DESCRIPTION,+ priority: 'HIGH',+ app: PORTOS_APP_ID,+ context,+ useWorktree: false,+ }, 'internal'))+ .catch((err) => {+ console.error(`❌ Failed to queue auto-update repo repair task: ${err.message}`);+ return null;+ });+}diff --git a/server/services/updateRepoReadiness.test.js b/server/services/updateRepoReadiness.test.jsnew file mode 100644index 0000000000..d86ce223f7--- /dev/null+++ b/server/services/updateRepoReadiness.test.js@@ -0,0 +1,108 @@+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { execFileSync } from 'child_process';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';++// Real git repositories, not a mocked porcelain string: this module decides+// whether an UNATTENDED process may move a user's checkout, and the thing that+// would make that wrong is git behaving differently from the fixture.+const { checkUpdateRepoReadiness, prepareUpdateRepo } = await import('./updateRepoReadiness.js');++const repos = [];+const git = (dir, ...args) => execFileSync('git', args, { cwd: dir, encoding: 'utf-8' });++function makeRepo() {+ const origin = mkdtempSync(join(tmpdir(), 'portos-origin-'));+ const clone = mkdtempSync(join(tmpdir(), 'portos-clone-'));+ repos.push(origin, clone);+ git(origin, 'init', '--bare', '--initial-branch=main');+ git(process.cwd(), 'clone', origin, clone);+ git(clone, 'config', 'user.email', '[email protected]');+ git(clone, 'config', 'user.name', 'Example Tester');+ writeFileSync(join(clone, 'README.md'), 'seed\n');+ writeFileSync(join(clone, 'package-lock.json'), '{"lockfileVersion":3}\n');+ git(clone, 'add', '-A');+ git(clone, 'commit', '-m', 'seed');+ git(clone, 'push', 'origin', 'main');+ git(clone, 'remote', 'set-head', 'origin', 'main');+ return clone;+}++beforeEach(() => vi.restoreAllMocks());+afterAll(() => repos.forEach((dir) => rmSync(dir, { recursive: true, force: true })));++describe('update repo readiness', () => {+ it('reports a clean checkout on the default branch as ready', async () => {+ const verdict = await checkUpdateRepoReadiness({ repoPath: makeRepo() });+ expect(verdict).toMatchObject({ ready: true, needsAgent: false, branch: 'main', defaultBranch: 'main', clean: true });+ });++ // Uncommitted work is the case the whole gate exists for: update.sh would+ // stash it and print recovery instructions nobody is there to read.+ it('refuses uncommitted work and escalates it rather than repairing it', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, 'README.md'), 'edited by the user\n');+ const verdict = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(verdict).toMatchObject({ ready: false, needsAgent: true });+ expect(verdict.reasons).toContain('uncommitted-changes');+ expect(verdict.repairable).toEqual([]);+ });++ it('refuses a local commit that is not on origin', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, 'README.md'), 'local work\n');+ git(repo, 'commit', '-am', 'local only');+ const verdict = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(verdict).toMatchObject({ ready: false, needsAgent: true, ahead: 1 });+ expect(verdict.reasons).toContain('unpushed-commits');+ });++ it('refuses an interrupted merge', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, '.git', 'MERGE_HEAD'), 'deadbeef\n');+ const verdict = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(verdict).toMatchObject({ ready: false, needsAgent: true, interrupted: 'merge' });+ });++ // A clean feature branch loses nothing when the checkout moves: the commits+ // stay on the branch ref. That is what makes this remedy safe unattended.+ it('switches a clean feature branch back to the default branch itself', async () => {+ const repo = makeRepo();+ git(repo, 'checkout', '-b', 'feature/example');+ writeFileSync(join(repo, 'README.md'), 'feature work\n');+ git(repo, 'commit', '-am', 'feature commit');++ const before = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(before).toMatchObject({ ready: false, needsAgent: false });+ expect(before.repairable).toContain('checkout-default');++ const { verdict, actions } = await prepareUpdateRepo({ repoPath: repo });+ expect(actions).toContain('switched to main');+ expect(verdict).toMatchObject({ ready: true, branch: 'main' });+ // The branch — and its commit — still exist; nothing was discarded.+ expect(git(repo, 'branch', '--list', 'feature/example')).toContain('feature/example');+ });++ it('restores a rewritten lockfile without touching anything else', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, 'package-lock.json'), '{"lockfileVersion":3,"rewritten":true}\n');+ const before = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(before).toMatchObject({ ready: false, needsAgent: false, lockfileOnlyDirt: true });++ const { verdict, actions } = await prepareUpdateRepo({ repoPath: repo });+ expect(actions.join(' ')).toMatch(/lockfile/);+ expect(verdict.ready).toBe(true);+ });++ // A dirty feature branch must NOT be silently moved — the checkout that would+ // carry the dirt along is exactly the surprise this gate prevents.+ it('does not move a dirty feature branch', async () => {+ const repo = makeRepo();+ git(repo, 'checkout', '-b', 'feature/dirty');+ writeFileSync(join(repo, 'README.md'), 'work in progress\n');+ const { verdict, actions } = await prepareUpdateRepo({ repoPath: repo });+ expect(actions).toEqual([]);+ expect(verdict).toMatchObject({ ready: false, needsAgent: true, branch: 'feature/dirty' });+ });+});diff --git a/server/sockets/apps.js b/server/sockets/apps.jsindex dc662b9dbf..5d99ae293b 100644--- a/server/sockets/apps.js+++ b/server/sockets/apps.js@@ -1,11 +1,9 @@import { streamDetection } from '../services/streamingDetect.js';import * as pm2Standardizer from '../services/pm2Standardizer.js';import * as appsService from '../services/apps.js';-import { logAction } from '../services/history.js';-import * as appUpdater from '../services/appUpdater.js';import * as appDeployer from '../services/appDeployer.js';-import { checkPortosUpdatePreflight } from '../services/updatePreflight.js';-import { PORTOS_APP_ID } from '../lib/appIdentity.js';+import { runAppUpdate } from '../services/appUpdateRunner.js';+import { activeOperationsPayload, claimAppOperation, endAppOperation, recordOperationStep } from '../services/appOperations.js';import {appDeploySchema,appStandardizeSchema,@@ -15,70 +13,11 @@ import {validateSocketData} from '../lib/socketValidation.js';-// In-flight app update/standardize operations, keyed by app id. These run for-// minutes and outlive the page that dispatched them, so the server owns both-// the re-entrancy guard and the resumable progress buffer.-const activeAppOperations = new Map();--// One operation occupies several keys, so collapse them back to one row.-// repoPath stays server-side: the client only needs to name and render the run.-const activeOperationsPayload = () => ({- operations: [...new Set(activeAppOperations.values())].map(({ repoPath: _repoPath, ...op }) => op)-});--// Two app records may point at the same checkout, so the app id alone doesn't-// identify the resource being mutated — an operation is registered under every-// key that names the resource it is mutating.-const operationKeys = (app) => (app.repoPath && app.repoPath !== app.id ? [app.id, app.repoPath] : [app.id]);--const findConflictingOperation = (app) => operationKeys(app)- .map(key => activeAppOperations.get(key))- .find(Boolean);--// Refuse rather than overwrite: a caller that reaches the registry without-// going through claimAppOperation must not be able to silently clobber a live-// run out of the map and orphan its step buffer.-const setOperationKey = (key, operation) => {- if (activeAppOperations.has(key)) throw new Error(`App operation already in flight for ${key}`);- activeAppOperations.set(key, operation);-};--// Claim the resource for this run. The conflict check and the registry write-// are one synchronous step — an await between them is what let two overlapping-// dispatches both pass the check, both run, and then delete each other's-// record (#6638). Callers must claim BEFORE any further await.-const claimAppOperation = (io, app, type) => {- const inFlight = findConflictingOperation(app);- if (inFlight) return { ok: false, inFlight };- const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now(), repoPath: app.repoPath };- for (const key of operationKeys(app)) setOperationKey(key, operation);- io.emit('app:operations:active', activeOperationsPayload());- return { ok: true, operation };-};--// A PortOS self-update deliberately leaves its operation registered: the-// process is about to be replaced, so the map dies with it. A test driving that-// path has no process boundary, so it needs a way back to an empty set.-export const __resetAppOperations = () => activeAppOperations.clear();--// Clear every key this operation holds, and only the keys pointing at THIS-// operation — a run that already finished must not evict a live sibling.-const endAppOperation = (io, appId) => {- const operation = activeAppOperations.get(appId);- if (!operation) return;- for (const [key, op] of activeAppOperations) {- if (op === operation) activeAppOperations.delete(key);- }- io.emit('app:operations:active', activeOperationsPayload());-};--// Record a step into the operation's buffer using the same last-write-wins-// per-step semantics the client renders with.-const recordOperationStep = (operation, frame) => {- const existing = operation.steps.findIndex(s => s.step === frame.step);- if (existing >= 0) operation.steps[existing] = frame;- else operation.steps.push(frame);-};+// The in-flight operation registry lives in services/appOperations.js — the+// unattended auto-updater claims the same resource through it, and the Live+// activity snapshot reads it. Re-exported here because the socket suite drives+// the reset through this module.+export { __resetAppOperations } from '../services/appOperations.js';export const registerAppHandlers = (socket, io) => {socket.on('detect:start', async (rawData) => {@@ -121,102 +60,48 @@ export const registerAppHandlers = (socket, io) => {}});+ // The update itself — the claim, the PortOS preflight refusals, the run, the+ // ledger row — lives in services/appUpdateRunner.js, because the unattended+ // auto-updater dispatches the identical action without a socket. This handler+ // owns only what is socket-shaped: validation, and routing the two refusals+ // that belong to the person who clicked back to THEIR socket rather than the+ // io bus. They are emitted directly (not thrown) so only that error event+ // fires — falling to the catch below would also fire app:update:complete with+ // success:false, which overwrites the message client-side+ // (useAppOperation's onDone patch).socket.on('app:update', async (rawData) => {- let operatingAppId = null;- let result = null;+ let appId = null;try {const data = validateSocketData(appUpdateSchema, rawData, socket, 'app:update');if (!data) return;+ appId = data.appId;- const app = await appsService.getAppById(data.appId);- if (!app) {+ const outcome = await runAppUpdate({+ io,+ appId: data.appId,+ syncFork: data.syncFork === true,+ acknowledgeFork: data.acknowledgeFork === true,+ acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,+ });+ if (outcome.ok) return;+ if (outcome.reason === 'not-found') {socket.emit('app:update:error', { message: 'App not found' });return;}-- // Claimed here, immediately after the app record resolves and BEFORE the- // preflight await below — the claim has to cover every await that- // precedes the actual update, or two dispatches land inside the gap.- const claim = claimAppOperation(io, app, 'update');- if (!claim.ok) {+ if (outcome.reason === 'duplicate') {socket.emit('app:update:error', {- appId: app.id,+ appId: data.appId,duplicate: true,- message: `An ${claim.inFlight.type} is already running for ${claim.inFlight.appName}`+ message: `An ${outcome.inFlight.type} is already running for ${outcome.inFlight.appName}`});return;}- const operation = claim.operation;- operatingAppId = app.id;-- // PortOS is itself a managed app, and updating it restarts the whole- // install — apply the same refusals POST /api/update/execute enforces- // (a live CoS agent, in-flight Persistent Mind image work, an- // unacknowledged fork) so App Management can't restart out from under- // them just because it dispatches through this socket instead (#5984).- // Emitted directly (not thrown) so only this error event fires — letting- // it fall to the outer catch below would also fire app:update:complete- // with success:false, which overwrites this message with a generic one- // client-side (useAppOperation's onDone patch).- if (app.id === PORTOS_APP_ID) {- const refusal = await checkPortosUpdatePreflight({- acknowledgeFork: data.acknowledgeFork === true,- acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,- }).then(() => null, (err) => err);- if (refusal) {- endAppOperation(io, app.id);- operatingAppId = null;- socket.emit('app:update:error', { appId: app.id, code: refusal.code, message: refusal.message });- return;- }- }-- console.log(`⬇️ Socket update started for ${app.name}`);- const emit = (step, status, message) => {- const frame = { appId: app.id, step, status, message, timestamp: Date.now() };- recordOperationStep(operation, frame);- io.emit('app:update:step', frame);- };-- let failure = null;- result = await appUpdater.updateApp(app, emit, {- syncFork: data.syncFork === true,- acknowledgeFork: data.acknowledgeFork === true,- acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,- }).catch(err => {- failure = err;- // Refusals raised inside the update (the PortOS launcher's post-lock- // re-check, say) carry the same acknowledgement codes the pre-check- // emits above — the panel's retry buttons key on `code`, so dropping it- // here would leave a refusal the user could have acted on inert.- io.emit('app:update:error', { appId: app.id, code: err.code || null, message: err.message });- return null;- });-- // The ledger and the apps-changed broadcast are the socket path's job now- // that it is the only way to update an app — a thrown update still gets a- // row, with success:false, rather than vanishing from the history.- await logAction('update', app.id, app.name, { steps: result?.steps ?? [] }, result?.success === true, failure?.message ?? null);- appsService.notifyAppsChanged('update', app.id);-- if (result?.selfUpdateStarted) {- // update.sh will `pm2 delete` THIS process partway through, so there is- // no completion to report and nothing after the restart to clear the- // operation. Leaving it registered (the map dies with the process) is- // what keeps the row rendering the script's STEP: frames right up to- // the moment the server goes down.- console.log(`♻️ PortOS self-update handed off — update.sh will restart this process`);- } else if (result) {- io.emit('app:update:complete', { appId: app.id, success: result.success, steps: result.steps });- console.log(`✅ Socket update complete for ${app.name}`);- }+ socket.emit('app:update:error', { appId: outcome.appId, code: outcome.code, message: outcome.message });} catch (err) {const message = err?.message ?? String(err);console.error(`❌ Socket handler error [app:update]: ${message}`);- io.emit('app:update:error', { appId: operatingAppId, code: err?.code || null, message });- io.emit('app:update:complete', { appId: operatingAppId, success: false, steps: [] });- } finally {- if (operatingAppId && !result?.selfUpdateStarted) endAppOperation(io, operatingAppId);+ io.emit('app:update:error', { appId, code: err?.code || null, message });+ io.emit('app:update:complete', { appId, success: false, steps: [] });}});