feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)
Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics. Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
1 parent
20f48d11ec
commit
c7428363cb
170 files changed
+7748
-3913
No files matched your search
@@ -20,6 +20,8 @@ status, OneBot configuration, logs, storage, and server settings.
|
||||
follows the actual drawer state.
|
||||
- Failures must remain visible in the affected control and in the operation
|
||||
result; do not convert failed responses into successful feedback.
|
||||
- JSON endpoints must return an object. Malformed or non-object responses are
|
||||
reported as errors rather than displayed as empty lists or default settings.
|
||||
- Password change flows use floating labels and inline validation consistently.
|
||||
- Password strength details appear only while the new-password field has focus
|
||||
and leave with the same motion language when focus moves away.
|
||||
@@ -30,6 +32,12 @@ status, OneBot configuration, logs, storage, and server settings.
|
||||
|
||||
## Local development
|
||||
|
||||
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
|
||||
reloads; “永久关闭” persists in this browser's site storage. Neither suppresses
|
||||
startup logs. Failed queries and preference writes remain visible.
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -51,5 +51,8 @@
|
||||
"typescript-eslint": "^8.58.2",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import { Modal } from '@/components/interior/modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
LOW_INTEGRITY_PERMANENT_KEY,
|
||||
readLowIntegrityDismissed,
|
||||
saveLowIntegrityDismissed,
|
||||
} from '@/lib/low-integrity-warning';
|
||||
|
||||
/** Mounted in the authenticated layout so polling and route changes cannot reopen it. */
|
||||
export function LowIntegrityWarning({ lowIntegrity }: { lowIntegrity: boolean }) {
|
||||
const [dismissed, setDismissed] = useState(readLowIntegrityDismissed);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const temporaryButton = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === LOW_INTEGRITY_PERMANENT_KEY && event.newValue === '1') {
|
||||
setDismissed(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', onStorage);
|
||||
return () => window.removeEventListener('storage', onStorage);
|
||||
}, []);
|
||||
|
||||
const dismiss = (scope: 'session' | 'permanent') => {
|
||||
try {
|
||||
saveLowIntegrityDismissed(scope);
|
||||
} catch (caught) {
|
||||
console.warn('failed to save low integrity warning preference', caught);
|
||||
|
||||
if (scope === 'permanent') {
|
||||
setError('无法保存设置,请允许浏览器存储或选择临时关闭。');
|
||||
return;
|
||||
}
|
||||
// Even with storage blocked, temporary dismissal must let the user continue.
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setDismissed(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={lowIntegrity && !dismissed}
|
||||
onClose={() => dismiss('session')}
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-warning" />
|
||||
Node 完整性过低
|
||||
</span>
|
||||
}
|
||||
showClose={false}
|
||||
closeOnBackdrop={false}
|
||||
initialFocusRef={temporaryButton}
|
||||
maxWidth={480}
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => dismiss('permanent')}>
|
||||
永久关闭
|
||||
</Button>
|
||||
<Button ref={temporaryButton} type="button" onClick={() => dismiss('session')}>
|
||||
临时关闭
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<p>
|
||||
当前进程可能无法连接
|
||||
QQ。请检查启动程序的完整性标签,修正后重启。详情见启动日志。
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
临时关闭仅对当前标签页会话有效;永久关闭保存在此浏览器。
|
||||
</p>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -93,17 +93,6 @@ function persist(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every cached contact list (the data layer's "清缓存" button). */
|
||||
export function clearDebugContactsCache(): void {
|
||||
mem.clear();
|
||||
|
||||
try {
|
||||
localStorage.removeItem(LS_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
type ParseRow = (row: Record<string, unknown>) => PickerOption | null;
|
||||
|
||||
interface ListState {
|
||||
|
||||
@@ -53,11 +53,29 @@ interface ErrorPayload {
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response): Promise<T> {
|
||||
let payload: unknown;
|
||||
|
||||
try {
|
||||
return (await res.json()) as T;
|
||||
} catch {
|
||||
return {} as T;
|
||||
payload = await res.json();
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw invalidJsonResponse(res);
|
||||
}
|
||||
|
||||
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
|
||||
throw invalidJsonResponse(res);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
function invalidJsonResponse(res: Response): ApiError {
|
||||
return res.ok
|
||||
? new ApiError(502, '服务端返回了无效的 JSON 响应', 'INVALID_RESPONSE')
|
||||
: new ApiError(res.status, res.statusText || '请求失败');
|
||||
}
|
||||
|
||||
function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
|
||||
@@ -1088,7 +1106,7 @@ class HttpApiClient implements ApiClient {
|
||||
}
|
||||
|
||||
if (!res.ok || !res.body) {
|
||||
const payload = await readJson<ErrorPayload>(res).catch(() => ({}) as ErrorPayload);
|
||||
const payload = await readJson<ErrorPayload>(res);
|
||||
throw new ApiError(
|
||||
res.status,
|
||||
extractErrorMessage(payload, '流式调用失败'),
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
export const LOW_INTEGRITY_PERMANENT_KEY = 'snowluma.low-integrity.dismissed.v1';
|
||||
export const LOW_INTEGRITY_SESSION_KEY = 'snowluma.low-integrity.session-dismissed.v1';
|
||||
|
||||
export function readLowIntegrityDismissed(): boolean {
|
||||
if (typeof window === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read independently: blocking one storage must not discard a preference
|
||||
// successfully saved in the other.
|
||||
for (const [storage, key] of [
|
||||
['localStorage', LOW_INTEGRITY_PERMANENT_KEY],
|
||||
['sessionStorage', LOW_INTEGRITY_SESSION_KEY],
|
||||
] as const) {
|
||||
try {
|
||||
if (window[storage].getItem(key) === '1') {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('failed to read low integrity warning preference', error);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function saveLowIntegrityDismissed(scope: 'session' | 'permanent'): void {
|
||||
if (scope === 'permanent') {
|
||||
window.localStorage.setItem(LOW_INTEGRITY_PERMANENT_KEY, '1');
|
||||
} else {
|
||||
window.sessionStorage.setItem(LOW_INTEGRITY_SESSION_KEY, '1');
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,6 @@ export function downloadBlob(blob: Blob, filename: string): void {
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Clipboard write that still works on LAN HTTP and inside a modal focus trap. */
|
||||
/** WebKit `<input type="color">` only accepts `#rrggbb`. */
|
||||
export function toColorInputValue(raw: string, fallback = '#0ea5e9'): string {
|
||||
const v = raw.trim();
|
||||
@@ -73,6 +72,7 @@ export function toColorInputValue(raw: string, fallback = '#0ea5e9'): string {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Clipboard write that still works on LAN HTTP and inside a modal focus trap. */
|
||||
export async function copyText(value: string): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
@@ -83,8 +83,9 @@ export async function copyText(value: string): Promise<boolean> {
|
||||
/* insecure origin / permission — fall through */
|
||||
}
|
||||
|
||||
const ta = document.createElement('textarea');
|
||||
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.setAttribute('readonly', '');
|
||||
ta.style.position = 'fixed';
|
||||
@@ -95,10 +96,10 @@ export async function copyText(value: string): Promise<boolean> {
|
||||
host.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.setSelectionRange(0, ta.value.length);
|
||||
const ok = document.execCommand('copy');
|
||||
host.removeChild(ta);
|
||||
return ok;
|
||||
return document.execCommand('copy');
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
ta.remove();
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { useHookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
import { MainLayout } from '@/components/layout/main-layout';
|
||||
import { NAV_ITEMS } from '@/components/layout/sidebar';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { LowIntegrityWarning } from '@/components/low-integrity-warning';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
import { AppStateProvider, type AppResourceState } from '@/contexts/AppStateContext';
|
||||
import { KioskProvider } from '@/contexts/KioskContext';
|
||||
@@ -529,6 +530,7 @@ export function AppLayout() {
|
||||
</KioskProvider>
|
||||
</LayoutProvider>
|
||||
|
||||
<LowIntegrityWarning lowIntegrity={systemInfo?.runtime.lowIntegrity === true} />
|
||||
<ConfirmDialog
|
||||
open={!!unloadFailedAlert}
|
||||
onOpenChange={(open) => !open && dismissUnloadFailedAlert()}
|
||||
|
||||
@@ -461,6 +461,7 @@ export interface SystemInfo {
|
||||
};
|
||||
runtime: {
|
||||
pid: number;
|
||||
lowIntegrity: boolean;
|
||||
rss: number;
|
||||
heapTotal: number;
|
||||
heapUsed: number;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createApiClient } from '../src/lib/api/client';
|
||||
|
||||
const tokenStore = { load: () => 'test-token', save: () => undefined };
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('API response JSON', () => {
|
||||
it.each(['<html>proxy error</html>', '', 'null', '[]', '42'])(
|
||||
'rejects an invalid successful response instead of returning an empty list (%j)',
|
||||
async (body) => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status: 200 })));
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.processes.list()).rejects.toMatchObject({
|
||||
status: 502,
|
||||
code: 'INVALID_RESPONSE',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves the HTTP status when an error response is not JSON', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response('<html>unavailable</html>', {
|
||||
status: 503,
|
||||
statusText: 'Service Unavailable',
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.processes.list()).rejects.toMatchObject({
|
||||
status: 503,
|
||||
message: 'Service Unavailable',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not turn a failed JSON body read into successful empty data', async () => {
|
||||
const failure = new Error('response stream interrupted');
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: true, status: 200, json: () => Promise.reject(failure) }),
|
||||
);
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.processes.list()).rejects.toBe(failure);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { copyText } from '../src/lib/utils';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('copyText', () => {
|
||||
it('uses the clipboard API without creating a temporary element', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } });
|
||||
vi.stubGlobal('document', undefined);
|
||||
|
||||
await expect(copyText('hello')).resolves.toBe(true);
|
||||
expect(writeText).toHaveBeenCalledWith('hello');
|
||||
});
|
||||
|
||||
it.each(['success', 'rejected', 'focus throws', 'copy throws'])(
|
||||
'removes the temporary element after legacy copy: %s',
|
||||
async (outcome) => {
|
||||
const children = new Set<unknown>();
|
||||
const host = {
|
||||
appendChild: (child: unknown) => children.add(child),
|
||||
removeChild: (child: unknown) => children.delete(child),
|
||||
};
|
||||
const textarea = {
|
||||
value: '',
|
||||
style: {},
|
||||
setAttribute: vi.fn(),
|
||||
setSelectionRange: vi.fn(),
|
||||
focus: () => {
|
||||
if (outcome === 'focus throws') {
|
||||
throw new Error('focus unavailable');
|
||||
}
|
||||
},
|
||||
remove: () => children.delete(textarea),
|
||||
};
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: { writeText: vi.fn().mockRejectedValue(new Error('permission denied')) },
|
||||
});
|
||||
vi.stubGlobal('document', {
|
||||
body: host,
|
||||
createElement: () => textarea,
|
||||
querySelector: () => host,
|
||||
execCommand: () => {
|
||||
if (outcome === 'copy throws') {
|
||||
throw new Error('copy unavailable');
|
||||
}
|
||||
|
||||
return outcome === 'success';
|
||||
},
|
||||
});
|
||||
|
||||
await expect(copyText('hello')).resolves.toBe(outcome === 'success');
|
||||
expect(children.size).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
LOW_INTEGRITY_PERMANENT_KEY,
|
||||
LOW_INTEGRITY_SESSION_KEY,
|
||||
readLowIntegrityDismissed,
|
||||
saveLowIntegrityDismissed,
|
||||
} from '../src/lib/low-integrity-warning';
|
||||
|
||||
function storage() {
|
||||
const data = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key: string) => data.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
data.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let local = storage();
|
||||
let session = storage();
|
||||
beforeEach(() => {
|
||||
local = storage();
|
||||
session = storage();
|
||||
vi.stubGlobal('window', { localStorage: local, sessionStorage: session });
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('Low integrity warning', () => {
|
||||
it('keeps temporary dismissal across reads/reloads but not a new tab session', () => {
|
||||
expect(readLowIntegrityDismissed()).toBe(false);
|
||||
saveLowIntegrityDismissed('session');
|
||||
expect(session.getItem(LOW_INTEGRITY_SESSION_KEY)).toBe('1');
|
||||
expect(local.getItem(LOW_INTEGRITY_PERMANENT_KEY)).toBeNull();
|
||||
expect(readLowIntegrityDismissed()).toBe(true);
|
||||
expect(readLowIntegrityDismissed()).toBe(true);
|
||||
vi.stubGlobal('window', { localStorage: local, sessionStorage: storage() });
|
||||
expect(readLowIntegrityDismissed()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps permanent dismissal across new sessions', () => {
|
||||
saveLowIntegrityDismissed('permanent');
|
||||
vi.stubGlobal('window', { localStorage: local, sessionStorage: storage() });
|
||||
expect(readLowIntegrityDismissed()).toBe(true);
|
||||
expect(session.getItem(LOW_INTEGRITY_SESSION_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('honors session dismissal when local storage is blocked', () => {
|
||||
saveLowIntegrityDismissed('session');
|
||||
vi.stubGlobal('window', {
|
||||
get localStorage() {
|
||||
throw new Error('blocked');
|
||||
},
|
||||
sessionStorage: session,
|
||||
});
|
||||
expect(readLowIntegrityDismissed()).toBe(true);
|
||||
expect(() => saveLowIntegrityDismissed('permanent')).toThrow('blocked');
|
||||
});
|
||||
|
||||
it('does not claim to save permanent dismissal when storage writes fail', () => {
|
||||
vi.spyOn(local, 'setItem').mockImplementation(() => {
|
||||
throw new Error('quota');
|
||||
});
|
||||
expect(() => saveLowIntegrityDismissed('permanent')).toThrow('quota');
|
||||
expect(readLowIntegrityDismissed()).toBe(false);
|
||||
});
|
||||
|
||||
it('can read in server rendering without accessing browser storage', () => {
|
||||
vi.stubGlobal('window', undefined);
|
||||
expect(readLowIntegrityDismissed()).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user