Hub 2.19.0: the server agent's releases; Update agent picks one

- AgentRelease (migration 20261123150000_agent_release): the agent's releases, apart from the
  products' so licences and billing are untouched.
- Release sources can be for the Server agent; the defaults include it (monorepo agent@ tags,
  apps/agent/WHATS-NEW.md). Same sync rules as products. A saved list without it gets an
  "Add the agent's source" button on the Releases page.
- GET /api/admin/agent-releases; server summaries carry agentLatest; update-agent jobs go to a
  known agent release, the latest when none is asked for (agentTag).
- Update agent is a ReleaseSelect with the chosen version's notes; the Servers list and a server's
  page say when a newer agent is out; the Releases page shows agent releases (Server agent filter,
  Everything newest first by date).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 13:18:56 +02:00
co-authored by Claude Opus 5.5
parent 44fac310eb
commit 65637711c6
19 changed files with 292 additions and 50 deletions
+14 -2
View File
@@ -17,7 +17,7 @@ const licenceToken = require('../utils/licenceToken');
const { smtpConfigured, testSmtp } = require('../utils/mail');
const { VERSION_RE, sortReleases, syncLatestVersion, latestVersions, unmetRequirementsFor } = require('../utils/releases');
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('../utils/releaseSync');
const { parseRepoUrl, syncReleases, releaseSources, cleanSources, agentSource } = require('../utils/releaseSync');
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
const { requireTotp } = require('../utils/jobs');
@@ -398,6 +398,18 @@ router.get('/releases', wrap(async (req, res) => {
res.json(sortReleases(releases).map(r => ({ ...r, latest: latest[r.product] === r.version, installs: onVersion[`${r.product}@${r.version}`] || 0 })));
}));
// Hub 2.19.0: the server agent's releases (from git only), newest first, with how many servers run each.
router.get('/agent-releases', wrap(async (req, res) => {
const [releases, servers] = await Promise.all([
prisma.agentRelease.findMany(),
prisma.server.findMany({ where: { removedAt: null }, select: { agentVersion: true } }),
]);
const sorted = sortReleases(releases);
const onVersion = {};
for (const s of servers) if (s.agentVersion) onVersion[s.agentVersion] = (onVersion[s.agentVersion] || 0) + 1;
res.json(sorted.map((r, i) => ({ ...r, latest: i === 0, servers: onVersion[r.version] || 0 })));
}));
// The release sources in use (the saved list or the defaults).
router.get('/releases/sources', wrap(async (req, res) => {
const settings = await getSettings();
@@ -550,7 +562,7 @@ router.delete('/notices/:id', wrap(async (req, res) => {
router.get('/settings', wrap(async (req, res) => {
const settings = await getSettings();
res.json({ settings, releaseSources: releaseSources(settings), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
res.json({ settings, releaseSources: releaseSources(settings), agentSource: agentSource(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
}));
const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from'];
+5 -2
View File
@@ -11,6 +11,7 @@ const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const servers = require('../utils/servers');
const jobs = require('../utils/jobs');
const { latestAgentVersion } = require('../utils/releases');
const { pageOf, paged } = require('../utils/paging');
const router = express.Router();
@@ -79,7 +80,9 @@ router.get('/servers', wrap(async (req, res) => {
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
const day = await prisma.serverStat.groupBy({ by: ['serverId'], where: { at: { gt: since } }, _avg: { cpuPercent: true, ramUsedPercent: true }, _max: { cpuPeak: true, ramPeak: true } });
const byServer = new Map(day.map(d => [d.serverId, { cpuAvg: d._avg.cpuPercent, ramAvg: d._avg.ramUsedPercent, cpuPeak: d._max.cpuPeak, ramPeak: d._max.ramPeak }]));
res.json({ servers: list.map(s => ({ ...serverSummary(s), lastDay: byServer.get(s.id) || null })) });
// Hub 2.19.0: the newest agent release, so each server can say when it's behind.
const agentLatest = await latestAgentVersion();
res.json({ servers: list.map(s => ({ ...serverSummary(s), agentLatest, lastDay: byServer.get(s.id) || null })) });
}));
router.post('/servers/join-token', wrap(async (req, res) => {
@@ -97,7 +100,7 @@ router.get('/servers/:id', wrap(async (req, res) => {
const stats = bucketStats(rows, { '24h': 0, '7d': 60, '90d': 360 }[range]);
const recentJobs = await prisma.job.findMany({ where: { serverId: s.id }, orderBy: { createdAt: 'desc' }, take: 25, select: { id: true, type: true, status: true, args: true, notBefore: true, finishedAt: true, message: true, deploymentId: true } });
res.json(jsonSafe({
server: serverSummary(s),
server: { ...serverSummary(s), agentLatest: await latestAgentVersion() },
config: masked(servers.serverConfig(s)),
processes: s.lastStats?.processes || [],
stats: stats.map(x => ({ at: x.at, cpuPercent: x.cpuPercent, cpuPeak: x.cpuPeak, ramUsedPercent: x.ramUsedPercent, ramPeak: x.ramPeak, diskUsedPercent: x.diskUsedPercent })),
+3 -1
View File
@@ -20,7 +20,7 @@ const { render } = require('./emailLayout');
const { getSettings } = require('./settings');
const { PRODUCT_NAMES } = require('./products');
const { generateLicence } = require('./licences');
const { unmetRequirements, unmetRequirementsFor } = require('./releases');
const { unmetRequirements, unmetRequirementsFor, agentTag } = require('./releases');
const { searchTerm } = require('./paging');
const { compareVersions } = require('./alerts');
const servers = require('./servers');
@@ -1526,6 +1526,8 @@ async function queueCentralCheck(ports, now = new Date()) {
/** Any job by hand (status, restart): no notice, runs at once. */
async function runNow({ serverId, type, args, deploymentId = null }, admin, now = new Date()) {
if (!['status', 'restart', 'check-ports', 'update-agent'].includes(type)) throw fail(400, 'BAD_REQUEST', `${type} jobs are made from their own pages.`);
// Hub 2.19.0: an agent update is to a known agent release, the latest when none is asked for.
if (type === 'update-agent') args = { version: await agentTag(args?.version) };
return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now });
}
+25 -11
View File
@@ -10,6 +10,9 @@
* A product's releases are the tags of all its sources. Releases of a product are only removed
* when every one of its sources was read and at least one tag was found, so an unreachable git
* server (or a mistyped address) never wipes releases. A product with no source is managed by hand.
*
* Hub 2.19.0: a source can also be for the server agent ("agent", tags agent@1.2.3): its releases go
* to AgentRelease (no requirements), by the same rules. They come from git only.
*/
const prisma = require('../config/db');
@@ -20,6 +23,13 @@ const { PRODUCTS, PRODUCT_NAMES, isProduct } = require('./products');
const TIMEOUT_MS = 20000;
const PLATFORM_REPO = 'https://c-git.crosscode.co.za/joshua/crosscode-platform';
// Hub 2.19.0: the server agent as a release source's target, next to the products.
const AGENT = 'agent';
const isTarget = p => isProduct(p) || p === AGENT;
const targetName = p => (p === AGENT ? 'Server agent' : PRODUCT_NAMES[p]);
/** The agent's source in the monorepo (one of the defaults; the Releases page offers it to a saved list without one). */
const agentSource = () => ({ product: AGENT, repo: PLATFORM_REPO, tagPrefix: 'agent@', notesPath: 'apps/agent/WHATS-NEW.md' });
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
function parseRepoUrl(url) {
try {
@@ -36,14 +46,14 @@ function parseRepoUrl(url) {
/**
* The default sources: every product from the platform monorepo (`events@1.2.3`, `accounts@…`,
* with notes in `apps/<product>/WHATS-NEW.md`), plus Cross Events before the move, from the
* repository set before Hub 2.0 (`release_repo_url`, `v1.2.3` tags).
* repository set before Hub 2.0 (`release_repo_url`, `v1.2.3` tags), and (2.19.0) the server agent.
*/
function defaultSources(settings = {}) {
const platform = product => ({ product, repo: PLATFORM_REPO, tagPrefix: `${product}@`, notesPath: `apps/${product}/WHATS-NEW.md` });
const legacy = parseRepoUrl(settings.release_repo_url)
? [{ product: 'events', repo: String(settings.release_repo_url).trim(), tagPrefix: 'v', notesPath: settings.release_notes_path || 'WHATS-NEW.md' }]
: [];
return [platform('events'), ...legacy, platform('accounts'), platform('website'), platform('app')];
return [platform('events'), ...legacy, platform('accounts'), platform('website'), platform('app'), agentSource()];
}
const bad = message => Object.assign(new Error(message), { status: 400 });
@@ -55,7 +65,7 @@ function cleanSources(list) {
const seen = new Set();
return list.map((s, i) => {
const n = `Source ${i + 1}`;
if (!isProduct(s?.product)) throw bad(`${n}: choose a product.`);
if (!isTarget(s?.product)) throw bad(`${n}: choose a product or the server agent.`);
const repo = String(s.repo || '').trim();
if (!parseRepoUrl(repo)) throw bad(`${n}: the repository address looks like https://git.example.com/owner/repo.`);
const tagPrefix = String(s.tagPrefix ?? '').trim();
@@ -179,7 +189,7 @@ async function fetchTags(repo, token) {
}
const sameRequires = (a, b) => JSON.stringify(a || []) === JSON.stringify(b || []);
const sourceLabel = s => `${PRODUCT_NAMES[s.product]} (${parseRepoUrl(s.repo)?.repo || s.repo}, ${s.tagPrefix || 'no prefix'}1.2.3)`;
const sourceLabel = s => `${targetName(s.product)} (${parseRepoUrl(s.repo)?.repo || s.repo}, ${s.tagPrefix || 'no prefix'}1.2.3)`;
/**
* Read every source: { found: { product: Map(version → { date, notes, urgent, requires }) },
@@ -244,30 +254,34 @@ async function syncReleases() {
let updated = 0;
let removed = 0;
for (const product of new Set(sources.map(s => s.product))) {
// The agent's releases have their own table, without a product or requirements.
const agentOnly = product === AGENT;
const table = agentOnly ? prisma.agentRelease : prisma.release;
const tagged = found[product] || new Map();
const existing = new Map((await prisma.release.findMany({ where: { product } })).map(r => [r.version, r]));
const existing = new Map((await table.findMany(agentOnly ? {} : { where: { product } })).map(r => [r.version, r]));
for (const [version, t] of tagged) {
const had = existing.get(version);
const requires = agentOnly ? {} : { requires: t.requires };
if (!had) {
await prisma.release.create({ data: { product, version, notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: t.date ? new Date(t.date) : new Date() } });
await table.create({ data: { ...(agentOnly ? {} : { product }), version, notes: t.notes, urgent: t.urgent, ...requires, releasedAt: t.date ? new Date(t.date) : new Date() } });
added++;
} else {
// Releases added by hand (or from the old latest_version setting) take the tag's date.
const date = t.date ? new Date(t.date) : had.releasedAt;
if (had.notes !== t.notes || had.urgent !== t.urgent || !sameRequires(had.requires, t.requires) || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: date } });
if (had.notes !== t.notes || had.urgent !== t.urgent || (!agentOnly && !sameRequires(had.requires, t.requires)) || date.getTime() !== new Date(had.releasedAt).getTime()) {
await table.update({ where: { id: had.id }, data: { notes: t.notes, urgent: t.urgent, ...requires, releasedAt: date } });
updated++;
}
}
}
if (failed.has(product)) continue;
if (!tagged.size) {
if (existing.size) problems.push(`${PRODUCT_NAMES[product]}: no version tags found in its sources, so its ${existing.size} release(s) were kept. Check the sources.`);
if (existing.size) problems.push(`${targetName(product)}: no version tags found in its sources, so its ${existing.size} release(s) were kept. Check the sources.`);
continue;
}
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
if (gone.length) {
await prisma.release.deleteMany({ where: { id: { in: gone } } });
await table.deleteMany({ where: { id: { in: gone } } });
removed += gone.length;
}
}
@@ -276,4 +290,4 @@ async function syncReleases() {
return { sources: counts, added, updated, removed, latest, problems };
}
module.exports = { PLATFORM_REPO, gitGet: get, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
module.exports = { PLATFORM_REPO, AGENT, agentSource, targetName, gitGet: get, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
+26
View File
@@ -104,7 +104,33 @@ async function unmetRequirementsFor(install, target, db = prisma) {
return unmetRequirements({ releases, from: install.version, target, siblings });
}
// ─── The server agent's releases (Hub 2.19.0) ─────────────────────────────────
/** The newest agent release's version, or null when there are none. */
async function latestAgentVersion(db = prisma) {
return sortReleases(await db.agentRelease.findMany({ select: { version: true } }))[0]?.version || null;
}
/**
* The tag an update-agent job gets: the version asked for (1.5.0 or agent@1.5.0) when it's a known
* agent release, or the latest when none is asked for. With no agent releases at all (no agent
* source yet), a version asked for is taken as it is.
*/
async function agentTag(version, db = prisma) {
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
const releases = await db.agentRelease.findMany({ select: { version: true } });
const want = String(version || '').trim().replace(/^agent@/, '');
if (!want) {
if (!releases.length) throw fail(409, 'NO_RELEASE', 'There are no agent releases yet: add the Server agent release source on the Releases page and Sync now.');
return `agent@${sortReleases(releases)[0].version}`;
}
if (!VERSION_RE.test(want)) throw fail(400, 'BAD_REQUEST', 'The agent version looks like 1.5.0.');
if (releases.length && !releases.some(r => r.version === want)) throw fail(400, 'NO_RELEASE', `There's no agent release ${want}.`);
return `agent@${want}`;
}
module.exports = {
latestAgentVersion, agentTag,
VERSION_RE, sortReleases, releasesFor, releasesForInstall, latestByProduct, latestVersions, syncLatestVersion,
unmetRequirements, unmetRequirementsFor, requirementMessage,
};