Merge branch 'feat/agent-releases'

This commit is contained in:
2026-11-23 13:18:57 +02:00
19 changed files with 292 additions and 50 deletions
+19
View File
@@ -5,6 +5,25 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.19.0] - 2026-11-23
**Migration:** a new table, `AgentRelease`. No API change for existing calls.
### Added
- **The server agent's releases.** A release source can be for the **Server agent** (the defaults have
it: the monorepo's `agent@` tags, notes in `apps/agent/WHATS-NEW.md`). The Releases page shows them
with their notes and how many servers run each, under **Server agent** and **Everything**. A saved
list of sources from before gets an **Add the agent's source** button.
- **Update agent picks a release**: Latest by default, the newest 10 with Show older versions, the
version running on the server marked and not pickable, and the chosen version's notes under it.
The Hub refuses a version that isn't an agent release (while it knows of any).
- The Servers list and a server's page say when a newer agent is out ("1.5.0 available").
### Changed
- The Releases page's **Everything** list is newest first by release date (it was by version number).
## [2.18.0] - 2026-11-23
Frontend only: no migration, no API changes.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.18.0",
"version": "2.19.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.18.0",
"version": "2.19.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.18.0",
"version": "2.19.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -0,0 +1,18 @@
-- Hub 2.19.0: the server agent's releases, from its release source (Releases page, Update agent).
-- CreateTable
CREATE TABLE "AgentRelease" (
"id" TEXT NOT NULL,
"version" TEXT NOT NULL,
"notes" TEXT NOT NULL DEFAULT '',
"urgent" BOOLEAN NOT NULL DEFAULT false,
"releasedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AgentRelease_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "AgentRelease_version_key" ON "AgentRelease"("version");
+13
View File
@@ -290,6 +290,19 @@ model Release {
@@unique([product, version])
}
// Hub 2.19.0: releases of the server agent, from its release source (tags agent@1.2.3, notes in
// apps/agent/WHATS-NEW.md), read by the same sync as the products'. The agent isn't a product (no
// licences or billing), so its releases have their own table. Update agent picks from them.
model AgentRelease {
id String @id @default(uuid())
version String @unique
notes String @default("")
urgent Boolean @default(false)
releasedAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum NoticeLevel {
info
maintenance
+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,
};
+65 -3
View File
@@ -3,8 +3,20 @@
// stub; the database is in memory.
const mockReleases = [];
const mockAgentReleases = [];
const mockSettings = { values: {} };
const mockDb = {
// Hub 2.19.0: the server agent's releases.
agentRelease: {
findMany: jest.fn(async ({ select } = {}) => (select ? mockAgentReleases.map(r => Object.fromEntries(Object.keys(select).map(k => [k, r[k]]))) : mockAgentReleases)),
create: jest.fn(async ({ data }) => { const row = { id: `a${mockAgentReleases.length + 1}_${data.version}`, ...data }; mockAgentReleases.push(row); return row; }),
update: jest.fn(async ({ where, data }) => Object.assign(mockAgentReleases.find(r => r.id === where.id), data)),
deleteMany: jest.fn(async ({ where }) => {
const ids = new Set(where.id.in);
for (let i = mockAgentReleases.length - 1; i >= 0; i--) if (ids.has(mockAgentReleases[i].id)) mockAgentReleases.splice(i, 1);
return { count: ids.size };
}),
},
release: {
findMany: jest.fn(async ({ where, select } = {}) => {
const rows = mockReleases.filter(r => !where?.product || r.product === where.product);
@@ -27,7 +39,7 @@ jest.mock('../src/utils/settings', () => ({
}));
const { parseNotes, parseRequirements, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases, PLATFORM_REPO } = require('../src/utils/releaseSync');
const { unmetRequirements, latestByProduct } = require('../src/utils/releases');
const { unmetRequirements, latestByProduct, agentTag, latestAgentVersion } = require('../src/utils/releases');
const LEGACY = 'https://c-git.crosscode.co.za/joshua/hope-events';
const api = repo => `https://c-git.crosscode.co.za/api/v1/repos/joshua/${repo}`;
@@ -49,15 +61,17 @@ global.fetch = jest.fn(async url => {
beforeEach(() => {
mockReleases.length = 0;
mockAgentReleases.length = 0;
mockSettings.values = { release_repo_url: LEGACY, release_notes_path: 'WHATS-NEW.md' };
gitea = {
'hope-events': { tags: ['v2.0.0', 'v2.1.0', 'v2.1.1', 'not-a-version'], files: { 'WHATS-NEW.md': '## 2.1.1\n- Feedback in the background\n## 2.1.0\n- Feedback page' } },
'crosscode-platform': {
tags: ['contracts@1.0.0', 'contracts@1.1.0', 'events@2.2.0', 'events@3.0.0', 'accounts@1.2.0', 'website@1.0.0'],
tags: ['contracts@1.0.0', 'contracts@1.1.0', 'events@2.2.0', 'events@3.0.0', 'accounts@1.2.0', 'website@1.0.0', 'agent@1.4.0', 'agent@1.5.0'],
files: {
'apps/events/WHATS-NEW.md': '## 3.0.0 — requires accounts 1.2.0\n- Sign in with your church account\n## 2.2.0\n- Moved into the monorepo',
'apps/accounts/WHATS-NEW.md': '## 1.2.0\n- Authenticator app',
'apps/website/WHATS-NEW.md': '## 1.0.0 — requires events 2.4.0\n- First release',
'apps/agent/WHATS-NEW.md': '## 1.5.0 — urgent\n- One product of a church at a time\n## 1.4.0\n- frp config from the Hub',
},
},
};
@@ -66,13 +80,14 @@ beforeEach(() => {
const versions = product => mockReleases.filter(r => r.product === product).map(r => r.version).sort();
describe('sources', () => {
test('the defaults: every product from the monorepo, plus Cross Events from the repo set before 2.0', () => {
test('the defaults: every product from the monorepo, plus Cross Events from the repo set before 2.0, and the agent', () => {
expect(defaultSources(mockSettings.values)).toEqual([
{ product: 'events', repo: PLATFORM_REPO, tagPrefix: 'events@', notesPath: 'apps/events/WHATS-NEW.md' },
{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' },
{ product: 'accounts', repo: PLATFORM_REPO, tagPrefix: 'accounts@', notesPath: 'apps/accounts/WHATS-NEW.md' },
{ product: 'website', repo: PLATFORM_REPO, tagPrefix: 'website@', notesPath: 'apps/website/WHATS-NEW.md' },
{ product: 'app', repo: PLATFORM_REPO, tagPrefix: 'app@', notesPath: 'apps/app/WHATS-NEW.md' },
{ product: 'agent', repo: PLATFORM_REPO, tagPrefix: 'agent@', notesPath: 'apps/agent/WHATS-NEW.md' },
]);
});
@@ -81,6 +96,10 @@ describe('sources', () => {
expect(releaseSources({ release_sources: JSON.stringify(saved) })).toEqual(saved);
});
test('a source can be for the server agent', () => {
expect(cleanSources([{ product: 'agent', repo: PLATFORM_REPO, tagPrefix: 'agent@', notesPath: 'apps/agent/WHATS-NEW.md' }])[0].product).toBe('agent');
});
test('bad sources are refused with what is wrong', () => {
expect(() => cleanSources([{ product: 'shop', repo: LEGACY }])).toThrow(/product/);
expect(() => cleanSources([{ product: 'events', repo: 'not a url' }])).toThrow(/repository/);
@@ -180,6 +199,49 @@ describe('sync', () => {
});
});
describe('the server agent (2.19.0)', () => {
const agentVersions = () => mockAgentReleases.map(r => r.version).sort();
test('its tags go to the agent releases, with notes, not to any product', async () => {
await syncReleases();
expect(agentVersions()).toEqual(['1.4.0', '1.5.0']);
expect(mockReleases.some(r => r.version === '1.5.0' || r.version === '1.4.0')).toBe(false);
const r = mockAgentReleases.find(x => x.version === '1.5.0');
expect(r).toMatchObject({ notes: '- One product of a church at a time', urgent: true });
expect(r).not.toHaveProperty('product');
expect(r).not.toHaveProperty('requires');
});
test('a removed tag removes its release; an unreachable source keeps them', async () => {
await syncReleases();
gitea['crosscode-platform'].tags = gitea['crosscode-platform'].tags.filter(t => t !== 'agent@1.4.0');
await syncReleases();
expect(agentVersions()).toEqual(['1.5.0']);
gitea['crosscode-platform'] = 'down';
await syncReleases();
expect(agentVersions()).toEqual(['1.5.0']);
});
test('a saved list without the agent leaves its releases alone', async () => {
await syncReleases();
mockSettings.values.release_sources = JSON.stringify([{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]);
await syncReleases();
expect(agentVersions()).toEqual(['1.4.0', '1.5.0']);
});
test('the latest, and the tag an update-agent job gets', async () => {
await expect(agentTag('')).rejects.toMatchObject({ code: 'NO_RELEASE' });
expect(await agentTag('agent@1.3.0')).toBe('agent@1.3.0'); // no agent releases yet: taken as asked
await syncReleases();
expect(await latestAgentVersion()).toBe('1.5.0');
expect(await agentTag('')).toBe('agent@1.5.0');
expect(await agentTag('1.4.0')).toBe('agent@1.4.0');
expect(await agentTag('agent@1.4.0')).toBe('agent@1.4.0');
await expect(agentTag('1.3.0')).rejects.toMatchObject({ code: 'NO_RELEASE' });
await expect(agentTag('latest')).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
});
describe('unmet requirements', () => {
const releases = [
{ version: '2.4.0', requires: [] },
+1 -1
View File
@@ -1,6 +1,6 @@
# Version pickers plan
Status: 2.18.0 done; 2.19.0 in progress · 2026-11-23
Status: done in Hub 2.18.0 and 2.19.0 · 2026-11-23
Three forms still ask for a version as free text, though the Hub knows (or could know) every release.
This plan turns them into a list to pick from, and gives the Hub the agent's releases so Update agent
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.18.0",
"version": "2.19.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.18.0",
"version": "2.19.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.18.0",
"version": "2.19.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+56 -13
View File
@@ -5,14 +5,18 @@ import { GitBranch, Link2, Pencil, Plus, RefreshCw, ShieldAlert, Trash2 } from "
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products";
import type { Release, ReleaseSource } from "@/lib/types";
import type { AgentRelease, Release, ReleaseSource } from "@/lib/types";
import { usePaged } from "@/lib/paging";
import { Badge, FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, ReleaseNotes, useSubmit } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Target = ReleaseSource["product"];
type Filter = Target | "all";
type Form = { product: Product; version: string; notes: string; urgent: boolean; releasedAt: string };
const today = () => new Date().toISOString().slice(0, 10);
/** Hub 2.19.0: a product's name, or "Server agent". */
const targetName = (p: Target) => (p === "agent" ? "Server agent" : PRODUCT_NAMES[p]);
const toBody = (f: Form) => ({ product: f.product, version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
/**
@@ -96,8 +100,9 @@ function SourcesModal({ sources, tokenSet, onClose, onSaved }: { sources: Releas
<div key={i} className="grid items-end gap-2 rounded-lg border border-slate-200 p-3 sm:grid-cols-[10rem_1fr_auto]">
<div>
<label className="label" htmlFor={`src_product_${i}`}>Product</label>
<select id={`src_product_${i}`} className="input" value={r.product} onChange={e => set(i, { product: e.target.value as Product })}>
<select id={`src_product_${i}`} className="input" value={r.product} onChange={e => set(i, { product: e.target.value as Target })}>
{PRODUCTS.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
<option value="agent">Server agent</option>
</select>
</div>
<div><label className="label" htmlFor={`src_repo_${i}`}>Repository</label><input id={`src_repo_${i}`} className="input" value={r.repo} onChange={e => set(i, { repo: e.target.value })} placeholder="https://c-git.crosscode.co.za/joshua/crosscode-platform" required /></div>
@@ -125,7 +130,7 @@ function SourcesModal({ sources, tokenSet, onClose, onSaved }: { sources: Releas
* Where releases come from: per product, one or more git sources (a repository, a tag prefix and a
* notes file), synced every 15 minutes. Hub 2.16.0: a read view; Edit opens the popup.
*/
function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]; state: SyncState; onSaved: () => void; setMsg: (m: Msg) => void }) {
function Sources({ sources, agentSource, state, onSaved, setMsg }: { sources: ReleaseSource[]; agentSource: ReleaseSource | null; state: SyncState; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [busy, setBusy] = useState(false);
const [editing, setEditing] = useState(false);
const saved = !!state.release_sources?.trim();
@@ -141,6 +146,13 @@ function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]
onSaved();
};
// Hub 2.19.0: a saved list from before has no source for the agent; one click adds it.
const addAgent = async () => {
if (!agentSource) return;
setMsg(null);
try { await saveSources([...sources, agentSource]); await syncNow("Added the agent's source and synced"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const useDefaults = async () => {
if (!confirm("Go back to the default sources? Your list is removed.")) return;
setMsg(null);
@@ -156,6 +168,7 @@ function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]
<button type="button" className="btn-secondary px-2.5 py-1.5" disabled={busy} onClick={() => { setMsg(null); syncNow(); }}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
{saved && agentSource && !sources.some(s => s.product === "agent") && <button type="button" className="btn-secondary px-2.5 py-1.5" disabled={busy} onClick={addAgent}><Plus className="h-3.5 w-3.5" /> Add the agent&apos;s source</button>}
{saved && <button type="button" className="btn-secondary px-2.5 py-1.5" disabled={busy} onClick={useDefaults}>Use the defaults</button>}
</>}
>
@@ -169,7 +182,7 @@ function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><th className="py-1 pr-3">Product</th><th className="pr-3">Repository</th><th className="pr-3">Tag prefix</th><th>Notes file</th></tr></thead>
<tbody>{sources.map((r, i) => (
<tr key={i} className="border-t border-slate-100"><td className="py-1.5 pr-3">{PRODUCT_NAMES[r.product]}</td><td className="break-all pr-3">{r.repo}</td><td className="pr-3 font-mono">{r.tagPrefix || "—"}</td><td className="font-mono">{r.notesPath || "—"}</td></tr>
<tr key={i} className="border-t border-slate-100"><td className="py-1.5 pr-3">{targetName(r.product)}</td><td className="break-all pr-3">{r.repo}</td><td className="pr-3 font-mono">{r.tagPrefix || "—"}</td><td className="font-mono">{r.notesPath || "—"}</td></tr>
))}</tbody>
</table>
</div>
@@ -185,24 +198,50 @@ function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]
);
}
type Item = { kind: "product"; r: Release } | { kind: "agent"; r: AgentRelease };
/** Hub 2.19.0: a release of the server agent: from git only, so no Edit or Delete. */
function AgentReleaseCard({ r }: { r: AgentRelease }) {
return (
<div className="card">
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold"><span className="text-slate-500">Server agent</span> {r.version}</h2>
{r.latest && <Badge value="ok" label="Latest" />}
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-200"><ShieldAlert className="h-3 w-3" /> Urgent</span>}
<span className="text-xs text-slate-500">{fmtDate(r.releasedAt, false)} · {r.servers} server{r.servers === 1 ? "" : "s"} on it</span>
</div>
{r.notes ? <ReleaseNotes notes={r.notes} /> : <p className="text-sm text-slate-500">No notes for this version.</p>}
</div>
);
}
/** Each product's versions and what's new in each. A product's newest is the latest version its installs are offered. */
export default function ReleasesPage() {
const [releases, setReleases] = useState<Release[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
// Hub 2.16.0: the popup that's open: a new release, or the id of the one being edited.
const [open, setOpen] = useState<"new" | string | null>(null);
const [filter, setFilter] = useState<Product | "all">("all");
const [state, setState] = useState<{ settings: SyncState; releaseSources: ReleaseSource[] } | null>(null);
const [filter, setFilter] = useState<Filter>("all");
const [state, setState] = useState<{ settings: SyncState; releaseSources: ReleaseSource[]; agentSource?: ReleaseSource } | null>(null);
// Hub 2.19.0: the server agent's releases, shown with the products'.
const [agentReleases, setAgentReleases] = useState<AgentRelease[]>([]);
const load = useCallback(() => {
api<Release[]>("/api/admin/releases").then(setReleases).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AgentRelease[]>("/api/admin/agent-releases").then(setAgentReleases).catch(() => {});
api<{ settings: SyncState; releaseSources: ReleaseSource[] }>("/api/admin/settings").then(setState).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
const fromGit = useMemo(() => new Set((state?.releaseSources || []).map(s => s.product)), [state]);
const manual = PRODUCTS.filter(p => !fromGit.has(p));
const shown = (releases || []).filter(r => filter === "all" || r.product === filter);
// Hub 2.19.0: the products' releases and the agent's in one list; All is newest first by date.
const shown = useMemo<Item[]>(() => {
const products: Item[] = filter === "agent" ? [] : (releases || []).filter(r => filter === "all" || r.product === filter).map(r => ({ kind: "product", r }));
const agents: Item[] = filter === "all" || filter === "agent" ? agentReleases.map(r => ({ kind: "agent", r })) : [];
const all = [...products, ...agents];
return filter === "all" ? all.sort((a, b) => new Date(b.r.releasedAt).getTime() - new Date(a.r.releasedAt).getTime()) : all;
}, [releases, agentReleases, filter]);
// Hub 2.6.0: a page at a time.
const paged = usePaged(shown, filter, 15);
const editing = open && open !== "new" ? releases?.find(r => r.id === open) || null : null;
@@ -225,7 +264,7 @@ export default function ReleasesPage() {
actions={state && manual.length > 0 && <button className="btn-primary" onClick={() => setOpen("new")}><Plus className="h-4 w-4" /> Add release</button>}
/>
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{state && <Sources sources={state.releaseSources} state={state.settings} onSaved={load} setMsg={setMsg} />}
{state && <Sources sources={state.releaseSources} agentSource={state.agentSource || null} state={state.settings} onSaved={load} setMsg={setMsg} />}
{open === "new" && manual.length > 0 && (
<ReleaseModal initial={{ product: manual[0], version: "", notes: "", urgent: false, releasedAt: today() }} products={manual} onClose={() => setOpen(null)} onSaved={saved} />
)}
@@ -234,16 +273,19 @@ export default function ReleasesPage() {
)}
<div className="mb-4 flex flex-wrap gap-2" role="group" aria-label="Show releases of">
{(["all", ...PRODUCTS] as const).map(p => (
{(["all", ...PRODUCTS, "agent"] as const).map(p => (
<button key={p} type="button" className={filter === p ? "btn-primary px-3 py-1 text-xs" : "btn-secondary px-3 py-1 text-xs"} aria-pressed={filter === p} onClick={() => setFilter(p)}>
{p === "all" ? "All products" : PRODUCT_NAMES[p]}
{p === "all" ? "Everything" : targetName(p)}
</button>
))}
</div>
{!releases ? <Loading /> : shown.length === 0 ? <p className="text-sm text-slate-500">No releases yet{filter === "all" ? "" : ` for ${PRODUCT_NAMES[filter]}`}.</p> : (
{!releases ? <Loading /> : shown.length === 0 ? <p className="text-sm text-slate-500">No releases yet{filter === "all" ? "" : ` for ${targetName(filter)}`}.</p> : (
<div className="space-y-4">
{paged.rows.map(r => (
{paged.rows.map(item => {
if (item.kind === "agent") return <AgentReleaseCard key={`agent-${item.r.id}`} r={item.r} />;
const r = item.r;
return (
<div key={r.id} className="card">
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold"><span className="text-slate-500">{PRODUCT_NAMES[r.product]}</span> {r.version}</h2>
@@ -264,7 +306,8 @@ export default function ReleasesPage() {
</div>
<ReleaseNotes notes={r.notes} />
</div>
))}
);
})}
<div className="card p-0"><Pager {...paged} /></div>
</div>
)}
+27 -8
View File
@@ -7,8 +7,10 @@ import { Plus, Trash2, Upload } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import { Field, Fields, FormError, Loading, Message, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, useSubmit } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
import { Field, Fields, FormError, Loading, Message, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, ReleaseNotes, useSubmit } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, agentUpdate, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
import { ReleaseSelect } from "@/components/ReleaseSelect";
import type { AgentRelease } from "@/lib/types";
import { FrpConfig, type FrpState } from "@/components/FrpConfig";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -69,17 +71,34 @@ function ConfigModal({ id, config, onClose, onSaved }: { id: string; config: Rec
);
}
/** Hub 2.17.0: Update agent in a popup; queuing it opens the job. */
/**
* Hub 2.17.0: Update agent in a popup; queuing it opens the job. 2.19.0: the version is picked from
* the agent's releases (Latest by default; the one running here can't be picked), with its notes.
*/
function UpdateAgentModal({ current, onClose, queue }: { current: string | null; onClose: () => void; queue: (version: string) => Promise<void> }) {
const [version, setVersion] = useState("");
const [releases, setReleases] = useState<AgentRelease[] | null>(null);
const { busy, error, run } = useSubmit();
useEffect(() => { api<AgentRelease[]>("/api/admin/agent-releases").then(setReleases).catch(() => setReleases([])); }, []);
const chosen = releases?.find(r => (version ? r.version === version : r.latest)) || null;
const nothingNew = !version && !!chosen && chosen.version === current;
return (
<Modal title="Update agent" onClose={onClose} dirty={version.trim() !== ""}>
<form onSubmit={e => { e.preventDefault(); run(() => queue(version.trim())); }} className="space-y-3">
<Modal title="Update agent" onClose={onClose} dirty={version !== ""} wide>
<form onSubmit={e => { e.preventDefault(); run(() => queue(version ? `agent@${version}` : "")); }} className="space-y-3">
<p className="text-sm text-slate-600">The agent here is {current || "an unknown version"}. The new version is queued as a job on this server.</p>
<div><label className="label" htmlFor="agent-version">Version</label><input id="agent-version" className="input font-mono" placeholder="agent@1.0.1" value={version} onChange={e => setVersion(e.target.value)} required /></div>
<div>
<label className="label" htmlFor="agent-version">Version</label>
{!releases ? <Loading /> : <ReleaseSelect id="agent-version" releases={releases} value={version} onChange={setVersion} current={current} currentPickable={false} />}
</div>
{chosen && (
<div className="max-h-64 overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-3">
<div className="mb-1 text-xs font-medium text-slate-500">What&apos;s new in {chosen.version}{chosen.urgent ? " (urgent)" : ""}</div>
{chosen.notes ? <ReleaseNotes notes={chosen.notes} /> : <p className="text-sm text-slate-500">No notes for this version.</p>}
</div>
)}
{nothingNew && <p className="text-sm text-slate-500">This server already runs the latest agent.</p>}
<FormError error={error} />
<ModalButtons busy={busy} onCancel={onClose} label="Update agent" busyLabel="Queuing…" />
<ModalButtons busy={busy} onCancel={onClose} label="Update agent" busyLabel="Queuing…" disabled={nothingNew} />
</form>
</Modal>
);
@@ -116,7 +135,7 @@ export default function ServerPage() {
return (
<div className="space-y-6">
<div>
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} /></>} />
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion}{agentUpdate(s) && <span className="font-medium text-amber-700"> ({agentUpdate(s)} available)</span>} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} /></>} />
<ServersNav active="/servers" />
<PageMessage msg={msg} onClose={() => setMsg(null)} />
</div>
+2 -2
View File
@@ -7,7 +7,7 @@ import { api, errorText } from "@/lib/api";
import { ago, bytes } from "@/lib/format";
import { usePaged } from "@/lib/paging";
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, useSubmit } from "@/components/ui";
import { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers";
import { ServersNav, StatusPill, agentUpdate, pct, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -86,7 +86,7 @@ export default function ServersPage() {
<div className="flex items-start justify-between gap-2">
<div>
<div className="font-medium">{s.name}</div>
<div className="text-xs text-slate-500">{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname || "?"} · agent {s.agentVersion || "?"}</div>
<div className="text-xs text-slate-500">{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname || "?"} · agent {s.agentVersion || "?"}{agentUpdate(s) && <span className="font-medium text-amber-700"> · {agentUpdate(s)} available</span>}</div>
</div>
<StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} />
</div>
+8
View File
@@ -2,11 +2,14 @@
import React, { useMemo, useRef, useState } from "react";
import { fmtDate } from "@/lib/format";
import { compareVersions } from "@/components/ReleaseSelect";
/** Shared pieces for the servers pages (2.1.0). */
export type ServerSummary = {
id: string; name: string; mode: "church" | "central"; hostname: string | null; agentVersion: string | null;
/** Hub 2.19.0: the newest agent release (null: none known). */
agentLatest?: string | null;
lastSeenAt: string | null; joinedAt: string; removedAt: string | null; notes: string | null; online: boolean; busy?: boolean;
ram: { totalBytes: number; availableBytes: number; usedPercent: number } | null;
cpu: { percent: number; load1: number; cores: number } | null;
@@ -173,3 +176,8 @@ export function ServersNav({ active }: { active: string }) {
</nav>
);
}
/** Hub 2.19.0: the newer agent release this server could update to, or null. */
export function agentUpdate(s: Pick<ServerSummary, "agentVersion" | "agentLatest">): string | null {
return s.agentLatest && s.agentVersion && compareVersions(s.agentLatest, s.agentVersion) > 0 ? s.agentLatest : null;
}
+4 -1
View File
@@ -86,7 +86,10 @@ export type AiInstallUse = { installId: string; name: string; url: string; produ
export type ReleaseRequirement = { product: Product; version: string };
export type Release = { id: string; product: Product; version: string; notes: string; urgent: boolean; requires: ReleaseRequirement[]; releasedAt: string; latest: boolean; installs: number };
export type ReleaseSource = { product: Product; repo: string; tagPrefix: string; notesPath: string };
/** Hub 2.19.0: a source is for a product or the server agent. */
export type ReleaseSource = { product: Product | "agent"; repo: string; tagPrefix: string; notesPath: string };
/** Hub 2.19.0: a release of the server agent (from git only), with how many servers run it. */
export type AgentRelease = { id: string; version: string; notes: string; urgent: boolean; releasedAt: string; latest: boolean; servers: number };
export type UnmetRequirement = { product: Product; version: string; current: string | null };
export type NoticeLevel = "info" | "maintenance" | "warning";