diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 82b165a4..1cd88d45 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -14,6 +14,7 @@ import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; +import { getUpdateInfo } from './update-check'; const log = createLogger('WebUI'); const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -285,6 +286,16 @@ export async function initWebUI( // ─── Read-only API ─────────────────────────────────────────────────────── app.get('/api/status', (c) => 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. + 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)); + }); + // Host system info let lastCpuTimes: { idle: number; total: number }[] | null = null; function sampleCpuLoad(): number[] { diff --git a/packages/core/src/webui/update-check.ts b/packages/core/src/webui/update-check.ts new file mode 100644 index 00000000..c1c6da30 --- /dev/null +++ b/packages/core/src/webui/update-check.ts @@ -0,0 +1,163 @@ +// 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'; + +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; +} + +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; +} + +let cache: UpdateCheckResult | null = null; +let inflight: Promise | null = null; + +async function fetchLatest(current: string): Promise { + 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 { + const current = currentVersion(); + if (!isEnabled()) { + return { ...emptyResult(current), error: 'disabled' }; + } + if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache; + if (inflight) return inflight; + inflight = (async () => { + const result = await fetchLatest(current); + if (result.error) { + log.debug('update check failed: %s', result.error); + } else { + cache = result; // only cache good results so transient errors retry + if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current); + } + return result; + })().finally(() => { + inflight = null; + }); + return inflight; +} + +function emptyResult(current: string): UpdateCheckResult { + return { + current, + latest: null, + hasUpdate: false, + htmlUrl: null, + notes: null, + publishedAt: null, + checkedAt: Date.now(), + }; +} diff --git a/packages/webui/src/components/layout/sidebar.tsx b/packages/webui/src/components/layout/sidebar.tsx index bcdc0376..1f3e02dc 100644 --- a/packages/webui/src/components/layout/sidebar.tsx +++ b/packages/webui/src/components/layout/sidebar.tsx @@ -1,10 +1,11 @@ -import { LayoutDashboard, PlugZap, Settings, SlidersHorizontal, Terminal } from 'lucide-react'; +import { LayoutDashboard, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react'; import { motion } from 'motion/react'; import { Link, useRouterState } from '@tanstack/react-router'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Separator } from '@/components/ui/separator'; import { cn } from '@/lib/utils'; import { APP_NAME, APP_VERSION } from '@/types'; +import { useAppState } from '@/contexts/AppStateContext'; import type { AppPath } from '@/router'; export interface NavItem { @@ -29,6 +30,7 @@ interface SidebarProps { export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) { const pathname = useRouterState({ select: (s) => s.location.pathname }); + const { updateInfo } = useAppState(); return (
@@ -89,6 +91,31 @@ export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) { + {updateInfo?.hasUpdate && ( +
+ + + {!collapsed && ( + + 有新版本可用 + v{updateInfo.latest} · 点击查看 + + )} + {collapsed && ( + + )} + +
+ )}
{collapsed ? '©' : `© ${new Date().getFullYear()} SnowLuma`}
diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 3241bbc6..0aba09b3 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -1,6 +1,6 @@ import { useState, type ReactNode } from 'react'; import { motion } from 'motion/react'; -import { Bug, Check, ExternalLink, Github, Info, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Star, Sun, Tag } from 'lucide-react'; +import { Bug, Check, Download, ExternalLink, Github, Info, KeyRound, Loader2, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sparkles, Star, Sun, Tag } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; @@ -312,6 +312,101 @@ function AccountPanel() { const REPO_URL = 'https://github.com/SnowLuma/SnowLuma'; +// Best-effort guess of the release asset matching the running platform, so +// the user knows which file to grab on the GitHub release page. Returns null +// for platforms with no official asset (e.g. macOS). +function assetHint(latest: string, platform?: string, arch?: string): string | null { + if (!platform) return null; + const tag = `v${latest}`; + if (platform === 'win32') return `SnowLuma-${tag}-win-x64.zip`; + if (platform === 'linux') return `SnowLuma-${tag}-linux-${arch === 'arm64' ? 'arm64' : 'x64'}.tar.gz`; + return null; +} + +// Advisory update status. Read-only: links to the GitHub release; SnowLuma +// never downloads or applies anything itself. +function UpdateStatus() { + const { updateInfo, refreshUpdate, systemInfo } = useAppState(); + const [checking, setChecking] = useState(false); + + const onCheck = async () => { + setChecking(true); + try { + await refreshUpdate(true); + } finally { + setChecking(false); + } + }; + + const checkButton = ( + + ); + + if (updateInfo?.hasUpdate && updateInfo.latest) { + const hint = assetHint(updateInfo.latest, systemInfo?.platform, systemInfo?.arch); + return ( +
+
+ + 发现新版本 v{updateInfo.latest} + {updateInfo.publishedAt && ( + + {new Date(updateInfo.publishedAt).toLocaleDateString()} + + )} +
+

+ 当前 v{updateInfo.current} → 最新 v{updateInfo.latest} +

+ {updateInfo.notes && ( +
+            {updateInfo.notes}
+          
+ )} + {hint && ( +

+ 适合你的平台: + {hint} + (在下载页选择) +

+ )} +
+ {updateInfo.htmlUrl && ( + + )} + {checkButton} +
+
+ ); + } + + let text: string; + if (!updateInfo) text = '正在检查更新…'; + else if (updateInfo.error === 'disabled') text = '更新检查已关闭'; + else if (updateInfo.error) text = '无法检查更新'; + else text = `已是最新版本(v${updateInfo.current})`; + + const ok = !!updateInfo && !updateInfo.error; + + return ( +
+ + {ok ? : } + {text} + + {updateInfo?.error !== 'disabled' && checkButton} +
+ ); +} + function AboutPanel() { return ( @@ -340,6 +435,9 @@ function AboutPanel() { 以轻量注入驱动 QQ NT,对外提供标准 OneBot v11 接口,让机器人一次部署、长期稳定运行。

+ {/* Update status */} + + {/* Star CTA */}
diff --git a/packages/webui/src/contexts/AppStateContext.tsx b/packages/webui/src/contexts/AppStateContext.tsx index adb54042..174a0d4c 100644 --- a/packages/webui/src/contexts/AppStateContext.tsx +++ b/packages/webui/src/contexts/AppStateContext.tsx @@ -1,5 +1,5 @@ import { createContext, useContext, type ReactNode } from 'react'; -import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types'; import type { HookProcessOps } from '@/hooks/use-hook-process-ops'; /** @@ -13,12 +13,16 @@ export interface AppStateValue { processList: HookProcessInfo[]; systemInfo: SystemInfo | null; connections: AccountConnections[]; + /** Advisory update-availability info; null until the first check resolves. */ + updateInfo: UpdateInfo | null; selectedUin: string | null; setSelectedUin: (uin: string | null) => void; processOps: HookProcessOps; refreshProcesses: () => void; refreshSystem: () => void; refreshConnections: () => void; + /** Re-run the update check; `force` bypasses the server-side cache. */ + refreshUpdate: (force?: boolean) => Promise; /** Triggered from the topbar logout button. */ onLogout: () => void; } diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 82718136..9988eca9 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -1,4 +1,4 @@ -import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo, UpdateInfo } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { @@ -42,6 +42,7 @@ class HttpApiClient implements ApiClient { readonly processes: ApiClient['processes']; readonly config: ApiClient['config']; readonly logs: ApiClient['logs']; + readonly update: ApiClient['update']; constructor(opts: CreateApiClientOptions = {}) { this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY); @@ -89,6 +90,11 @@ class HttpApiClient implements ApiClient { setLevel: (level) => this.postJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`, { level }), }; + + this.update = { + check: (force) => + this.getJson(`/api/update/check${force ? '?force=true' : ''}`), + }; } // ---------- HTTP helpers ---------- diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 4644fba5..6a26e7af 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -6,6 +6,7 @@ import type { OneBotConfig, QQInfo, SystemInfo, + UpdateInfo, } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; @@ -69,6 +70,12 @@ export interface ApiClient { save(uin: string, config: OneBotConfig): Promise; }; + // ---- update check ---- + update: { + /** Advisory check for a newer stable release. Read-only — never downloads. */ + check(force?: boolean): Promise; + }; + // ---- logs ---- logs: { list(limit?: number): Promise; diff --git a/packages/webui/src/router/app-layout.tsx b/packages/webui/src/router/app-layout.tsx index c6b7b1c0..e015799f 100644 --- a/packages/webui/src/router/app-layout.tsx +++ b/packages/webui/src/router/app-layout.tsx @@ -8,7 +8,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog'; import { Skeleton } from '@/components/ui/skeleton'; import { AppStateProvider } from '@/contexts/AppStateContext'; import { useSession } from '@/contexts/SessionContext'; -import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types'; /** * The layout route. Owns the live state shared across the four pages @@ -25,6 +25,7 @@ export function AppLayout() { const [processList, setProcessList] = useState([]); const [systemInfo, setSystemInfo] = useState(null); const [connections, setConnections] = useState([]); + const [updateInfo, setUpdateInfo] = useState(null); const [selectedUin, setSelectedUin] = useState(null); const refreshQqList = useCallback(async () => { @@ -59,6 +60,14 @@ export function AppLayout() { } }, [api]); + const refreshUpdate = useCallback(async (force = false) => { + try { + setUpdateInfo(await api.update.check(force)); + } catch (e) { + console.error('update-check', e); + } + }, [api]); + const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({ onAfterOp: refreshProcesses, }); @@ -78,12 +87,22 @@ export function AppLayout() { }; }, [pollInterval, refreshQqList, refreshProcesses, refreshSystem, refreshConnections]); + // Update check runs on its own slow cadence (6h), independent of the fast + // list-polling above — GitHub's API is rate-limited, the result rarely + // changes, and the server caches it anyway, so this is cheap. + useEffect(() => { + refreshUpdate(); + const id = setInterval(() => refreshUpdate(), 6 * 60 * 60 * 1000); + return () => clearInterval(id); + }, [refreshUpdate]); + const handleLogout = useCallback(async () => { await api.logout(); setQqList([]); setProcessList([]); setSystemInfo(null); setConnections([]); + setUpdateInfo(null); setSelectedUin(null); session.onLogoutComplete(); }, [api, session]); @@ -95,12 +114,14 @@ export function AppLayout() { processList, systemInfo, connections, + updateInfo, selectedUin, setSelectedUin, processOps, refreshProcesses, refreshSystem, refreshConnections, + refreshUpdate, onLogout: handleLogout, }} > diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 0f65ab15..415e0524 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -2,6 +2,26 @@ export const APP_NAME = 'SnowLuma'; // Injected at build time by Vite from the monorepo root package.json. export const APP_VERSION = __APP_VERSION__; +/** Advisory update-availability info from `GET /api/update/check`. */ +export interface UpdateInfo { + /** The running build's version (no `v` prefix). */ + current: string; + /** Latest stable release version, or null if 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 server-side. */ + 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/disabled or failed; the UI degrades quietly. */ + error?: string; +} + export interface QQInfo { uin: string; nickname: string;