diff --git a/frontend/scripts/check-ui-contract.mjs b/frontend/scripts/check-ui-contract.mjs index 325738d..63ab765 100644 --- a/frontend/scripts/check-ui-contract.mjs +++ b/frontend/scripts/check-ui-contract.mjs @@ -23,22 +23,22 @@ const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS') const slots = extractArray('UI_CONTRACT_SLOTS') const tokens = extractArray('UI_CONTRACT_TOKENS') -// Collect all TSX source text to verify every declared part class is actually emitted (§5.1). -function readAllTsx(dir) { +// Collect all React component TSX source text (excluding contract/SDK/theme helpers) +// and verify every declared part class is emitted as a distinct class token (§5.1, M17). +function readComponentTsx(dir) { let buf = '' for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name) - if (entry.isDirectory()) buf += readAllTsx(full) - else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) buf += '\n' + fs.readFileSync(full, 'utf8') + if (entry.isDirectory()) buf += readComponentTsx(full) + else if (entry.name.endsWith('.tsx')) buf += '\n' + fs.readFileSync(full, 'utf8') } return buf } -const allSrc = readAllTsx(srcDir) +const allTsx = readComponentTsx(srcDir) const missingParts = parts.filter((p) => { - // Exclude the definition file itself by checking for usage outside ui-contract.ts. - const withoutContract = allSrc.replace(contractSrc, '') - return !withoutContract.includes(p) + const re = new RegExp(`(? !tokensCss.includes(`${tk}:`)) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 40fe53f..04eebc7 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,7 +8,7 @@ import { SendTextDialog } from './components/SendTextDialog' import type { ThemeMode } from './components/AppSettingsPage' import { LogPanel, LogTab } from './components/LogPanel' import { TitleMenus } from './components/TitleMenus' -import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' +import { HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' import { VMAction, VMPage } from './components/VMPage' import { I18nKey, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' @@ -31,6 +31,7 @@ const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup }))) const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView }))) const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage }))) +const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage }))) const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '') @@ -88,11 +89,24 @@ export const App: React.FC = () => { const [reducedMotion, setReducedMotion] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches, ) - const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode const [pluginUI, setPluginUI] = useState(null) const [activeThemePayload, setActiveThemePayload] = useState(null) const [themeRevision, setThemeRevision] = useState(0) + const activeThemeContrib = activeThemePayload?.theme + ?? (pluginUI?.themes ?? []).find((th) => th.id === (activeThemePayload?.theme_id || 'builtin.theme.default')) + ?? null + const themeAppearanceCap: 'light' | 'dark' | 'both' = + pluginUI === null + ? 'both' + : activeThemeContrib + ? (activeThemeContrib.appearance === 'light' || activeThemeContrib.appearance === 'dark' ? activeThemeContrib.appearance : 'both') + : 'light' + const canLight = themeAppearanceCap === 'both' || themeAppearanceCap === 'light' + const canDark = themeAppearanceCap === 'both' || themeAppearanceCap === 'dark' + const theme: 'light' | 'dark' = !canDark ? 'light' : !canLight ? 'dark' : (themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode) + const effectiveThemeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : themeMode + useEffect(() => { document.documentElement.dataset.theme = theme document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full' @@ -122,7 +136,10 @@ export const App: React.FC = () => { } catch {} } - const toggleTheme = () => setThemeMode(theme === 'light' ? 'dark' : 'light') + const toggleTheme = () => { + if (!canLight || !canDark) return + setThemeMode(theme === 'light' ? 'dark' : 'light') + } // Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user. const [sidebarOpen, setSidebarOpen] = useState(() => { @@ -154,7 +171,7 @@ export const App: React.FC = () => { setState(s) setLoadError('') setSelected((cur) => { - if (cur === HOST_ID || cur === INSTALLERS_ID || cur === SETTINGS_ID) return cur + if (cur === HOST_ID || cur === INSTALLERS_ID || cur === PLUGINS_ID || cur === SETTINGS_ID) return cur if ((s.vms ?? []).some((v) => v.name === cur)) return cur return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID }) @@ -166,21 +183,21 @@ export const App: React.FC = () => { useEffect(() => { refresh() - const offState = events.onStateChanged(() => { refresh(true) }) + events.emitUIPong() + const offPing = events.onUIPing(() => { events.emitUIPong() }) + const offState = events.onStateChanged(() => { + refresh(true) + setThemeRevision((r) => r + 1) + }) // Logs never pop the panel open (docs/design-guidelines.md §7.3); errors only bump a badge. const offLog = events.onLog((entry) => { - setLogLines((prev) => { - const next = appendLog(prev, entry) - const last = next[next.length - 1] - if (!logsOpenRef.current && last.level === 'error' && last !== prev[prev.length - 1]) { - setUnseenErrors((n) => n + 1) - } - return next - }) + if (!entry || typeof entry !== 'object') return + const lineText = typeof entry.line === 'string' ? entry.line : String(entry.line ?? '') + if (!logsOpenRef.current && /\b(error|failed|fatal|panic)\b/i.test(lineText)) { + setUnseenErrors((n) => n + 1) + } + setLogLines((prev) => appendLog(prev, entry)) }) - api.GetState().then(async (s) => { - setState(s) - }).catch(() => {}) api.GetPluginUIContributions().then(setPluginUI).catch(() => {}) api.GetActiveTheme().then(setActiveThemePayload).catch(() => {}) // Tasks: seed from the backend, then follow events. @@ -188,6 +205,13 @@ export const App: React.FC = () => { setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev)) }).catch(() => {}) const offTask = events.onTask((task) => onTaskRef.current(task)) + const onVisibility = () => { + if (!document.hidden) { + events.emitUIPong() + void refresh() + } + } + document.addEventListener('visibilitychange', onVisibility) // Keep host telemetry (memory load, free disk) fresh while the window is visible. const hostTimer = window.setInterval(() => { if (!document.hidden) void refresh() @@ -197,12 +221,19 @@ export const App: React.FC = () => { if (updatedAt < cutoff) notifiedTasks.current.delete(id) } }, 10000) - return () => { offState(); offLog(); offTask(); window.clearInterval(hostTimer) } + return () => { + offPing() + offState() + offLog() + offTask() + document.removeEventListener('visibilitychange', onVisibility) + window.clearInterval(hostTimer) + } }, [refresh]) const vms = state?.vms ?? [] const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length - const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== SETTINGS_ID + const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== PLUGINS_ID && selected !== SETTINGS_ID ? vms.find((v) => v.name === selected) : undefined @@ -306,7 +337,7 @@ export const App: React.FC = () => { const showSetup = !!state && (state.needs_setup || setupStage === 'runtime') // UI Contract v1 read-only document state attributes (§5.1). - const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === SETTINGS_ID ? 'settings' : 'vm' + const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : 'vm' const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0 const hasAnyError = unseenErrors > 0 || !!loadError const uiStateRef = useRef({ @@ -718,7 +749,9 @@ export const App: React.FC = () => { onToggleSidebar={toggleSidebar} logsOpen={logsOpen} onToggleLogs={toggleLogs} - themeMode={themeMode} + themeMode={effectiveThemeMode} + canLight={canLight} + canDark={canDark} onThemeMode={setThemeMode} vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null} onNewVM={openWizard} @@ -731,16 +764,18 @@ export const App: React.FC = () => { /> )}
e.stopPropagation()}> - - - + {canLight && canDark && ( + + + + )}
@@ -752,7 +787,7 @@ export const App: React.FC = () => { {state?.safe_mode && (
{tr('safeModeBanner')} -
@@ -791,6 +826,7 @@ export const App: React.FC = () => { onNew={openWizard} onVMContextAction={onSidebarContextAction} downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')} + safeMode={state?.safe_mode} />
@@ -809,6 +845,15 @@ export const App: React.FC = () => { onError={fail} onToast={(title) => toasts.push({ kind: 'ok', title })} /> + ) : selected === PLUGINS_ID ? ( + setThemeRevision((r) => r + 1)} + /> ) : selectedVM ? ( { setThemeRevision((r) => r + 1)} onSetLocale={setLang} onRefresh={refresh} onError={fail} diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 9906d33..32c4104 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -1,5 +1,5 @@ import { Download } from 'lucide-react' -import React, { Suspense, lazy, useEffect, useState } from 'react' +import React, { useEffect, useState } from 'react' import { I18nKey, t } from '../i18n' import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations' import { AppState, AppUpdateInfo, Locale } from '../types' @@ -7,24 +7,22 @@ import { Button } from '../ui/controls' import { Segmented, Switch } from '../ui/settings' import { api } from '../wails' -const PluginsSection = lazy(() => import('./PluginsSection').then((m) => ({ default: m.PluginsSection }))) - export type ThemeMode = 'light' | 'dark' | 'system' interface Props { state: AppState locale: Locale themeMode: ThemeMode - appearance?: 'light' | 'dark' + canLight?: boolean + canDark?: boolean onThemeMode: (mode: ThemeMode) => void - onThemeChanged?: () => void onSetLocale: (l: Locale) => void onRefresh: () => void onError: (title: string, e: unknown) => void } export const AppSettingsPage: React.FC = ({ - state, locale, themeMode, appearance = 'light', onThemeMode, onThemeChanged, onSetLocale, onRefresh, onError, + state, locale, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const { host, config, optimizations } = state @@ -124,16 +122,21 @@ export const AppSettingsPage: React.FC = ({
{tr('settingsAppearance')}
-
{tr('themeLabel')}
+
+
{tr('themeLabel')}
+ {(!canDark || !canLight) && ( +
{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}
+ )} +
@@ -155,17 +158,6 @@ export const AppSettingsPage: React.FC = ({
- - - -
{tr('settingsAbout')}
diff --git a/frontend/src/components/ErrorBoundary.tsx b/frontend/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..c0c987b --- /dev/null +++ b/frontend/src/components/ErrorBoundary.tsx @@ -0,0 +1,96 @@ +import React from 'react' +import { events } from '../wails' + +interface State { + error: Error | null + stack: string +} + +/** + * Top-level React error boundary: prevents any uncaught render/lifecycle error + * from unmounting the entire tree into an unrecoverable blank white screen, + * reports the stack trace to the Go backend log, and offers a one-click reload. + */ +export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, State> { + state: State = { error: null, stack: '' } + + static getDerivedStateFromError(error: Error): Partial { + return { error } + } + + componentDidCatch(error: Error, info: React.ErrorInfo): void { + const stack = [error.stack, info.componentStack].filter(Boolean).join('\n').trim() + this.setState({ stack }) + events.emitUIError(`ReactErrorBoundary: ${error.message}\n${stack.slice(0, 1500)}`) + } + + render(): React.ReactNode { + const { error, stack } = this.state + if (!error) return this.props.children + + const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh') + return ( +
+
+

+ {isZh ? '界面发生异常' : 'Interface encountered an error'} +

+

+ {isZh + ? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。' + : 'An unexpected UI error occurred. Running VMs and background services are unaffected.'} +

+
+            {error.message || String(error)}
+            {stack ? `\n\n${stack}` : ''}
+          
+
+ +
+
+
+ ) + } +} diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx new file mode 100644 index 0000000..1e6c2f9 --- /dev/null +++ b/frontend/src/components/PluginsPage.tsx @@ -0,0 +1,713 @@ +import { + AlertTriangle, BadgeCheck, Clipboard, Code2, Cpu, Disc3, FolderOpen, Keyboard, + Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw, Search, + Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2, +} from 'lucide-react' +import React, { useEffect, useMemo, useState } from 'react' +import { I18nKey, t } from '../i18n' +import { + ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, +} from '../types' +import { Button, IconButton, Tip } from '../ui/controls' +import { Modal } from '../ui/dialog' +import { PopupSelect, Switch } from '../ui/settings' +import { api } from '../wails' +import { PluginPanelFrame } from './PluginPanelFrame' +import { SchemaForm, locText } from './SchemaForm' + +// Search only earns its space once the list is long enough to scan. +const SEARCH_THRESHOLD = 12 + +interface Props { + locale: Locale + appearance: 'light' | 'dark' + safeMode?: boolean + onRefresh: () => void + onError: (title: string, e: unknown) => void + onThemeChanged?: () => void +} + +interface PluginVisual { + tone: string + icon: React.ReactNode +} + +function resolvePluginVisual(p: PluginInfo): PluginVisual { + const id = p.id.toLowerCase() + const perms = new Set((p.permissions ?? []).map((x) => x.name)) + if (id.includes('theme') || perms.has('ui:script')) { + return { tone: 'purple', icon: