diff --git a/docs/memory-audit.md b/docs/memory-audit.md new file mode 100644 index 0000000..0f96505 --- /dev/null +++ b/docs/memory-audit.md @@ -0,0 +1,31 @@ +# 内存占用审计(2026-11-29) + +## 范围与结论 + +本轮检查了 Reims-Go 的 Go 后端、React 前端、Guest Tools、QMP 截图和 VM 启停链路,并采样已运行的桌面应用,使用无磁盘 WHPX 虚拟机和 4K 图像分别测量 QEMU 启动占用与预览开销。用户的 macOS 虚拟机处于关机状态。 + +已确认并修复 Reims-Go 按 VM 生命周期无界保留的状态:缩略图锁、Guest Tools 注册与 WebDAV handler、进程采样、磁盘路径、绑核 PID、远程文本队列及其 worker。删除 VM 时立即回收;通过 CLI 或外部工具删除时,由 VM 轮询回收。日志和任务列表也有上限或过期清理。 + +本机 macOS VM 的配置与上次启动日志均记录了 8 GiB 客体内存。检查时 Windows 可用提交内存约 7.2 GiB,低于启动器对该 VM 要求的 9 GiB(含 1 GiB 余量)。QEMU 和 vGPU 在固定 macOS 图形负载下是否会持续增长,待验证。 + +## 测量与修复 + +- 在 macOS VM 关机时,每 15 秒采样一次,共 11 次。Reims-Go 主进程的私有提交为 59.9–60.5 MiB,其进程树中的 6 个 WebView2 进程合计 282.6–286.3 MiB。数值来自修复前已在运行的桌面程序。 +- 用本机便携运行时(`3731afd`)启动无磁盘、无网络的 WHPX 测试机,依次配置 512、1024、512 MiB 内存。各轮第 10 秒的 QEMU 私有提交为 537.2、1049.9、537.3 MiB,工作集为 46.8、46.8、46.9 MiB,三次 QMP 退出的进程退出码均为 0。此测试覆盖固件空载阶段。 +- 后台监视串口和 QEMU 日志时,旧实现遇到一直没有换行的输出会持续拼接并保留整行。现在每行暂存上限为 64 KiB,过长行跳到下一个换行,原始日志文件完整保留。 +- 前端会在已结束任务超过 10 分钟后清理任务记录及通知去重标记,与后端保留时间一致。运行中的任务持续显示。 +- 用相同的 3840×2160 PPM 文件生成宽 640 像素的 JPEG,各测 8 帧。`BenchmarkPreview4K` 在原版本(`704f68c`)每帧分配 56.4 MiB,按行缩放后为 1.04 MiB,下降约 98%。这是单帧累计 Go 分配量。手动复制截图仍保留全分辨率,并按行将 RGB 转为 RGBA。 +- VM 详情原先随每次宿主状态刷新重新调用 `reims-ctl show`,包含窗口可见时每 10 秒一次的轮询。现在只随选择、运行/过渡状态和显式 `reims:state-changed` 事件重取,配置保存后的刷新语义保持不变。 +- Go 的 RSS 在 GC 后不必然立即下降;只有保留对象持续增长才证明泄漏。不要为了压低任务管理器数字在热路径加入 `debug.FreeOSMemory`。 + +## 实机复测建议 + +使用同一 VM、固定客体负载和同一分辨率,在启动稳定后、1 小时、4 小时分别记录 QEMU 与 Reims-Go 进程树的 Private Bytes、Working Set 和句柄数。期间分别覆盖打开/隐藏 Reims-Go 窗口、切换 VM、截图、复制大图片和客体睡眠唤醒。 + +若 QEMU Private Bytes 在固定负载下持续线性增长,再按运行时 manifest 中的 commit 和补丁进行上游定位。既有 `qemu-win32-coroutine-fiber-commit.patch` 将每个协程栈初始提交从 1 MiB 降为 64 KiB,但仍是待真机验证的补丁,且不会改变 Guest RAM 的基础占用。 + +## 验证 + +- `go test ./...`:通过。 +- `pnpm --dir frontend run build`:通过;仅有既存的 Vite 大 chunk 提示。 +- 临时启用 CGO 并使用本机 MSYS2 CLANG64,`go test -race ./...` 通过。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 87a4125..b8613e4 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,30 +1,37 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { CreateWizard, WizardDraft } from './components/CreateWizard' -import { AffinityDialog } from './components/AffinityDialog' +import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' +import type { WizardDraft } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' -import { HostView } from './components/HostView' -import { AppSettingsPage, ThemeMode } from './components/AppSettingsPage' +import type { ThemeMode } from './components/AppSettingsPage' import { LogPanel, LogTab } from './components/LogPanel' -import { SettingsModal } from './components/SettingsModal' import { TitleMenus } from './components/TitleMenus' -import { Setup } from './components/Setup' import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' -import { InstallersPage } from './components/InstallersPage' import { VMAction, VMPage } from './components/VMPage' import { I18nKey, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { LogLine, appendLog } from './lib/logs' -import { currentTask, upsertTask } from './lib/tasks' -import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail, VMStats } from './types' +import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks' +import { latestVMStats } from './lib/vmStats' +import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail } from './types' import { Tip, TooltipProvider } from './ui/controls' import { Toaster, useToasts } from './ui/toast' import { api, events } from './wails' import { OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime' +// Opened on demand, so each is its own chunk and stays out of the startup +// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and +// the Engine / Installers / Settings pages. +const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard }))) +const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal }))) +const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog }))) +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 AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) + const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '') const failKey: Record = { @@ -54,7 +61,7 @@ export const App: React.FC = () => { const [state, setState] = useState(null) const [selected, setSelected] = useState(HOST_ID) const [detail, setDetail] = useState(null) - const [vmStats, setVmStats] = useState(null) + const [detailRevision, setDetailRevision] = useState(0) const [showWizard, setShowWizard] = useState(false) const [wizardDraft, setWizardDraft] = useState(null) const [showSettings, setShowSettings] = useState(false) @@ -120,12 +127,12 @@ export const App: React.FC = () => { logsOpenRef.current = logsOpen const [taskMap, setTaskMap] = useState>({}) const onTaskRef = useRef<(task: Task) => void>(() => {}) - const notifiedTasks = useRef(new Set()) + const notifiedTasks = useRef(new Map()) const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null) const toasts = useToasts() - const refresh = useCallback(async () => { + const refresh = useCallback(async (reloadDetail = false) => { try { const s = await api.GetState() setState(s) @@ -135,6 +142,7 @@ export const App: React.FC = () => { if ((s.vms ?? []).some((v) => v.name === cur)) return cur return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID }) + if (reloadDetail) setDetailRevision((revision) => revision + 1) } catch (e) { setLoadError(errText(e)) } @@ -142,7 +150,7 @@ export const App: React.FC = () => { useEffect(() => { refresh() - const offState = events.onStateChanged(() => { refresh() }) + const offState = events.onStateChanged(() => { refresh(true) }) // Logs never pop the panel open (docs/ui-redesign.md §5.2); errors only bump a badge. const offLog = events.onLog((entry) => { setLogLines((prev) => { @@ -162,6 +170,11 @@ export const App: React.FC = () => { // Keep host telemetry (memory load, free disk) fresh while the window is visible. const hostTimer = window.setInterval(() => { if (!document.hidden) void refresh() + const cutoff = Date.now() - finishedTaskTTL + setTaskMap((prev) => pruneFinishedTasks(prev, cutoff)) + for (const [id, updatedAt] of notifiedTasks.current) { + if (updatedAt < cutoff) notifiedTasks.current.delete(id) + } }, 10000) return () => { offState(); offLog(); offTask(); window.clearInterval(hostTimer) } }, [refresh]) @@ -173,9 +186,9 @@ export const App: React.FC = () => { : undefined useEffect(() => { - if (!selectedVM) { setDetail(null); setVmStats(null); return } + if (!selectedVM) { setDetail(null); return } api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null)) - }, [selectedVM?.name, state]) + }, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM?.name ?? ''], detailRevision]) // Display names (the VM's note, .reims-go-note): shown in place of the VM's // name in the sidebar and page title; the name itself stays the identifier. @@ -192,17 +205,8 @@ export const App: React.FC = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [vmNamesKey]) - useEffect(() => { - if (!selectedVM) { setVmStats(null); return } - let live = true - const vmName = selectedVM.name - const sample = () => { - api.GetVMStats(vmName).then((st) => { if (live) setVmStats(st) }).catch(() => {}) - } - sample() - const timer = window.setInterval(sample, 3000) - return () => { live = false; window.clearInterval(timer) } - }, [selectedVM?.name, selectedVM?.state]) + // Live VM stats are polled by lib/vmStats.ts and read where they are shown + // (VMPage), so a 3-second tick no longer re-renders the whole App. const locale: Locale = state?.config.locale ?? 'zh-CN' const tr = (k: I18nKey, v?: Record) => t(locale, k, v) @@ -214,7 +218,7 @@ export const App: React.FC = () => { // Toast once per finished download; only live events reach here, not the seed list. const notify = task.kind === 'installer-download' || task.kind === 'recovery-download' || task.kind === 'runtime-install' if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) { - notifiedTasks.current.add(task.id) + notifiedTasks.current.set(task.id, task.updated_at) const isRuntime = task.kind === 'runtime-install' const isRecovery = task.kind === 'recovery-download' if (task.status === 'done') { @@ -238,10 +242,10 @@ export const App: React.FC = () => { api.InstallRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e)) } const setChannel = (alpha: boolean) => { - api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e)) + api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e)) } const setSource = (source: RuntimeSource) => { - api.SetRuntimeSource(source).then(refresh).catch((e) => fail(tr('failGeneric'), e)) + api.SetRuntimeSource(source).then(() => refresh()).catch((e) => fail(tr('failGeneric'), e)) } const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) } const importRuntime = async () => { @@ -648,6 +652,7 @@ export const App: React.FC = () => { {showSetup && state ? ( + { onCancelTask={cancelTask} onImportRuntime={importRuntime} /> + ) : (
{
+ {!state ? (
{loadError ?
{loadError}
: …} @@ -702,7 +709,6 @@ export const App: React.FC = () => { onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))} state={effectiveState} detail={detail} - stats={vmStats} host={state.host} pending={pending} busyAction={busy[selectedVM.name]} @@ -764,6 +770,7 @@ export const App: React.FC = () => { onCancelTask={cancelTask} /> )} +
@@ -796,6 +803,7 @@ export const App: React.FC = () => { )} {showWizard && state && ( + { onClose={() => { setShowWizard(false); setWizardDraft(null) }} onSubmit={submitCreate} /> + )} {showSettings && state && detail && ( + { refresh() }} /> + )} {affinityTarget && state && ( + { refresh() }} /> + )} {deleteTarget && ( @@ -877,7 +890,7 @@ export const App: React.FC = () => { setSendTextTarget(null)} onConfirm={(text) => { const target = sendTextTarget diff --git a/frontend/src/components/LogPanel.tsx b/frontend/src/components/LogPanel.tsx index 67b24c8..e234de6 100644 --- a/frontend/src/components/LogPanel.tsx +++ b/frontend/src/components/LogPanel.tsx @@ -56,6 +56,15 @@ function useStickToBottom(dep: unknown, active: boolean) { return { ref, stuck, onScroll, jump } } +const LogRow = React.memo(({ line }: { line: LogLine }) => ( +
+ {line.ts} + {line.source} + {line.line} +
+)) +LogRow.displayName = 'LogRow' + const LOG_HEIGHT_KEY = 'reims-go-log-height' const DEFAULT_LOG_HEIGHT = 240 const MIN_LOG_HEIGHT = 120 @@ -77,6 +86,10 @@ export const LogPanel: React.FC = ({ return true }) }, [lines, errorsOnly, q]) + // Same element list while the lines are unchanged, so an App re-render for + // something else doesn't rebuild up to MAX_LOG_LINES rows; a new line renders + // just its own row (LogRow is memoised on the line object). + const rows = useMemo(() => filteredLines.map((l) => ), [filteredLines]) const filteredText = useMemo(() => { const raw = tab === 'serial' ? serialText : qemuText @@ -302,13 +315,7 @@ export const LogPanel: React.FC = ({ {tab === 'app' ? (filteredLines.length === 0 ? {tr('logsEmpty')} - : filteredLines.map((l) => ( -
- {l.ts} - {l.source} - {l.line} -
- ))) + : rows) : (filteredText || {tr('logsEmpty')})} {!stuck && ( diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index a788128..1914c52 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -4,7 +4,7 @@ import React, { useState } from 'react' import { I18nKey, t } from '../i18n' import { Locale } from '../types' import { Tip } from '../ui/controls' -import { ThemeMode } from './AppSettingsPage' +import type { ThemeMode } from './AppSettingsPage' import { HOST_ID, INSTALLERS_ID, SETTINGS_ID } from './Sidebar' import { VMAction } from './VMPage' diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 5ce6869..e9d3a4d 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -44,7 +44,8 @@ import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, guestLangLabel, parseMemoryGB, pendingChangeText, splitLangLabel, sshCommand, } from '../lib/format' -import { DiskSnapshot, HostReport, Locale, PendingChange, VMDetail, VMStats, VMThumbnail } from '../types' +import { useVMStats } from '../lib/vmStats' +import { DiskSnapshot, HostReport, Locale, PendingChange, VMDetail, VMThumbnail } from '../types' import { api } from '../wails' import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls' import { Switch } from '../ui/settings' @@ -86,7 +87,6 @@ interface Props { onDisplayNameSaved: (displayName: string) => void state: string detail: VMDetail | null - stats: VMStats | null host: HostReport pending: PendingChange[] busyAction?: VMAction @@ -121,12 +121,14 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, displayName, onDisplayNameSaved, state, detail, stats, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, + locale, name, displayName, onDisplayNameSaved, state, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined const running = state === 'running' const transitioning = state === 'starting' || state === 'stopping' + // Polled here rather than in App so each tick re-renders only this page. + const stats = useVMStats(name, running) // Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM // runs, otherwise the last frame saved. Skipped while this window is hidden; diff --git a/frontend/src/lib/tasks.ts b/frontend/src/lib/tasks.ts index 81f4bd0..e418a45 100644 --- a/frontend/src/lib/tasks.ts +++ b/frontend/src/lib/tasks.ts @@ -1,6 +1,19 @@ import { t } from '../i18n' import { Locale, Task } from '../types' +// Match the finished-task retention period in internal/app/tasks.go. +export const finishedTaskTTL = 10 * 60 * 1000 + +export function pruneFinishedTasks(tasks: Record, cutoff: number): Record { + let next = tasks + for (const task of Object.values(tasks)) { + if (task.status === 'running' || task.updated_at >= cutoff) continue + if (next === tasks) next = { ...tasks } + delete next[task.id] + } + return next +} + /** Insert or replace a task by id; events can arrive out of order, keep the newest. */ export function upsertTask(prev: Record, task: Task): Record { const cur = prev[task.id] diff --git a/frontend/src/lib/vmStats.ts b/frontend/src/lib/vmStats.ts new file mode 100644 index 0000000..e53f750 --- /dev/null +++ b/frontend/src/lib/vmStats.ts @@ -0,0 +1,85 @@ +import { useEffect, useState } from 'react' +import { VMStats } from '../types' +import { api } from '../wails' + +// Shared VM stats poller (stats_flow.go). Components that show stats +// subscribe with useVMStats, so a tick re-renders only them, not the whole +// App. One timer per VM however many subscribe; it pauses while the window +// is hidden and samples once on return. + +const RUNNING_MS = 3000 +// A stopped VM only changes disk usage, so it is sampled rarely. +const STOPPED_MS = 30000 + +interface Entry { + subs: Set<(s: VMStats) => void> + running: boolean + last: VMStats | null + timer?: number +} + +const entries = new Map() + +function sample(name: string) { + api.GetVMStats(name) + .then((s) => { + const e = entries.get(name) + if (!e) return + e.last = s + e.subs.forEach((f) => f(s)) + }) + .catch(() => {}) +} + +function schedule(name: string, e: Entry) { + if (e.timer) window.clearInterval(e.timer) + e.timer = undefined + if (document.hidden || e.subs.size === 0) return + e.timer = window.setInterval(() => sample(name), e.running ? RUNNING_MS : STOPPED_MS) +} + +if (typeof document !== 'undefined') { + document.addEventListener('visibilitychange', () => { + entries.forEach((e, name) => { + if (!document.hidden && e.subs.size > 0) sample(name) + schedule(name, e) + }) + }) +} + +/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */ +export function latestVMStats(name: string | undefined | null): VMStats | null { + return name ? entries.get(name)?.last ?? null : null +} + +/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */ +export function useVMStats(name: string | null, running: boolean): VMStats | null { + const [stats, setStats] = useState(() => latestVMStats(name)) + + useEffect(() => { + if (!name) { setStats(null); return } + let e = entries.get(name) + if (!e) { + e = { subs: new Set(), running, last: null } + entries.set(name, e) + } + setStats(e.last) + const sub = (s: VMStats) => setStats(s) + e.subs.add(sub) + // A state change (start/stop) samples at once and re-paces the timer. + e.running = running + sample(name) + schedule(name, e) + return () => { + const cur = entries.get(name) + if (!cur) return + cur.subs.delete(sub) + if (cur.subs.size === 0) { + if (cur.timer) window.clearInterval(cur.timer) + entries.delete(name) + } + } + }, [name, running]) + + return stats +} diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9610a97..bf1b94e 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -50,8 +50,9 @@ h1, h2, h3, p { margin: 0; } height: var(--titlebar-h); flex-shrink: 0; position: relative; z-index: 10; display: flex; align-items: center; justify-content: space-between; padding-left: var(--sp-4); + /* No backdrop blur: the bar is opaque, so blurring behind it showed nothing + and still cost a GPU compositing layer (the GPU is shared with the VM). */ background: var(--surface-chrome); - backdrop-filter: var(--blur-chrome); border-bottom: 1px solid var(--border); user-select: none; --wails-draggable: drag; } @@ -133,8 +134,8 @@ h1, h2, h3, p { margin: 0; } flex: 1; min-height: 0; display: flex; flex-direction: column; gap: var(--sp-1); padding: 10px 8px; overflow-y: auto; overscroll-behavior: contain; + /* Translucent over a fixed gradient: a backdrop blur would look the same. */ background: var(--surface-sidebar); - backdrop-filter: var(--blur-chrome); border: 1px solid var(--surface-sidebar-border); border-radius: 14px; box-shadow: var(--surface-sidebar-shadow); @@ -647,7 +648,6 @@ h1, h2, h3, p { margin: 0; } flex-shrink: 0; display: flex; flex-direction: column; position: relative; z-index: 10; border-top: 1px solid var(--border); background: var(--surface-statusbar); - backdrop-filter: var(--blur-chrome); } .log-resize-handle { position: absolute; top: -3px; left: 0; right: 0; height: 7px; z-index: 5;