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
simplify: never write to the checkout before the idle gate, and stop paying for reads the gates discard
[._.]/ Adam Eivycba12015176e
diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.jsxindex ebeb957972..f8bbdd081c 100644--- a/client/src/components/apps/tabs/AutoUpdatePanel.jsx+++ b/client/src/components/apps/tabs/AutoUpdatePanel.jsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { AlertTriangle, Bot, Check, Clock, GitBranch, Loader, Tag } from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';@@ -41,14 +41,23 @@ export default function AutoUpdatePanel() {const runtime = status?.runtime;const repo = status?.repo;const activity = status?.activity;+ // Clamp bounds come from the server (`storableAutoUpdateConfig`'s schema+ // enforces the same pair), so the form can't drift into values the PUT 400s on.+ const bounds = status?.bounds?.minIntervalHours || { min: 1, max: 720 };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.+ // Re-seed when the SERVER's value changes — compared against the last config+ // it sent, not against the draft. Comparing against the draft would read the+ // user's half-typed interval as staleness and overwrite it on the next 15s+ // poll, which is the opposite of what this effect is for.+ const lastServerConfig = useRef(null);useEffect(() => {- if (config) setDraft((prev) => (prev && JSON.stringify(prev) === JSON.stringify(config) ? prev : config));+ if (!config) return;+ const serialized = JSON.stringify(config);+ if (serialized === lastServerConfig.current) return;+ lastServerConfig.current = serialized;+ setDraft(config);}, [config]);if (!draft) return null;@@ -66,7 +75,7 @@ export default function AutoUpdatePanel() {setDraft(config);return;}- refetch?.();+ refetch();};const blockers = activity?.blockers || [];@@ -135,13 +144,13 @@ export default function AutoUpdatePanel() {<inputid="auto-update-interval"type="number"- min={1}- max={720}+ min={bounds.min}+ max={bounds.max}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));+ const hours = Math.min(bounds.max, Math.max(bounds.min, Number(e.target.value) || bounds.min));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"diff --git a/client/src/components/dashboard/ActiveProcessingWidget.jsx b/client/src/components/dashboard/ActiveProcessingWidget.jsxindex 1bf4a8a656..eccccb49c4 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.jsx@@ -73,19 +73,6 @@ function LaneRow({ to, icon: Icon, label, detail }) {);}-// `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,@@ -97,7 +84,10 @@ function ActiveProcessingWidget() {const mind = data?.mind;const appOperations = data?.appOperations || [];const activeAgents = data?.agents?.active || 0;- const activity = data ? (data.activity || localActivity(data)) : null;+ // Derived server-side (server/lib/systemIdle.js) and rendered as sent: the+ // unattended auto-updater refuses to restart the install on this same verdict,+ // so a second definition here is exactly what that module exists to prevent.+ const activity = data?.activity ?? null;const idle = !activity || activity.idle;const runningJobs = jobs.filter((job) => job.status !== 'queued').length;return (diff --git a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx b/client/src/components/dashboard/ActiveProcessingWidget.test.jsxindex 2db51e4502..abc5c986be 100644--- a/client/src/components/dashboard/ActiveProcessingWidget.test.jsx+++ b/client/src/components/dashboard/ActiveProcessingWidget.test.jsx@@ -44,10 +44,13 @@ describe('ActiveProcessingWidget', () => {extras: { imageTo3d: [{ id: 'model-1', name: 'Example mesh' }] },agents: { active: 2, queued: 1 },mind: { trusted: true, thinking: false, queued: 0 },+ // Sent by the server (lib/systemIdle.js) and rendered as-is — the widget+ // deliberately has no second definition of "idle" to fall back on.+ activity: { idle: false, activeCount: 4, queuedCount: 2, blockers: [] },});renderWidget();- // Running and queued are counted separately now: a queued render is real- // work waiting on the user, not part of the "active" tally.+ // Running and queued are counted separately: 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();diff --git a/client/src/lib/textUtils.js b/client/src/lib/textUtils.jsindex 2d75dc4a54..f7344765c6 100644--- a/client/src/lib/textUtils.js+++ b/client/src/lib/textUtils.js@@ -1,7 +1,7 @@/*** Pure prose helpers, from the module that owns them on both sides.*- * `escapeRegExp`, `countWords`, `isStr` and `isNonBlankStr` are named+ * `escapeRegExp`, `countWords`, `isStr`, `isNonBlankStr` and `pluralize` are named* re-exports of `server/lib/textUtils.js` — imported rather than copied so the* two runtimes cannot drift: the word count the Writers Room and autobiography* editors show beside a draft is the same `\S+` rule the server stores for it,@@ -11,11 +11,5 @@* caller for; the file itself stays so every `lib/textUtils` import path in the* client is unchanged.*/-export { countWords, escapeRegExp, isStr, isNonBlankStr } from '../../../server/lib/textUtils.js';+export { countWords, escapeRegExp, isStr, isNonBlankStr, pluralize } from '../../../server/lib/textUtils.js';-/**- * `pluralize(1, 'item')` → "1 item"; `pluralize(2, 'item')` → "2 items".- * Pass a third arg for an irregular plural: `pluralize(1, 'person', 'people')`.- */-export const pluralize = (count, singular, pluralForm = `${singular}s`) =>- `${count} ${count === 1 ? singular : pluralForm}`;diff --git a/docs/README.md b/docs/README.mdindex 46bcbf768e..7b61366cce 100644--- a/docs/README.md+++ b/docs/README.md@@ -27,7 +27,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions || [GITHUB_ACTIONS.md](./GITHUB_ACTIONS.md) | CI and release workflows || [VERSIONING.md](./VERSIONING.md) | SemVer + release process (`/do:release`) |-| [SELF_UPDATE.md](./SELF_UPDATE.md) | Fork-aware self-update flow — release polling, `FORK_SYNC_REQUIRED`, fork sync, running a customized fork |+| [SELF_UPDATE.md](./SELF_UPDATE.md) | Fork-aware self-update flow — release polling, `FORK_SYNC_REQUIRED`, fork sync, running a customized fork, and the unattended idle-gated automatic update || [MANAGED_APP_UPDATES.md](./MANAGED_APP_UPDATES.md) | Safe managed-app update default and the opt-in app lifecycle contract || [MANAGED_APP_FORGE_ACCOUNTS.md](./MANAGED_APP_FORGE_ACCOUNTS.md) | Running managed apps under a second GitHub account — ssh `Host` aliases and the per-app `forgeAccount` pin || [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict |diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.jsindex 2f22a5eec3..46048a3fe6 100644--- a/server/lib/sharedSchemas.js+++ b/server/lib/sharedSchemas.js@@ -244,3 +244,18 @@ export function resolveAutoUpdateConfig(raw) {resolveBlockersWithAgent: source.resolveBlockersWithAgent !== false,};}++/**+ * The resolved config MINUS the derived `minIntervalMs`, i.e. exactly the keys+ * `autoUpdateSettingsSchema` accepts.+ *+ * Every surface that shows the effective config also hands it back on the next+ * save (the panel PUTs `{...draft, ...patch}`), and the schema is `.strict()` —+ * so echoing a derived key turns every toggle into a 400. One projection, used+ * by both the settings GET and `GET /api/update/auto`, is what keeps the two+ * from having to remember that separately.+ */+export function storableAutoUpdateConfig(raw) {+ const { minIntervalMs: _derived, ...storable } = resolveAutoUpdateConfig(raw);+ return storable;+}diff --git a/server/lib/systemIdle.js b/server/lib/systemIdle.jsindex ae4ee5819f..94640584f6 100644--- a/server/lib/systemIdle.js+++ b/server/lib/systemIdle.js@@ -25,6 +25,8 @@* the auto-update runtime record on disk.*/+import { pluralize } from './textUtils.js';+/** Media kinds the queue runs, mapped to the noun a blocker line uses. */const MEDIA_NOUNS = {image: 'image render',@@ -33,8 +35,6 @@ const MEDIA_NOUNS = {training: 'training run',};-const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;-const mediaNoun = (kind) => MEDIA_NOUNS[kind] || 'media job';/**@@ -67,19 +67,19 @@ export function summarizeSystemActivity(snapshot) {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);+ add(`media-running:${kind}`, `${pluralize(count, mediaNoun(kind))} running`, count);}for (const [kind, count] of countByKind(jobs, 'queued')) {- add(`media-queued:${kind}`, `${plural(count, mediaNoun(kind))} queued`, count);+ add(`media-queued:${kind}`, `${pluralize(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);+ if (imageTo3d > 0) add('image-to-3d', `${pluralize(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);+ if (activeAgents > 0) add('agents-running', `${pluralize(activeAgents, 'CoS agent')} running`, activeAgents);const queuedAgents = Number(snapshot?.agents?.queued) || 0;- if (queuedAgents > 0) add('agents-queued', `${plural(queuedAgents, 'CoS task')} queued`, queuedAgents);+ if (queuedAgents > 0) add('agents-queued', `${pluralize(queuedAgents, 'CoS task')} queued`, queuedAgents);const mind = snapshot?.mind;// An unreadable Persistent Mind state is NOT an idle one: the update path@@ -91,12 +91,12 @@ export function summarizeSystemActivity(snapshot) {} 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);+ if (queuedMessages > 0) add('mind-queued', `${pluralize(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);+ add('app-operations', `${pluralize(appOperations.length, 'app operation')} running`, appOperations.length);}if (snapshot?.update?.inProgress) add('update-in-progress', 'An update is already running', 1);diff --git a/server/lib/textUtils.js b/server/lib/textUtils.jsindex 72cbd3304d..7cb9f05a7d 100644--- a/server/lib/textUtils.js+++ b/server/lib/textUtils.js@@ -198,3 +198,13 @@ export function kebabCase(text) {.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');}++/**+ * `pluralize(1, 'item')` → "1 item"; `pluralize(2, 'item')` → "2 items".+ * Pass a third arg for an irregular plural: `pluralize(1, 'person', 'people')`.+ *+ * Lives here rather than in the client mirror because the server builds+ * user-facing count prose too (`lib/systemIdle.js`'s activity blockers).+ */+export const pluralize = (count, singular, pluralForm = `${singular}s`) =>+ `${count} ${count === 1 ? singular : pluralForm}`;diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 328a155434..c174994f38 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -21,7 +21,7 @@ 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 { storableAutoUpdateConfig } 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';@@ -182,13 +182,10 @@ const projectEffectiveBackup = (safe) => {// 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 } };-};+const projectEffectiveAutoUpdate = (safe) => ({+ ...safe,+ autoUpdate: { ...safe.autoUpdate, ...storableAutoUpdateConfig(safe.autoUpdate) },+});// 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: stripdiff --git a/server/routes/update.js b/server/routes/update.jsindex ecac11e0c5..b33bba401d 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -5,6 +5,11 @@ import { validateRequest } from '../lib/validation.js';import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';import * as updateChecker from '../services/updateChecker.js';import { startPortosSelfUpdate } from '../services/portosSelfUpdate.js';+import {+ AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX,+ AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN,+ storableAutoUpdateConfig,+} from '../lib/sharedSchemas.js';import {countActiveCosAgents,getPersistentMindImageWorkGuard,@@ -50,29 +55,42 @@ router.get('/status', asyncHandler(async (req, res) => {// 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).+// Its OWN route rather than a block on /status, and the three service imports+// are deferred, for one reason each: /status is polled every few seconds while+// this tab is open and must not drag a git status walk along at that cadence,+// and a static import of the activity/readiness graph would pull the whole CoS+// + git subtree into every suite that mounts this router (see "Import scoping"+// in server/AGENTS.md). `sharedSchemas` is already in this module's static+// closure through validation.js, so it stays a plain import.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([+ const [{ getSettings }, { checkUpdateRepoReadiness }, { getSystemActivity }] = await Promise.all([+ import('../services/settings.js'),+ import('../services/updateRepoReadiness.js'),+ import('../services/activeProcessing.js'),+ ]);+ const [settings, runtime] = 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),]);+ const config = storableAutoUpdateConfig(settings?.autoUpdate);+ // The two expensive halves answer "what is the scheduler waiting for", which+ // is not a question while the scheduler is off — and this route is polled+ // every 15s by an open Update tab on an install where the feature ships OFF.+ // No fetch either way: refreshing origin refs is the scheduler's own tick,+ // not a network hop every viewer of this tab pays for.+ const [repo, processing] = config.enabled+ ? await Promise.all([+ checkUpdateRepoReadiness({ fetch: false }).catch(() => null),+ getSystemActivity().catch(() => null),+ ])+ : [null, null];res.json({- config: resolveAutoUpdateConfig(settings?.autoUpdate),+ // Storable keys only — the panel hands this straight back on the next save,+ // and the settings schema is strict.+ config,+ // Server-authoritative bounds so the form's clamp can't drift from what the+ // schema enforces (the `parallelLimitBounds` pattern in routes/settings.js).+ bounds: { minIntervalHours: { min: AUTO_UPDATE_MIN_INTERVAL_HOURS_MIN, max: AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX } },runtime,repo,activity: processing?.activity ?? null,diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex b18a35623a..ec26762a68 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -38,38 +38,75 @@ function summarizeMind(snapshot) {};}-export async function getActiveProcessing() {- const [capability, jobs, models, loadedModels, pendingTaskIds, agents, mindState] = await Promise.all([- getCudaCapability(),+/**+ * Active vs queued CoS agents, from ONE read of the agent list.+ *+ * A task stays 'pending' until spawnAgentForTask flips it to 'in_progress',+ * which happens AFTER its agent is registered as running — so a snapshot taken+ * in between would count one task as queued AND active, and the widget read+ * 'N active, N queued' for a queue of N. A task a live agent holds is active.+ *+ * When the agent list is readable, BOTH counts come off that one read: taking+ * `active` from `getStatus()` and `queued` from here would let the two skew+ * against each other, which is the same defect one layer up. When it is NOT+ * readable (`agents === null`), there is no claim set to subtract — fall back to+ * `getStatus()`'s own tally rather than reporting zero active agents while still+ * counting their tasks as queued, which would understate BOTH numbers at once.+ */+function agentCounts(agents, cosStatus, pendingTaskIds) {+ const runningAgents = agents === null ? null : agents.filter((agent) => agent.status === 'running');+ const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));+ return {+ active: runningAgents ? runningAgents.length : (cosStatus?.activeAgents || 0),+ queued: pendingTaskIds.filter((id) => !claimedTaskIds.has(id)).length,+ };+}++/**+ * Just the slices `summarizeSystemActivity` reads, plus the verdict.+ *+ * Split out because two callers — `GET /api/update/auto` and the auto-update+ * tick — want only `activity`, and the full snapshot also shells out to+ * nvidia-smi and makes an HTTP request to Ollama, whose latency is unbounded+ * when the daemon is wedged. Neither feeds the verdict.+ */+export async function getSystemActivity() {+ const [jobs, models, pendingTaskIds, agents, mindState] = await Promise.all([Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),listGeneratingModelSummaries().catch(() => []),- getLoadedModels().catch(() => []),cos.getPendingTaskIds().catch(() => []),// `null` = the read FAILED, distinct from `[]` = read fine, no agents. The- // counts below degrade differently for the two, so they must stay separable.+ // counts 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 slices = {+ jobs: jobs.map(sanitizeJob),+ extras: { imageTo3d: models.map((model) => ({ id: model.id, name: model.name || model.id })) },+ agents: agentCounts(agents, cosStatus, pendingTaskIds),+ 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() },+ };+ return { ...slices, activity: summarizeSystemActivity(slices) };+}++export async function getActiveProcessing() {+ const [capability, activity, loadedModels] = await Promise.all([+ getCudaCapability(),+ getSystemActivity(),+ getLoadedModels().catch(() => []),+ ]);const utilization = capability.status === 'available' ? await getCudaUtilization() : { status: capability.status, gpus: [] };- // A task stays 'pending' until spawnAgentForTask flips it to 'in_progress',- // which happens AFTER its agent is registered as running — so a snapshot taken- // in between would count one task as queued AND active, and the widget read- // 'N active, N queued' for a queue of N. A task a live agent holds is active.- //- // When the agent list is readable, BOTH counts come off that one read: taking- // `active` from `getStatus()` and `queued` from here would let the two skew- // against each other, which is the same defect one layer up. When it is NOT- // readable, there is no claim set to subtract — fall back to `getStatus()`'s- // own tally rather than reporting zero active agents while still counting- // their tasks as queued, which would understate BOTH numbers at once.- const runningAgents = agents === null ? null : agents.filter((agent) => agent.status === 'running');- const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));- const pendingTasks = pendingTaskIds.filter((id) => !claimedTaskIds.has(id)).length;const gpuBusy = Boolean(getRunningJob());- const snapshot = {+ return {+ ...activity,updatedAt: new Date().toISOString(),gpu: {status: capability.status,@@ -82,23 +119,6 @@ export async function getActiveProcessing() {memoryTotalMib: gpu.memoryTotalMib ?? gpu.vramMib ?? null,})),},- jobs: jobs.map(sanitizeJob),- extras: {- imageTo3d: models.map((model) => ({ id: model.id, name: model.name || model.id })),- ollama: loadedModels,- },- agents: {- 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() },+ extras: { ...activity.extras, ollama: loadedModels },};- // 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/appOperations.js b/server/services/appOperations.jsindex e6593623fd..6e66ca553d 100644--- a/server/services/appOperations.js+++ b/server/services/appOperations.js@@ -13,18 +13,16 @@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.+ * The live operations as rows — id, name, type, age. One operation occupies+ * several keys, so they collapse back to one row; repoPath stays server-side,+ * since the client only needs to name and render the run.*/-export const listActiveAppOperations = () => activeOperationsPayload().operations;+export const listActiveAppOperations = () =>+ [...new Set(activeAppOperations.values())].map(({ repoPath: _repoPath, ...op }) => op);++/** The same rows in the shape the `app:operations:active` frame carries. */+export const activeOperationsPayload = () => ({ operations: listActiveAppOperations() });// 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 everydiff --git a/server/services/appUpdateRunner.js b/server/services/appUpdateRunner.jsindex c0db2a5f1c..3075f4b5cc 100644--- a/server/services/appUpdateRunner.js+++ b/server/services/appUpdateRunner.js@@ -31,11 +31,11 @@ import { PORTOS_APP_ID } from '../lib/appIdentity.js';* @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}+ * | {ok: false, reason: 'not-found'|'duplicate'|'refused', appId: string|null, code: string|null, message: string}+ * | {ok: true}* >}+ * Every refusal carries a rendered `message`; a caller decides only WHERE it+ * goes (the dispatching socket, or a log line), never how it reads.*/export async function runAppUpdate({io,@@ -45,13 +45,21 @@ export async function runAppUpdate({acknowledgePersistentMindImageBackup = false,}) {const app = await appsService.getAppById(appId);- if (!app) return { ok: false, reason: 'not-found' };+ if (!app) return { ok: false, reason: 'not-found', appId: null, code: null, message: 'App 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 };+ if (!claim.ok) {+ return {+ ok: false,+ reason: 'duplicate',+ appId: app.id,+ code: null,+ message: `An ${claim.inFlight.type} is already running for ${claim.inFlight.appName}`,+ };+ }const operation = claim.operation;let operatingAppId = app.id;let result = null;@@ -114,7 +122,10 @@ export async function runAppUpdate({console.log(`✅ Update complete for ${app.name}`);}- return { ok: true, appId: app.id, result, selfUpdateStarted: result?.selfUpdateStarted === true, failure };+ // The run's own outcome is already on the io bus (`app:update:complete` /+ // `app:update:error`) and in the history ledger, which is where both callers+ // read it from — so the return says only "this dispatch was accepted".+ return { ok: true };} finally {if (operatingAppId && !result?.selfUpdateStarted) endAppOperation(io, operatingAppId);}diff --git a/server/services/autoUpdateScheduler.js b/server/services/autoUpdateScheduler.jsindex 2379cce15a..02f3dcbf37 100644--- a/server/services/autoUpdateScheduler.js+++ b/server/services/autoUpdateScheduler.js@@ -10,14 +10,17 @@* 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+ * 4. The checkout is on the default branch and clean, or is one mechanical+ * repair away (`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).*+ * Nothing on disk is WRITTEN until every one of those has passed: the checkout+ * repairs run after the idle gate, never before it.+ ** 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`@@ -33,10 +36,10 @@import { schedule, cancel } from './eventScheduler.js';import { getSettings, settingsEvents } from './settings.js';-import { getActiveProcessing } from './activeProcessing.js';+import { getSystemActivity } from './activeProcessing.js';import { startPortosSelfUpdate } from './portosSelfUpdate.js';import { runAppUpdate } from './appUpdateRunner.js';-import { prepareUpdateRepo, queueRepoRepairTask } from './updateRepoReadiness.js';+import { checkUpdateRepoReadiness, prepareUpdateRepo, queueRepoRepairTask } from './updateRepoReadiness.js';import * as updateChecker from './updateChecker.js';import { describeActivityBlockers } from '../lib/systemIdle.js';import { resolveAutoUpdateConfig } from '../lib/sharedSchemas.js';@@ -73,6 +76,14 @@ export function updateBaselineAt(runtime, lastUpdateResult, now = Date.now()) {return candidates.length ? Math.max(...candidates) : now;}+/**+ * Is the only thing standing between this checkout and readiness something+ * `prepareUpdateRepo` can mechanically fix? Those are not worth waking an agent+ * for, and they are not a reason to stand down — they are handled after the+ * idle gate.+ */+const isRepairableOnly = (verdict) => verdict.reasons.length === 0 && verdict.repairable.length > 0;+/** Record the skip and log it once per distinct reason, not once per tick. */let lastLoggedSkip = null;async function standDown(reason, detail) {@@ -90,9 +101,9 @@ async function standDown(reason, detail) {/*** Is there anything to update TO on this channel?*- * @returns {Promise<{available: boolean, detail: string}>}+ * @returns {{available: boolean, detail: string}}*/-async function updateAvailableFor(channel, status, verdict) {+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' };@@ -121,7 +132,11 @@ export async function runAutoUpdateTick({ io = ioRef } = {}) {const config = resolveAutoUpdateConfig(settings?.autoUpdate);if (!config.enabled) return { ran: false, reason: 'disabled' };- const runtime = await updateChecker.getAutoUpdateRuntime();+ // ONE read of update.json serves the cooldown and the already-running check.+ // `getUpdateStatus()` is deliberately NOT called yet: its `getInstallState()`+ // walks every file under client/src, and the cooldown discards the answer on+ // 71 of every 72 ticks at the default interval.+ const { runtime, lastUpdateResult, updateInProgress } = await updateChecker.getAutoUpdateGateState();// 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.@@ -129,55 +144,63 @@ export async function runAutoUpdateTick({ io = ioRef } = {}) {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');+ if (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 baselineAt = updateBaselineAt(runtime, 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);+ const status = await updateChecker.getUpdateStatus().catch(() => null);+ if (!status) return standDown('status-unavailable', 'could not read the update status');++ // READ the checkout — never write to it yet. The write half+ // (`prepareUpdateRepo`) is deliberately held until after the idle gate+ // below: `git checkout main` in the primary checkout under a live+ // `useWorktree: false` CoS agent is a branch-jack, and the whole point of the+ // idle gate is to prove nothing is running before this process touches+ // anything. Reading early is still right, because the one remedy that takes+ // TIME is the repair agent — queued now, it is work the idle gate then waits+ // on, and the window after it finishes is the one that updates.+ const read = await checkUpdateRepoReadiness({ fetch: true })+ .catch((err) => ({ ready: false, needsAgent: false, reasons: ['git-unreadable'], summary: err.message, repairable: [] }));+ if (!read.ready && !isRepairableOnly(read)) {+ if (read.needsAgent && config.resolveBlockersWithAgent) {+ const task = await queueRepoRepairTask(read);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');+ return standDown('repo-not-ready', read.summary);}- if (actions.length) console.log(`🧹 Auto-update prepared the checkout: ${actions.join(', ')}`);- const availability = await updateAvailableFor(config.channel, status, verdict);+ const availability = updateAvailableFor(config.channel, status, read);if (!availability.available) return standDown('up-to-date', availability.detail);- // Idle is checked LAST, immediately before the launch, so the window it+ // Idle is checked immediately before anything is written, 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);+ const processing = await getSystemActivity().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));}+ // Only NOW may the checkout be written to. `prepareUpdateRepo` re-reads before+ // and after its remedies, so a checkout that went dirty since the read above+ // is refused here rather than repaired blindly.+ const { verdict, actions } = await prepareUpdateRepo().catch((err) => ({+ verdict: { ready: false, reasons: ['git-unreadable'], summary: err.message },+ actions: [],+ }));+ if (!verdict.ready) return standDown('repo-not-ready', verdict.summary);+ if (actions.length) console.log(`🧹 Auto-update prepared the checkout: ${actions.join(', ')}`);+lastLoggedSkip = null;console.log(`⬆️ Auto-update starting (${config.channel} channel) — ${availability.detail}`);await updateChecker.recordAutoUpdateRuntime({@@ -213,13 +236,7 @@ async function launchUpdateFor(channel, io) {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 };+ return result.ok ? { ok: true } : { ok: false, message: result.message };}/**diff --git a/server/services/autoUpdateScheduler.test.js b/server/services/autoUpdateScheduler.test.jsindex 0ed6512051..d89f660411 100644--- a/server/services/autoUpdateScheduler.test.js+++ b/server/services/autoUpdateScheduler.test.js@@ -6,9 +6,10 @@ const deps = vi.hoisted(() => ({selfUpdate: vi.fn(),appUpdate: vi.fn(),prepareRepo: vi.fn(),+ readRepo: vi.fn(),queueRepair: vi.fn(),status: vi.fn(),- runtime: vi.fn(),+ gateState: vi.fn(),recordRuntime: vi.fn(),schedule: vi.fn(),cancel: vi.fn(),@@ -19,16 +20,17 @@ vi.mock('./settings.js', () => ({getSettings: deps.settings,settingsEvents: { on: vi.fn(), emit: vi.fn() },}));-vi.mock('./activeProcessing.js', () => ({ getActiveProcessing: deps.processing }));+vi.mock('./activeProcessing.js', () => ({ getSystemActivity: deps.processing }));vi.mock('./portosSelfUpdate.js', () => ({ startPortosSelfUpdate: deps.selfUpdate }));vi.mock('./appUpdateRunner.js', () => ({ runAppUpdate: deps.appUpdate }));vi.mock('./updateRepoReadiness.js', () => ({+ checkUpdateRepoReadiness: deps.readRepo,prepareUpdateRepo: deps.prepareRepo,queueRepoRepairTask: deps.queueRepair,}));vi.mock('./updateChecker.js', () => ({getUpdateStatus: deps.status,- getAutoUpdateRuntime: deps.runtime,+ getAutoUpdateGateState: deps.gateState,recordAutoUpdateRuntime: deps.recordRuntime,}));@@ -39,22 +41,25 @@ 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: [] };+const readyVerdict = { ready: true, needsAgent: false, behind: 3, defaultBranch: 'main', reasons: [], repairable: [] };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.gateState.mockResolvedValue({+ runtime: { armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null, repairTaskId: null },+ lastUpdateResult: null,+ updateInProgress: false,+ });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.readRepo.mockResolvedValue(readyVerdict);+ deps.prepareRepo.mockResolvedValue({ verdict: readyVerdict, actions: [] });deps.processing.mockResolvedValue(idleSnapshot);deps.selfUpdate.mockResolvedValue({ started: true, tag: 'v9.9.9' });deps.appUpdate.mockResolvedValue({ ok: true });@@ -92,23 +97,32 @@ 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();+ expect(deps.gateState).not.toHaveBeenCalled();});- it('waits out the minimum interval before looking at all', async () => {- deps.runtime.mockResolvedValue({ armedAt: null, lastRunAt: iso(Date.now() - 2 * HOUR) });+ // The cooldown rejects 71 of every 72 ticks at the default interval, and+ // `getUpdateStatus()` walks every file under client/src — so it must not be+ // paid before the gate that discards it.+ it('waits out the minimum interval without reading the update status', async () => {+ deps.gateState.mockResolvedValue({+ runtime: { armedAt: null, lastRunAt: iso(Date.now() - 2 * HOUR) },+ lastUpdateResult: null,+ updateInProgress: false,+ });const result = await runAutoUpdateTick({ io: {} });expect(result).toMatchObject({ ran: false, reason: 'cooldown' });+ expect(deps.status).not.toHaveBeenCalled();+ expect(deps.readRepo).not.toHaveBeenCalled();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' },+ deps.gateState.mockResolvedValue({+ runtime: { armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null },lastUpdateResult: { completedAt: iso(Date.now() - HOUR) },+ updateInProgress: false,});await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'cooldown' });});@@ -132,8 +146,7 @@ describe('automatic update gates', () => {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 },+ updateAvailable: false, latestRelease: { version: '1.0.0' }, installState: { outOfSync: false },});await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'up-to-date' });expect(deps.selfUpdate).not.toHaveBeenCalled();@@ -141,10 +154,9 @@ describe('automatic update gates', () => {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.readRepo.mockResolvedValue({ ...readyVerdict, behind: 0 });deps.status.mockResolvedValue({- updateInProgress: false, updateAvailable: true, latestRelease: { version: '9.9.9' },- lastUpdateResult: null, installState: { outOfSync: false },+ updateAvailable: true, latestRelease: { version: '9.9.9' }, installState: { outOfSync: false },});await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'up-to-date' });expect(deps.appUpdate).not.toHaveBeenCalled();@@ -153,35 +165,48 @@ describe('automatic update gates', () => {describe('checkout readiness gate', () => {const notReady = {- verdict: { ready: false, needsAgent: true, summary: 'the working tree has uncommitted changes', reasons: ['uncommitted-changes'], repairable: [] },- actions: [],+ ready: false, needsAgent: true, behind: 3, defaultBranch: 'main',+ summary: 'the working tree has uncommitted changes',+ reasons: ['uncommitted-changes'], repairable: [],};it('refuses to update a checkout that is not clean on the default branch', async () => {- deps.prepareRepo.mockResolvedValue(notReady);+ deps.readRepo.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();});+ // The repairs run `git checkout` in the PRIMARY checkout. Doing that before+ // the idle gate would branch-jack a live `useWorktree: false` CoS agent, so+ // nothing may be written until the install is proven idle.+ it('never writes to the checkout before the idle gate passes', async () => {+ deps.processing.mockResolvedValue({ activity: { idle: false, blockers: [{ label: '1 CoS agent running' }] } });+ deps.readRepo.mockResolvedValue({ ...readyVerdict, ready: false, needsAgent: false, repairable: ['checkout-default'] });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: false, reason: 'busy' });+ expect(deps.prepareRepo).not.toHaveBeenCalled();+ });++ it('repairs a mechanically-fixable checkout after the idle gate, without an agent', async () => {+ deps.readRepo.mockResolvedValue({ ...readyVerdict, ready: false, needsAgent: false, repairable: ['checkout-default'] });+ deps.prepareRepo.mockResolvedValue({ verdict: readyVerdict, actions: ['switched to main'] });+ await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ ran: true });+ expect(deps.queueRepair).not.toHaveBeenCalled();+ expect(deps.prepareRepo).toHaveBeenCalledTimes(1);+ });+it('queues an agent only for what no script may safely repair', async () => {- deps.prepareRepo.mockResolvedValue(notReady);+ deps.readRepo.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();+ expect(deps.prepareRepo).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);+ deps.readRepo.mockResolvedValue(notReady);await expect(runAutoUpdateTick({ io: {} })).resolves.toMatchObject({ reason: 'repo-not-ready' });expect(deps.queueRepair).not.toHaveBeenCalled();});diff --git a/server/services/repoSync.js b/server/services/repoSync.jsindex da9a6c9077..81aca1dffd 100644--- a/server/services/repoSync.js+++ b/server/services/repoSync.js@@ -142,7 +142,7 @@ const STASH_CLASSIFY_CONCURRENCY = 6;* @param {string} repoPath* @returns {Promise<string|null>}*/-async function detectOperationInProgress(repoPath) {+export async function detectOperationInProgress(repoPath) {const out = await execGitSafe(['rev-parse', '--git-dir'], repoPath, { ignoreExitCode: true });if (out.exitCode !== 0) {throw new Error(out.stderr || `could not inspect git operation state (exit code ${out.exitCode})`);@@ -450,7 +450,7 @@ async function collectRepoState(repoPath) {* @param {string} base* @returns {Promise<{ahead:number, behind:number}|null>}*/-async function countAheadBehind(repoPath, ref, base) {+export async function countAheadBehind(repoPath, ref, base) {const out = await execGitSafe(['rev-list', '--left-right', '--count', `${base}...${ref}`], repoPath, { ignoreExitCode: true });if (out.exitCode !== 0) return null;const [behind, ahead] = (out.stdout || '').trim().split(/\s+/).map((n) => Number.parseInt(n, 10));diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex a40db4031e..4f09c00536 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -331,6 +331,24 @@ export async function getAutoUpdateRuntime() {return normalizeAutoUpdateRuntime(state.autoUpdate);}+/**+ * Everything the auto-update tick's CHEAP gates need, from one file read.+ *+ * The cooldown rejects 71 of every 72 ticks at the default 6h interval, and it+ * only needs the runtime record, the last update's completion, and whether an+ * update is already running — none of which requires `getUpdateStatus()`, whose+ * `getInstallState()` walks every file under `client/src`. Reading them together+ * also collapses what used to be three separate loads of `update.json` per tick.+ */+export async function getAutoUpdateGateState() {+ const state = await loadState();+ return {+ runtime: normalizeAutoUpdateRuntime(state.autoUpdate),+ lastUpdateResult: state.lastUpdateResult,+ updateInProgress: state.updateInProgress === true,+ };+}+/** Merge a patch into the runtime record. Returns the merged result. */export async function recordAutoUpdateRuntime(patch) {return withLock(async () => {diff --git a/server/services/updateRepoReadiness.js b/server/services/updateRepoReadiness.jsindex c8139502f4..9e62c1c4f6 100644--- a/server/services/updateRepoReadiness.js+++ b/server/services/updateRepoReadiness.js@@ -26,11 +26,11 @@* managed-app pull.*/-import { existsSync } from 'fs';-import { join, isAbsolute } from 'path';+import { isAbsolute } from 'path';import { PATHS } from '../lib/fileUtils.js';-import { execGit } from '../lib/execGit.js';+import { execGitSafe } from '../lib/execGit.js';import * as gitService from './git.js';+import { countAheadBehind, detectOperationInProgress } from './repoSync.js';import { classifyWorktreeDirt } from './worktreeManager.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';@@ -45,6 +45,9 @@ const REASON_LABELS = {'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',+ 'divergence-unreadable': 'how far the checkout has diverged from origin could not be read',+ 'agent-at-work': 'a CoS agent is working in this checkout',+ 'agent-check-unreadable': 'whether a CoS agent is working in this checkout could not be established','detached-head': 'HEAD is detached','wrong-branch': 'the checkout is not on the default branch',};@@ -54,41 +57,17 @@ 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. */+/**+ * How far HEAD and its origin counterpart have diverged, via `repoSync`'s+ * counter so the left/right → ahead/behind mapping is decided in one place.+ *+ * `null` means the read FAILED — deliberately not 0. Every missing fact here+ * would otherwise default to the value that looks safe, and "0 commits ahead"+ * is precisely the value that unlocks the update. The caller refuses on a null.+ */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,- };+ const counts = await countAheadBehind(repoPath, 'HEAD', `refs/remotes/origin/${branch}`);+ return counts || { ahead: null, behind: null };}/**@@ -102,34 +81,71 @@ async function divergence(repoPath, branch) {* the UI does not.* @returns {Promise<object>} the readiness verdict.*/-export async function checkUpdateRepoReadiness({ repoPath = PATHS.root, fetch = false } = {}) {+export async function checkUpdateRepoReadiness({ repoPath, 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,+ // ONE verdict shape on every path, including the failure ones — the scheduler+ // and the UI both read `summary` and `repairable`, and an early return that+ // omitted them forced a fallback message that named the wrong cause.+ const verdict = (fields) => {+ const reasons = fields.reasons || [];+ const repairable = fields.repairable || [];+ return {+ repoPath: dir,+ branch: null, defaultBranch: null, interrupted: null, ahead: null, behind: null,+ lockfilePaths: [],+ ...fields,+ 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. Nor may an unreadable+ // one: there is nothing for an agent to resolve if git itself is the+ // problem.+ needsAgent: reasons.length > 0 && !reasons.includes('git-unreadable'),+ summary: reasons.length ? reasons.map(describe).join('; ') : null,+ };};if (!(await gitService.isRepo(dir).catch(() => false))) {- return { ...base, reasons: ['git-unreadable'], needsAgent: false };+ return verdict({ reasons: ['git-unreadable'] });}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);+ // Five independent reads — nothing below depends on another's answer, and+ // serializing them cost ~110ms of git spawns on a path the Update tab polls.+ // `allowRemote` follows `fetch`: without it `getDefaultBranch` may run+ // `git remote set-head --auto`, a 5s network call, on that same poll.+ const [defaultBranch, branch, porcelain, interrupted, activeAgentId] = await Promise.all([+ gitService.getDefaultBranch(dir, { strict: true, allowRemote: fetch }).catch(() => null),+ gitService.getBranch(dir).catch(() => null),+ gitService.getStatusPorcelain(dir).catch(() => null),+ // `'unknown'` = the marker read itself failed, which is not "no operation".+ detectOperationInProgress(dir).catch(() => 'unknown'),+ // A CoS agent working in THIS checkout (a `useWorktree: false` task,+ // including the repair task this module queues) owns the branch it is on.+ // Moving it, or running update.sh's pm2 restart under it, is the branch-jack+ // `repoSync` refuses on for the same reason — and the idle gate alone would+ // not catch a paused agent that still holds the tree.+ gitService.findActiveAgentInWorkspace(dir, { includePaused: true, failClosed: true }).catch(() => 'unknown'),+ ]);if (branch === null || porcelain === null) {- return { ...base, defaultBranch, reasons: ['git-unreadable'] };+ return verdict({ 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 = [];+ // Distinct codes: "an agent holds this checkout" is a wait; "the registry+ // could not be read" is a fault the user has to see named, not a phantom agent.+ if (activeAgentId === 'unknown') reasons.push('agent-check-unreadable');+ else if (activeAgentId) reasons.push('agent-at-work');if (!defaultBranch) reasons.push('no-default-branch');if (interrupted) reasons.push('merge-in-progress');if (conflicted) reasons.push('conflicted-files');@@ -144,30 +160,27 @@ export async function checkUpdateRepoReadiness({ repoPath = PATHS.root, fetch =}// 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');+ // An UNREADABLE count refuses too — `null > 0` is false, so treating it as a+ // number here would make "could not tell" indistinguishable from "nothing+ // unpushed", in the one path whose whole premise is never losing work.+ if (onDefaultBranch && (ahead === null || ahead > 0)) {+ reasons.push(ahead === null ? 'divergence-unreadable' : 'unpushed-commits');+ }- return {- repoPath: dir,+ // The paths of the user's own uncommitted work are deliberately NOT returned:+ // this verdict is served to the browser on the Update tab's poll, and the+ // reason codes already say what is wrong. `lockfilePaths` is the exception —+ // `prepareUpdateRepo` restores exactly those paths and nothing else.+ return verdict({branch,defaultBranch,- onDefaultBranch,- clean: dirt.clean,- lockfileOnlyDirt: !dirt.clean && !dirt.hasRealChanges,- lockfilePaths: dirt.lockfilePaths,- dirtyPaths: dirt.realChangePaths,interrupted,ahead,behind,+ lockfilePaths: dirt.lockfilePaths,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,- };+ });}/**@@ -181,7 +194,9 @@ export async function checkUpdateRepoReadiness({ repoPath = PATHS.root, fetch =*/export async function prepareUpdateRepo({ repoPath = PATHS.root } = {}) {const dir = resolveRepoPath(repoPath);- const before = await checkUpdateRepoReadiness({ repoPath: dir, fetch: true });+ // No fetch: the one caller reads with `fetch: true` before its idle gate and+ // then calls this, so a second network hop would only re-answer that read.+ const before = await checkUpdateRepoReadiness({ repoPath: dir, fetch: false });if (before.ready || before.repairable.length === 0) return { verdict: before, actions: [] };const actions = [];@@ -190,11 +205,11 @@ export async function prepareUpdateRepo({ repoPath = PATHS.root } = {}) {// 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 });+ const restore = await execGitSafe(['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 });+ const checkout = await execGitSafe(['checkout', before.defaultBranch], dir, { ignoreExitCode: true });if (checkout.exitCode === 0) actions.push(`switched to ${before.defaultBranch}`);}diff --git a/server/services/updateRepoReadiness.test.js b/server/services/updateRepoReadiness.test.jsindex d86ce223f7..3a74acdb29 100644--- a/server/services/updateRepoReadiness.test.js+++ b/server/services/updateRepoReadiness.test.js@@ -4,9 +4,15 @@ 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.+// The CoS agent registry is the one collaborator these fixtures cannot supply:+// the temp repos are not a PortOS install, so the live registry read fails+// closed and every verdict would come back blocked on it. Doubled as "no agents+// running" — the condition each case below is actually about.+vi.mock('./cosAgentLifecycle.js', () => ({ getAgents: async () => [] }));++// Otherwise 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 = [];@@ -35,7 +41,7 @@ afterAll(() => repos.forEach((dir) => rmSync(dir, { recursive: true, force: truedescribe('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 });+ expect(verdict).toMatchObject({ ready: true, needsAgent: false, branch: 'main', defaultBranch: 'main', reasons: [], repairable: [] });});// Uncommitted work is the case the whole gate exists for: update.sh would@@ -88,13 +94,26 @@ describe('update repo readiness', () => {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 });+ expect(before).toMatchObject({ ready: false, needsAgent: false, reasons: [], repairable: ['restore-lockfiles'] });const { verdict, actions } = await prepareUpdateRepo({ repoPath: repo });expect(actions.join(' ')).toMatch(/lockfile/);expect(verdict.ready).toBe(true);});+ // The refusal a live agent in this very checkout earns: update.sh's pm2+ // restart, and the branch move, would both land on top of its work.+ it('refuses while a CoS agent is working in the checkout', async () => {+ const repo = makeRepo();+ const lifecycle = await import('./cosAgentLifecycle.js');+ vi.spyOn(lifecycle, 'getAgents').mockResolvedValue([+ { id: 'agent-1', status: 'running', metadata: { workspacePath: repo } },+ ]);+ const verdict = await checkUpdateRepoReadiness({ repoPath: repo });+ expect(verdict).toMatchObject({ ready: false, needsAgent: true });+ expect(verdict.reasons).toContain('agent-at-work');+ });+// 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 () => {diff --git a/server/sockets/apps.js b/server/sockets/apps.jsindex 5d99ae293b..a24c7eece8 100644--- a/server/sockets/apps.js+++ b/server/sockets/apps.js@@ -84,19 +84,12 @@ export const registerAppHandlers = (socket, io) => {acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,});if (outcome.ok) return;- if (outcome.reason === 'not-found') {- socket.emit('app:update:error', { message: 'App not found' });- return;- }- if (outcome.reason === 'duplicate') {- socket.emit('app:update:error', {- appId: data.appId,- duplicate: true,- message: `An ${outcome.inFlight.type} is already running for ${outcome.inFlight.appName}`- });- return;- }- socket.emit('app:update:error', { appId: outcome.appId, code: outcome.code, message: outcome.message });+ socket.emit('app:update:error', {+ appId: outcome.appId,+ code: outcome.code,+ message: outcome.message,+ ...(outcome.reason === 'duplicate' ? { duplicate: true } : {}),+ });} catch (err) {const message = err?.message ?? String(err);console.error(`❌ Socket handler error [app:update]: ${message}`);