feat(core): add staged self-updates and unify application version

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:50:11 +08:00
1 parent c54aeffc77
commit 5032cbb8c0
45 files changed
+1860 -165

No files matched your search

+22 -9
View File
@@ -1,3 +1,4 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
@@ -77,7 +78,7 @@ import { restoreBackup, RestoreTransactionError, type RestorePhase } from './res
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse } from './sse-response';
import { sseResponse as createSseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
@@ -99,7 +100,9 @@ import {
sniffImageMime,
writeBackgroundImage,
} from './ui-config';
import { currentVersion, getUpdateInfo } from './update-check';
import { getUpdateInfo } from '../update/check';
import { createUpdateService } from '../update/service';
import { updateRoutes } from './update-routes';
import { buildFullTraceDownload } from './log-export';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
@@ -629,6 +632,8 @@ export async function initWebUI(
tlsEnabled?: boolean;
trustProxy?: string;
stateBus?: StateBus;
restart?: () => void;
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const host = listener.host || '127.0.0.1';
@@ -747,6 +752,9 @@ export async function initWebUI(
}
const app = new Hono();
const shutdownStreams = new AbortController();
const sseResponse = (...args: Parameters<typeof createSseResponse>) =>
createSseResponse(args[0], args[1], shutdownStreams.signal);
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
@@ -1312,11 +1320,15 @@ export async function initWebUI(
return c.json({ status: 'running' });
});
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
// never downloads or applies the update itself. `?force=1` bypasses the
// server-side cache (the "立即检查" button). Never errors out — a failed
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
const updater = await createUpdateService(
listener.restart ? listener.updateRoot : undefined,
APP_VERSION,
);
app.route(
'/api/update',
updateRoutes(updater, () => listener.restart?.()),
);
app.get('/api/update/check', async (c) => {
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
return c.json(await getUpdateInfo(force));
@@ -1397,7 +1409,7 @@ export async function initWebUI(
// ── System settings (WebUI listener) — Wave A1 ──
// Listener-level changes (port/host/TLS) are persisted but apply only on the
// next restart (no supervisor → no self-restart). The panel surfaces which
// next restart. The panel surfaces which
// fields are currently overridden by env so edits that won't take effect are
// visible.
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
@@ -1850,7 +1862,7 @@ export async function initWebUI(
app.get('/api/logs/export/trace', (c) => {
const exportedAt = new Date().toISOString();
const download = buildFullTraceDownload(getLogSnapshot(), {
version: currentVersion(),
version: APP_VERSION,
operatingSystem: os.platform(),
architecture: os.arch(),
nodeVersion: process.version,
@@ -2344,6 +2356,7 @@ export async function initWebUI(
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
shutdownStreams.abort();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});
+14 -1
View File
@@ -32,7 +32,11 @@ export interface SseChannel {
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
export function sseResponse(
c: Context,
start: (ch: SseChannel) => void,
shutdown?: AbortSignal,
): Response {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
@@ -91,6 +95,15 @@ export function sseResponse(c: Context, start: (ch: SseChannel) => void): Respon
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
shutdown?.addEventListener('abort', teardown, { once: true });
cleanups.push(() => {
c.req.raw.signal.removeEventListener('abort', teardown);
shutdown?.removeEventListener('abort', teardown);
});
if (shutdown?.aborted) {
teardown();
}
},
});
return new Response(stream, {
-195
View File
@@ -1,195 +0,0 @@
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
const log = createLogger('Update');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
export interface UpdateCheckResult {
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
export function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) {
nums.push(0);
}
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) {
return pa.nums[i] - pb.nums[i];
}
}
if (pa.pre === pb.pre) {
return 0;
}
if (!pa.pre) {
return 1;
} // release > prerelease
if (!pb.pre) {
return -1;
}
return pa.pre < pb.pre ? -1 : 1;
}
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
return { ...base, error: `github ${res.status}` };
}
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) {
return { ...base, error: 'no tag' };
}
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
}
/**
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
* failures come back as a result with `error` set and `hasUpdate: false`, and
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
}
+38
View File
@@ -0,0 +1,38 @@
import { Hono } from 'hono';
import type { HttpBindings } from '@hono/node-server';
import type { UpdateService } from '../update/service';
export function updateRoutes(service: UpdateService, restart: () => void) {
const app = new Hono<{ Bindings: HttpBindings }>();
app.get('/status', (c) => c.json(service.status()));
app.post('/download', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ message: '请求必须是 JSON 对象' }, 400);
}
if (!body || typeof body !== 'object' || !('version' in body)) {
return c.json({ message: '缺少更新版本' }, 400);
}
try {
service.start(body.version);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
app.post('/restart', (c) => {
try {
service.restart();
c.env.outgoing.once('finish', restart);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
return app;
}