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

+4
View File
@@ -68,6 +68,10 @@ account does not delay other accounts.
## Local development
Packaged installations offer download and restart controls in Settings → About.
Downloads are verified and staged; files are applied before the application starts.
Restart confirmation uses the shared modal, and download results use action feedback.
On Windows, the native API logs the process token and EXE integrity label once
at startup. A Low (or lower) token triggers a WebUI warning; file labels and
query failures alone do not. “临时关闭” lasts for the tab session, including
@@ -1,3 +1,4 @@
import { APP_VERSION } from '@/types';
import {
createContext,
useContext,
@@ -93,6 +94,7 @@ import { settingsRoute, type SettingsTab } from '@/router';
import { NotificationsPanel } from '@/components/settings/notifications-panel';
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
import { SystemPanel } from '@/components/settings/system-panel';
import { UpdateInstaller } from '@/components/settings/update-installer';
import { StoragePanel } from '@/components/settings/storage-panel';
import { DeveloperCrashProbe, developerCrashReducer } from '@/components/settings/developer-tools';
@@ -1864,31 +1866,8 @@ function DeveloperPanel() {
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 software update, shown as a grouped list. Read-only: links to the
// GitHub release; SnowLuma never downloads or applies anything itself.
function UpdateGroup() {
const { updateInfo, refreshUpdate, systemInfo, resources } = useAppState();
const { updateInfo, refreshUpdate, resources } = useAppState();
const { runAction } = useActionFeedback();
const [checking, setChecking] = useState(false);
@@ -1899,7 +1878,7 @@ function UpdateGroup() {
await runAction(
{
title: '正在检查更新',
detail: `当前版本 v${__APP_VERSION__}`,
detail: `当前版本 v${APP_VERSION}`,
successTitle: '更新检查完成',
successDetail: (result) =>
result?.hasUpdate && result.latest
@@ -1954,7 +1933,6 @@ function UpdateGroup() {
if (updateInfo?.hasUpdate && updateInfo.latest) {
const latest = updateInfo.latest;
const hint = assetHint(latest, systemInfo?.platform, systemInfo?.arch);
detail = (
<div className="bg-primary/[0.05] px-5 py-4 text-left">
<div className="flex items-center gap-2">
@@ -1974,17 +1952,10 @@ function UpdateGroup() {
{updateInfo.notes}
</pre>
)}
{hint && (
<p className="mt-3 text-xs text-muted-foreground">
适合你的平台:
<code className="rounded bg-muted px-1 py-0.5 font-mono">{hint}</code>
(在下载页选择)
</p>
)}
{updateInfo.htmlUrl && (
<Button asChild size="sm" className="mt-3">
<a href={updateInfo.htmlUrl} target="_blank" rel="noreferrer noopener">
<Download className="size-4" /> 前往下载
<ExternalLink className="size-4" /> 发布说明
</a>
</Button>
)}
@@ -1993,10 +1964,10 @@ function UpdateGroup() {
}
return (
<Group title="软件更新" icon={Sparkles} description="仅提示新版本,从不自动下载或安装。">
<Group title="软件更新" icon={Sparkles}>
<SettingRow label="当前版本" layout="inline">
<code className="rounded-md border bg-muted/40 px-2 py-0.5 font-mono text-xs tabular-nums">
v{__APP_VERSION__}
v{APP_VERSION}
</code>
</SettingRow>
<SettingRow label="检查更新">
@@ -2029,6 +2000,7 @@ function UpdateGroup() {
</div>
</SettingRow>
{detail}
<UpdateInstaller version={updateInfo?.hasUpdate ? updateInfo.latest : null} />
</Group>
);
}
@@ -2059,7 +2031,7 @@ function AboutPanel() {
<div className="flex items-center gap-2">
<span className="text-2xl font-semibold tracking-tight">SnowLuma</span>
<span className="rounded-full border border-primary/30 bg-primary/10 px-2 py-0.5 font-mono text-meta text-primary tabular-nums">
v{__APP_VERSION__}
v{APP_VERSION}
</span>
</div>
<p className="text-sm text-muted-foreground">
@@ -1,9 +1,4 @@
// Settings → 服务 tab (Wave A1). Edits the WebUI listener's own config
// (port / bind host / trust-proxy / HTTPS). Listener-level changes are
// persisted but apply only after a restart — there is no supervisor to
// self-restart, so we never offer a "restart now" button, only a banner.
// Fields currently pinned by SNOWLUMA_* env vars are flagged (edits to them
// won't take effect until the env var is removed).
// Listener changes apply after restart; environment overrides remain authoritative.
import { useEffect, useRef, useState } from 'react';
import { motion } from 'motion/react';
import {
@@ -0,0 +1,165 @@
import { useEffect, useState } from 'react';
import { Download, Loader2, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useApi } from '@/lib/api';
import type { UpdateStatus } from '@/types';
export function UpdateInstaller({ version }: { version: string | null }) {
const api = useApi();
const { startAction, runAction } = useActionFeedback();
const [status, setStatus] = useState<UpdateStatus | null>(null);
const [error, setError] = useState<string | null>(null);
const [confirmRestart, setConfirmRestart] = useState(false);
const [submitting, setSubmitting] = useState(false);
const phase = status?.phase;
useEffect(() => {
if (phase !== undefined && phase !== 'downloading') {
return;
}
let disposed = false;
let timer: ReturnType<typeof setTimeout>;
const activity = phase === 'downloading' ? startAction({ title: '正在下载更新' }) : null;
const poll = async () => {
try {
const next = await api.update.status();
if (disposed && !activity) {
return;
}
if (!disposed) {
setStatus(next);
setError(null);
}
if (next.phase === 'ready') {
activity?.succeed({ title: '更新已就绪', detail: '重启后生效' });
} else if (next.phase === 'error') {
activity?.fail(next.message, { title: '更新失败' });
} else if (next.phase === 'downloading') {
timer = setTimeout(() => {
void poll();
}, 1000);
}
} catch (caught) {
const message = caught instanceof Error ? caught.message : String(caught);
activity?.fail(message, { title: '读取更新状态失败' });
if (!disposed) {
setError(message);
timer = setTimeout(() => {
void poll();
}, 5000);
}
}
};
void poll();
return () => {
disposed = true;
if (!activity) {
clearTimeout(timer);
}
};
}, [api, phase, startAction]);
const download = async () => {
if (!version) {
return;
}
setSubmitting(true);
setError(null);
try {
setStatus(await api.update.download(version));
} catch (caught) {
const message = caught instanceof Error ? caught.message : String(caught);
setError(message);
setStatus(null);
startAction({ title: '下载更新' }).fail(message, { title: '下载失败' });
} finally {
setSubmitting(false);
}
};
const restart = async () => {
await runAction(
{
title: '正在重启',
successTitle: '已请求重启',
successDetail: '稍后刷新页面',
errorTitle: '重启失败',
},
async () => {
setStatus(await api.update.restart());
},
);
};
if (status?.phase === 'idle' && !version && !error) {
return null;
}
return (
<div className="flex flex-col gap-3 px-5 py-4">
{error && (
<p role="alert" className="text-xs text-destructive">
{error}
</p>
)}
{status?.phase === 'error' && (
<p role="alert" className="text-xs text-destructive">
{status.message}
</p>
)}
{status?.phase === 'unavailable' && (
<p className="text-xs text-muted-foreground">{status.message}</p>
)}
{status?.phase === 'downloading' && (
<p className="flex items-center gap-2 text-sm">
<Loader2 className="size-4 animate-spin" />
正在下载 v{status.version}
</p>
)}
{status?.phase === 'restarting' && <p className="text-sm">正在重启,稍后刷新页面。</p>}
{status?.phase === 'ready' && (
<div className="flex items-center gap-3">
<span className="text-sm">v{status.version} 已就绪</span>
<Button size="sm" onClick={() => setConfirmRestart(true)}>
<RefreshCw className="size-4" />
重启更新
</Button>
</div>
)}
{version && (phase === 'idle' || phase === 'error') && (
<Button
size="sm"
className="self-start"
onClick={() => {
void download();
}}
disabled={submitting}
>
<Download className="size-4" />
下载更新
</Button>
)}
<ConfirmDialog
open={confirmRestart}
onOpenChange={setConfirmRestart}
title="重启并更新?"
description="连接将暂时断开,配置与数据保留。"
confirmText="重启更新"
onConfirm={restart}
/>
</div>
);
}
-1
View File
@@ -1 +0,0 @@
declare const __APP_VERSION__: string;
+4
View File
@@ -23,6 +23,7 @@ import type {
UiAppearance,
UiConfig,
UpdateInfo,
UpdateStatus,
} from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-form';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
@@ -219,6 +220,9 @@ class HttpApiClient implements ApiClient {
this.update = {
check: (force) =>
this.getJson<UpdateInfo>(`/api/update/check${force ? '?force=true' : ''}`),
status: () => this.getJson<UpdateStatus>('/api/update/status'),
download: (version) => this.postJson<UpdateStatus>('/api/update/download', { version }),
restart: () => this.postJson<UpdateStatus>('/api/update/restart'),
};
this.systemSettings = {
+4
View File
@@ -27,6 +27,7 @@ import type {
UiAppearance,
UiConfig,
UpdateInfo,
UpdateStatus,
} from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-form';
@@ -275,6 +276,9 @@ export interface ApiClient {
update: {
/** Advisory check for a newer stable release. Read-only — never downloads. */
check(force?: boolean): Promise<UpdateInfo>;
status(): Promise<UpdateStatus>;
download(version: string): Promise<UpdateStatus>;
restart(): Promise<UpdateStatus>;
};
// ---- WebUI customization (config/ui.json) ----
+8 -2
View File
@@ -1,8 +1,14 @@
export const APP_NAME = 'SnowLuma';
// Injected at build time by Vite from the monorepo root package.json.
export const APP_VERSION = __APP_VERSION__;
export { APP_VERSION } from '@snowluma/common/version';
/** Advisory update-availability info from `GET /api/update/check`. */
export type UpdateStatus = { current: string } & (
| { phase: 'unavailable' | 'error'; message: string }
| { phase: 'idle' }
| { phase: 'downloading' | 'ready' | 'restarting'; version: string }
);
/** Update-availability info from `GET /api/update/check`. */
export interface UpdateInfo {
/** The running build's version (no `v` prefix). */
current: string;
+43
View File
@@ -0,0 +1,43 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
afterEach(() => vi.unstubAllGlobals());
describe('update API', () => {
it('sends authenticated download and restart requests', async () => {
const fetchMock = vi.fn<typeof fetch>(async () =>
Response.json({ current: '1.0.0', phase: 'ready', version: '2.0.0' }),
);
vi.stubGlobal('fetch', fetchMock);
const api = createApiClient({ tokenStore: { load: () => 'token', save: () => undefined } });
await api.update.download('2.0.0');
await api.update.restart();
await api.update.status();
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
'/api/update/download',
'/api/update/restart',
'/api/update/status',
]);
expect(fetchMock).toHaveBeenNthCalledWith(
1,
'/api/update/download',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ version: '2.0.0' }),
headers: new Headers({
'Content-Type': 'application/json',
'X-SnowLuma-Token': 'token',
}),
}),
);
});
it('surfaces a rejected restart instead of treating it as complete', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => Response.json({ message: '更新包尚未就绪' }, { status: 409 })),
);
const api = createApiClient({ tokenStore: { load: () => 'token', save: () => undefined } });
await expect(api.update.restart()).rejects.toThrow('更新包尚未就绪');
});
});
-9
View File
@@ -1,4 +1,3 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
@@ -7,11 +6,6 @@ import tailwindcss from '@tailwindcss/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Single source of truth for the user-facing app version: monorepo root package.json.
const rootPkg = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf-8'),
) as { version: string };
export default defineConfig({
plugins: [tailwindcss(), react()],
resolve: {
@@ -19,9 +13,6 @@ export default defineConfig({
'@': path.resolve(__dirname, 'src'),
},
},
define: {
__APP_VERSION__: JSON.stringify(rootPkg.version),
},
server: {
port: 5178,
strictPort: false,